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

IJHack / QtPass / 44948554706

21 Nov 2026 08:52PM UTC coverage: 94.716% (+0.03%) from 94.69%
44948554706

Pull #2299

github

web-flow
Merge 4f708528f into b0b2c94ed
Pull Request #2299: Add password: do not size the folder picker to every folder path

24 of 24 new or added lines in 1 file covered. (100.0%)

95 existing lines in 3 files now uncovered.

9554 of 10087 relevant lines covered (94.72%)

2577.64 hits per line

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

98.44
/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 <QTextStream>
29
#include <algorithm>
30
#include <array>
31
#include <optional>
32
#include <utility>
33

34
#include "qtpasslogging.h"
35

36
using Enums::GIT_INIT;
37
using Enums::GIT_PULL;
38
using Enums::GIT_PUSH;
39
using Enums::GPG_GENKEYS;
40
using Enums::PASS_COPY;
41
using Enums::PASS_INIT;
42
using Enums::PASS_INSERT;
43
using Enums::PASS_MOVE;
44
using Enums::PASS_REMOVE;
45
using Enums::PASS_SHOW;
46

47
namespace {
48
auto fallbackCharset(const QString &input, const QString &fallback) -> QString {
49
  return input.isEmpty() ? fallback : input;
1,625 ✔
50
}
51

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

62
Pass::Pass() : env(QProcessEnvironment::systemEnvironment()) {
414 ✔
63
  connect(&exec, &Executor::finished, this, &Pass::finished);
414 ✔
64
  connect(&exec, &Executor::error, this, &Pass::finished);
414 ✔
65

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

114
void Pass::executeWrapper(PROCESS id, const QString &app,
2 ✔
115
                          const QStringList &args, bool readStdout,
116
                          bool readStderr) {
117
  executeWrapper(id, app, args, QString(), readStdout, readStderr);
2 ✔
118
}
2 ✔
119

120
void Pass::executeWrapper(PROCESS id, const QString &app,
339 ✔
121
                          const QStringList &args, QString input,
122
                          bool readStdout, bool readStderr) {
123
  beforeExecute(id);
339 ✔
124
  qCDebug(lcQtPass) << app << loggableArgs(args);
339 ✔
125
  exec.execute(id, m_settings.passStore, app, args, std::move(input),
339 ✔
126
               readStdout, readStderr);
127
}
339 ✔
128

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

157
void Pass::beforeExecute(PROCESS /*id*/) {}
73 ✔
158

159
void Pass::init(const AppSettings &settings) {
828 ✔
160
  m_settings = settings;
828 ✔
161
#ifdef __APPLE__
162
  // If it exists, prepend gpgtools to PATH
163
  if (QFile(QStringLiteral("/usr/local/MacGPG2/bin")).exists())
164
    env.insert(QStringLiteral("PATH"),
165
               QStringLiteral("/usr/local/MacGPG2/bin:") +
166
                   env.value(QStringLiteral("PATH")));
167
  // Add missing /usr/local/bin (exact component match, no leading colon)
168
  const QString currentPath = env.value(QStringLiteral("PATH"));
169
  if (!currentPath.split(':', Qt::SkipEmptyParts)
170
           .contains(QStringLiteral("/usr/local/bin"))) {
171
    env.insert(QStringLiteral("PATH"),
172
               currentPath.isEmpty()
173
                   ? QStringLiteral("/usr/local/bin")
174
                   : QStringLiteral("/usr/local/bin:") + currentPath);
175
  }
176
#endif
177

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

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

274
bool Pass::gpgSupportsEd25519(const QString &gpgExecutable) {
34 ✔
275
  const QString exe =
276
      gpgExecutable.isEmpty() ? QStringLiteral("gpg") : gpgExecutable;
34 ✔
277
  QString out, err;
34 ✔
278
  if (Executor::executeBlocking(exe, {"--version"}, &out, &err) != 0) {
136 ✔
279
    return false;
280
  }
281
  QRegularExpression versionRegex(R"(gpg \(GnuPG\) (\d+)\.(\d+))");
32 ✔
282
  QRegularExpressionMatch match = versionRegex.match(out);
32 ✔
283
  if (!match.hasMatch()) {
32 ✔
284
    return false;
285
  }
286
  int major = match.captured(1).toInt();
31 ✔
287
  int minor = match.captured(2).toInt();
31 ✔
288
  return major > 2 || (major == 2 && minor >= 1);
31 ✔
289
}
32 ✔
290

291
// ed25519 (GnuPG 2.1+) generates much faster than RSA.
292
QString Pass::getDefaultKeyTemplate(const QString &gpgExecutable) {
30 ✔
293
  if (gpgSupportsEd25519(gpgExecutable)) {
30 ✔
294
    return QStringLiteral("%echo Generating a default key\n"
27 ✔
295
                          "Key-Type: EdDSA\n"
296
                          "Key-Curve: Ed25519\n"
297
                          "Subkey-Type: ECDH\n"
298
                          "Subkey-Curve: Curve25519\n"
299
                          "Name-Real: \n"
300
                          "Name-Comment: QtPass\n"
301
                          "Name-Email: \n"
302
                          "Expire-Date: 0\n"
303
                          "%no-protection\n"
304
                          "%commit\n"
305
                          "%echo done");
306
  }
307
  return QStringLiteral("%echo Generating a default key\n"
3 ✔
308
                        "Key-Type: RSA\n"
309
                        "Subkey-Type: RSA\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

319
namespace {
320
auto resolveWslGpgconfPath(const QString &lastPart) -> QString {
8 ✔
321
  qsizetype lastSep = lastPart.lastIndexOf('/');
8 ✔
322
  if (lastSep < 0) {
8 ✔
323
    lastSep = lastPart.lastIndexOf('\\');
5 ✔
324
  }
325
  if (lastSep >= 0) {
5 ✔
326
    return lastPart.left(lastSep + 1) + "gpgconf";
6 ✔
327
  }
328
  return QStringLiteral("gpgconf");
5 ✔
329
}
330

331
QString findGpgconfInGpgDir(const QString &gpgPath) {
8 ✔
332
  QFileInfo gpgInfo(gpgPath);
8 ✔
333
  if (!gpgInfo.isAbsolute()) {
8 ✔
334
    return {};
1 ✔
335
  }
336

337
  QDir dir(gpgInfo.absolutePath());
7 ✔
338

339
#ifdef Q_OS_WIN
340
  QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
341
  if (candidateExe.isExecutable()) {
342
    return candidateExe.filePath();
343
  }
344
#endif
345

346
  QFileInfo candidate(dir.filePath("gpgconf"));
7 ✔
347
  if (candidate.isExecutable()) {
7 ✔
348
    return candidate.filePath();
5 ✔
349
  }
350
  return {};
2 ✔
351
}
8 ✔
352

353
} // namespace
354

355
auto Pass::resolveGpgconfCommand(const QString &gpgPath)
22 ✔
356
    -> ResolvedGpgconfCommand {
357
  if (gpgPath.trimmed().isEmpty()) {
22 ✔
358
    return {"gpgconf", {}};
359
  }
360

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

372
  const QStringList parts = QProcess::splitCommand(gpgPath);
12 ✔
373
  if (parts.isEmpty()) {
12 ✔
374
    return {"gpgconf", {}};
375
  }
376
  const QString first = parts.first();
377
  if (QFileInfo(first).fileName().compare("wsl", Qt::CaseInsensitive) == 0 ||
33 ✔
378
      QFileInfo(first).fileName().compare("wsl.exe", Qt::CaseInsensitive) ==
30 ✔
379
          0) {
380
    return {"gpgconf", {}};
381
  }
382

383
  if (!first.contains('/') && !first.contains('\\')) {
9 ✔
384
    return {"gpgconf", {}};
385
  }
386

387
  QString gpgconfPath = findGpgconfInGpgDir(first);
8 ✔
388
  if (!gpgconfPath.isEmpty()) {
8 ✔
389
    return {gpgconfPath, {}};
5 ✔
390
  }
391

392
  return {"gpgconf", {}};
393
}
22 ✔
394

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

412
  // A stale gpg-agent holding the key database lock causes "database locked"
413
  // timeouts during key generation.
414
  ResolvedGpgconfCommand resolvedGpgconf = resolveGpgconfCommand(gpgPath);
2 ✔
415
  QStringList killArgs = resolvedGpgconf.arguments;
416
  killArgs << "--kill";
2 ✔
417
  killArgs << "gpg-agent";
2 ✔
418
  // Use same environment as key generation to target correct gpg-agent
419
  if (Executor::executeBlocking(env, resolvedGpgconf.program, killArgs) != 0) {
2 ✔
420
    qCWarning(lcQtPass) << "Failed to kill gpg-agent";
2 ✔
421
  }
422

423
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
16 ✔
424
                 std::move(batch), true, true);
425
}
426

427
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
211 ✔
428
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
1,477 ✔
429
  args.append(secret ? "--list-secret-keys" : "--list-keys");
572 ✔
430

431
  for (const QString &keystring : std::as_const(keystrings)) {
6,468 ✔
432
    if (!keystring.isEmpty()) {
6,257 ✔
433
      args.append(keystring);
434
    }
435
  }
436
  QString p_out;
211 ✔
437
  if (Executor::executeBlocking(m_settings.gpgExecutable, args, &p_out) != 0) {
211 ✔
438
    return {};
10 ✔
439
  }
440
  return parseGpgColonOutput(p_out, secret);
201 ✔
441
}
442

443
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
174 ✔
444
  return listKeys(QStringList(keystring), secret);
348 ✔
445
}
446

447
namespace {
448

449
auto containsAny(const QString &str, const QStringList &patterns) -> bool {
127 ✔
450
  for (const QString &p : patterns) {
352 ✔
451
    if (str.contains(p)) {
246 ✔
452
      return true;
453
    }
454
  }
455
  return false;
456
}
457

458
// @p patterns must already be lowercase; only @p str is lowered.
459
auto containsAnyCaseInsensitive(const QString &str, const QStringList &patterns)
107 ✔
460
    -> bool {
461
  const QString lower = str.toLower();
462
  for (const QString &p : patterns) {
265 ✔
463
    if (lower.contains(p)) {
169 ✔
464
      return true;
465
    }
466
  }
467
  return false;
468
}
469

470
} // namespace
471

472
auto gpgErrorMessage(const QString &err) -> QString {
47 ✔
473
  // Machine-readable status tokens added by --status-fd 2
474
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYEXPIRED"),
235 ✔
475
                        QStringLiteral("[GNUPG:] INV_RECP 5 ")}))
47 ✔
476
    return QCoreApplication::translate(
477
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
478
                "replace it.");
5 ✔
479
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYREVOKED"),
210 ✔
480
                        QStringLiteral("[GNUPG:] INV_RECP 4 ")}))
42 ✔
481
    return QCoreApplication::translate(
482
        "Pass", "Encryption failed: GPG key has been revoked.");
4 ✔
483
  if (containsAny(err, {QStringLiteral("[GNUPG:] NO_PUBKEY"),
190 ✔
484
                        QStringLiteral("[GNUPG:] INV_RECP")}))
38 ✔
485
    return QCoreApplication::translate(
486
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
487
                "Check that the key ID in .gpg-id is correct and imported.");
12 ✔
488
  if (err.contains(QStringLiteral("[GNUPG:] FAILURE")))
26 ✔
489
    return QCoreApplication::translate(
490
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
491

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

521
  return {};
14 ✔
522
}
×
523

524
void Pass::finished(int id, int exitCode, const QString &out,
292 ✔
525
                    const QString &err) {
526
  auto pid = static_cast<PROCESS>(id);
292 ✔
527

528
  // Pop the Show() this completion belongs to whether it worked or not, or
529
  // the next result would be attributed to the wrong file.
530
  QString shownFile;
292 ✔
531
  if (pid == PASS_SHOW && !m_pendingShows.isEmpty()) {
292 ✔
532
    shownFile = m_pendingShows.dequeue();
76 ✔
533
  }
534
  // Count this insert off, success or failure, before its result goes out, so
535
  // insertsPending() tracks the inserts still awaiting a report. Each insert
536
  // reaches here once as PASS_INSERT.
537
  if (pid == PASS_INSERT && m_insertsPending > 0) {
292 ✔
538
    --m_insertsPending;
104 ✔
539
  }
540

541
  if (exitCode != 0) {
292 ✔
542
    handleProcessError(pid, exitCode, out, err);
62 ✔
543
    return;
544
  }
545

546
  if (pid == PASS_SHOW) {
230 ✔
547
    emit finishedShow(out, shownFile, exec.lastOutputLossless());
47 ✔
548
    return;
549
  }
550
  emitProcessFinishedSignal(pid, out, err);
183 ✔
551
}
552

553
void Pass::handleProcessError(PROCESS pid, int exitCode, const QString &out,
62 ✔
554
                              const QString &err) {
555
  Q_UNUSED(out);
556

557
  if (pid == PASS_INSERT) {
62 ✔
558
    const QString friendly = gpgErrorMessage(err);
19 ✔
559
    const QString why =
560
        friendly.isEmpty() ? err : formatInsertError(friendly, err);
19 ✔
561
    const bool written = insertWritten(err);
19 ✔
562
    emit insertFailed(why, written);
19 ✔
563
    if (written) {
19 ✔
564
      // The entry is in the store; a git step after it failed (a commit
565
      // that could not be signed, with pass.signcommits, say). The dialog
566
      // closes on this, so say it here rather than only in the output
567
      // panel.
568
      emit critical(tr("Saved, not committed"),
10 ✔
569
                    tr("The entry is saved in the store, but recording it "
5 ✔
570
                       "in git failed. What was reported:\n\n%1")
571
                        .arg(err.trimmed()));
10 ✔
572
    }
573
    emit processErrorExit(exitCode, why);
19 ✔
574
    return;
575
  }
576

577
  if (pid == GPG_GENKEYS) {
43 ✔
578
    emit generateGPGKeysFailed(err);
1 ✔
579
  }
580
  emit processErrorExit(exitCode, err);
43 ✔
581
}
582

583
auto Pass::withoutStatusLines(const QString &err) -> QString {
45 ✔
584
  QStringList humanLines;
45 ✔
585
  for (const QString &line : err.split('\n')) {
181 ✔
586
    QString cleanedLine = line;
587
    cleanedLine.remove('\r');
91 ✔
588
    if (!cleanedLine.startsWith(QLatin1String("[GNUPG:]")))
91 ✔
589
      humanLines.append(cleanedLine);
590
  }
591
  return humanLines.join('\n');
45 ✔
592
}
593

594
auto Pass::formatInsertError(const QString &friendly, const QString &err)
6 ✔
595
    -> QString {
596
  const QString humanErr = withoutStatusLines(err).trimmed();
12 ✔
597
  return humanErr.isEmpty() ? friendly : friendly + "\n\n" + humanErr;
12 ✔
598
}
599

600
void Pass::emitProcessFinishedSignal(PROCESS pid, const QString &out,
183 ✔
601
                                     const QString &err) {
602
  // Only output that cannot contain a secret reaches the generic listeners
603
  // (the output panel among them); Enums::processInfo is the one table.
604
  if (pid >= 0 && pid < Enums::PROCESS_COUNT &&
183 ✔
605
      !Enums::processInfo(pid).secret) {
181 ✔
606
    emit finishedAnyWithPid(out, err, pid);
89 ✔
607
  }
608

609
  // The kind-specific signal. PASS_SHOW is emitted by finished(), which
610
  // knows the file. Content search runs in-process (NativeGrep), not
611
  // through `pass grep`, and emits finishedGrep itself.
612
  using Signal = void (Pass::*)(const QString &, const QString &);
613
  static const QHash<int, Signal> kSignals{
614
      {GIT_INIT, &Pass::finishedGitInit},
615
      {GIT_PULL, &Pass::finishedGitPull},
616
      {GIT_PUSH, &Pass::finishedGitPush},
617
      {PASS_INSERT, &Pass::finishedInsert},
618
      {PASS_REMOVE, &Pass::finishedRemove},
619
      {PASS_INIT, &Pass::finishedInit},
620
      {PASS_MOVE, &Pass::finishedMove},
621
      {PASS_COPY, &Pass::finishedCopy},
622
      {GPG_GENKEYS, &Pass::finishedGenerateGPGKeys},
623
  };
189 ✔
624
  if (const Signal signal = kSignals.value(pid, nullptr)) {
183 ✔
625
    (this->*signal)(out, err);
179 ✔
626
  }
627
}
183 ✔
628

629
void Pass::setEnvVar(const QString &name, const QString &value) {
3,772 ✔
630
  if (value.isEmpty())
3,772 ✔
631
    env.remove(name);
1,252 ✔
632
  else
633
    env.insert(name, value);
2,520 ✔
634
}
3,772 ✔
635

636
void Pass::updateEnv() {
418 ✔
637
  setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY"),
836 ✔
638
            m_settings.passSigningKey);
418 ✔
639
  setEnvVar(QStringLiteral("PASSWORD_STORE_DIR"), m_settings.passStore);
836 ✔
640
  // Every path QtPass hands git names one file or folder: an entry called
641
  // "a*.gpg" must not make `git rm -f -- a*.gpg` remove every entry that
642
  // matches. Also reaches the git that pass runs, which passes names the
643
  // same way.
644
  setEnvVar(QStringLiteral("GIT_LITERAL_PATHSPECS"), QStringLiteral("1"));
836 ✔
645

646
  const PasswordConfiguration &passConfig = m_settings.passwordConfiguration;
418 ✔
647
  setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH"),
836 ✔
648
            QString::number(passConfig.length));
418 ✔
649

650
  setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET"),
836 ✔
651
            effectiveCharset(passConfig));
418 ✔
652

653
  // pass hands PASSWORD_STORE_GPG_OPTS to every gpg it runs: the user's own
654
  // options (split as pass's shell splits them: spaces, tabs, newlines),
655
  // then the output limit ImitatePass passes directly.
656
  QStringList gpgOpts = QProcessEnvironment::systemEnvironment()
418 ✔
657
                            .value(QStringLiteral("PASSWORD_STORE_GPG_OPTS"))
836 ✔
658
                            .split(QRegularExpression(QStringLiteral("\\s+")),
836 ✔
659
                                   Qt::SkipEmptyParts);
836 ✔
660
  gpgOpts << maxOutputArgs();
836 ✔
661
  setEnvVar(QStringLiteral("PASSWORD_STORE_GPG_OPTS"),
836 ✔
662
            gpgOpts.join(QLatin1Char(' ')));
418 ✔
663

664
  // As pass does: git never looks for a repository above the store's own
665
  // parent. A store that is not a repository itself but lies inside one (a
666
  // dotfiles repository in the home folder) would otherwise have its entries
667
  // committed and pushed there by native git mode. Only in the environment
668
  // of the processes QtPass runs for the store, never QtPass's own, which a
669
  // file manager or terminal it opens would inherit. pass sets its own
670
  // ceiling whatever this says. A store kept inside a larger repository on
671
  // purpose opts out (gitUseParentRepository), and then, as without a
672
  // store, whatever ceiling QtPass was started with applies.
673
  // A ceiling git cannot take as one entry (the parent's path holds the
674
  // list separator) is backed by GIT_DIR and GIT_WORK_TREE naming the
675
  // store's own repository (Util::gitStoreVariables()); pass unsets those
676
  // for itself and keeps its own ceiling.
677
  setEnvVar(QStringLiteral("GIT_DIR"), QString());
836 ✔
678
  setEnvVar(QStringLiteral("GIT_WORK_TREE"), QString());
836 ✔
679
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
418 ✔
680
    setEnvVar(QStringLiteral("GIT_CEILING_DIRECTORIES"),
36 ✔
681
              qEnvironmentVariable("GIT_CEILING_DIRECTORIES"));
36 ✔
682
  } else {
683
    for (const auto &[name, value] : Util::gitStoreVariables(
684
             m_settings.passStore, m_settings.gitExecutable)) {
1,204 ✔
685
      setEnvVar(name, value);
404 ✔
686
    }
687
  }
688

689
  exec.setEnvironment(env);
418 ✔
690
}
418 ✔
691

692
auto Pass::withCurrentGitPin(QProcessEnvironment base) const
1,414 ✔
693
    -> QProcessEnvironment {
694
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
1,414 ✔
695
    return base;
16 ✔
696
  }
697
  base.remove(QStringLiteral("GIT_DIR"));
2,796 ✔
698
  base.remove(QStringLiteral("GIT_WORK_TREE"));
2,796 ✔
699
  for (const auto &[name, value] : Util::gitStoreVariables(
700
           m_settings.passStore, m_settings.gitExecutable)) {
4,204 ✔
701
    base.insert(name, value);
1,408 ✔
702
  }
703
  return base;
1,398 ✔
704
}
705

706
auto Pass::maxOutputArgs() -> QStringList {
1,106 ✔
707
  return {QStringLiteral("--max-output"), QString::number(kMaxPlaintextBytes)};
3,318 ✔
708
}
1,106 ✔
709

710
namespace {
711
/// File names compare the way the platform's file system compares them:
712
/// "C:/Store" and "c:/store" are the same directory on Windows.
713
#ifdef Q_OS_WIN
714
constexpr auto kPathCase = Qt::CaseInsensitive;
715
#else
716
constexpr auto kPathCase = Qt::CaseSensitive;
717
#endif
718

719
/// Whether @p path is @p dir or lies under it.
720
auto isAtOrUnder(const QString &path, const QString &dir,
1,930 ✔
721
                 const QString &dirPrefix) -> bool {
722
  return path.compare(dir, kPathCase) == 0 ||
3,354 ✔
723
         path.startsWith(dirPrefix, kPathCase);
1,424 ✔
724
}
725

726
/// Where the lookup of a .gpg-id starts and the store that bounds it.
727
struct GpgIdLookup {
728
  QDir start;
729
  /// The folder whose list is wanted, whether it exists or not.
730
  QString folder;
731
  QString storeDir;
732
  QString storePrefix;
733
};
734

735
/// The folder whose list @p for_file wants: its own for a folder, its
736
/// folder's for an entry.
737
auto gpgIdLookup(const QString &for_file, const QString &passStore)
563 ✔
738
    -> GpgIdLookup {
739
  const QString normalizedFile = QDir::fromNativeSeparators(for_file);
563 ✔
740
  // Inside the store means at a path boundary: "/store-other/x" is not
741
  // under "/store", however the prefix compares.
742
  const QString storeDir =
743
      QDir::cleanPath(QDir::fromNativeSeparators(passStore));
563 ✔
744
  const QString storePrefix = storeDir.endsWith(QLatin1Char('/'))
563 ✔
745
                                  ? storeDir
563 ✔
746
                                  : storeDir + QLatin1Char('/');
563 ✔
747
  const QString cleanFile = QDir::cleanPath(normalizedFile);
563 ✔
748
  const bool insideStore = isAtOrUnder(cleanFile, storeDir, storePrefix);
563 ✔
749
  // A relative name is one inside the store; an absolute path outside it
750
  // stays what it is and the walk stops at once.
751
  const QString fullPath = insideStore || QDir::isAbsolutePath(cleanFile)
15 ✔
752
                               ? cleanFile
563 ✔
753
                               : storePrefix + cleanFile;
10 ✔
754
  // A folder (trailing separator, which cleanPath() dropped, or an existing
755
  // directory) wants its own list; an entry wants its folder's.
756
  const bool isFolder =
757
      normalizedFile.endsWith(QLatin1Char('/')) || QFileInfo(fullPath).isDir();
563 ✔
758
  // A folder that does not exist yet (an entry saved into a new folder, a
759
  // move to one) starts the walk at its nearest existing ancestor in the
760
  // store, as pass's set_gpg_recipients does: otherwise the walk ended at
761
  // once and the store root's list was taken over the one in between.
762
  const QString folder =
763
      QDir::cleanPath(isFolder ? fullPath : QFileInfo(fullPath).absolutePath());
1,348 ✔
764
  QString start = folder;
765
  while (!QFileInfo(start).exists() &&
595 ✔
766
         isAtOrUnder(QDir::cleanPath(start), storeDir, storePrefix) &&
1,174 ✔
767
         QDir::cleanPath(start) != storeDir) {
595 ✔
768
    start = QFileInfo(start).absolutePath();
32 ✔
769
  }
770
  return {QDir(start), folder, storeDir, storePrefix};
563 ✔
771
}
563 ✔
772

773
/// Whether @p candidate can be its folder's .gpg-id: a regular file, as
774
/// pass looks for (test -f), so a folder under the name is passed over as
775
/// pass passes it. A link under the name is not: whoever planted it chose
776
/// the recipients elsewhere.
777
auto isOwnGpgId(const QFileInfo &candidate) -> bool {
695 ✔
778
  return candidate.isFile() && !candidate.isSymLink() &&
1,087 ✔
779
         !candidate.isJunction();
392 ✔
780
}
781

782
/// Walk up from the lookup's start to the first folder inside the store
783
/// that has its own .gpg-id; nothing when none does. A link under the name
784
/// is skipped, so the parent's list applies instead.
785
auto nearestGpgId(const GpgIdLookup &lookup) -> std::optional<QString> {
363 ✔
786
  QDir dir = lookup.start;
363 ✔
787
  while (dir.exists() && isAtOrUnder(QDir::cleanPath(dir.absolutePath()),
1,836 ✔
788
                                     lookup.storeDir, lookup.storePrefix)) {
459 ✔
789
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
434 ✔
790
    if (isOwnGpgId(candidate)) {
434 ✔
791
      return candidate.absoluteFilePath();
338 ✔
792
    }
793
    if (!dir.cdUp()) {
96 ✔
794
      break;
795
    }
796
  }
434 ✔
797
  return std::nullopt;
25 ✔
798
}
363 ✔
799

800
} // namespace
801

802
auto Pass::heldScopes() -> QSet<QString> & {
246 ✔
803
  static QSet<QString> scopes;
252 ✔
804
  return scopes;
246 ✔
805
}
806

807
auto Pass::scopePath(const QString &path) const -> QString {
246 ✔
808
  return QDir::cleanPath(QDir(m_settings.passStore).absoluteFilePath(path));
492 ✔
809
}
810

811
auto Pass::autoPushHeld() const -> bool {
63 ✔
812
  const QString store = scopePath(QString());
63 ✔
813
  const QSet<QString> &scopes = heldScopes();
63 ✔
814
  return std::any_of(scopes.cbegin(), scopes.cend(),
63 ✔
815
                     [&store](const QString &s) {
165 ✔
816
                       return isAtOrUnder(s, store, store + QLatin1Char('/'));
330 ✔
817
                     });
63 ✔
818
}
819

820
void Pass::GitPushAutomatic() {
15 ✔
821
  m_pushIsAutomatic = true;
15 ✔
822
  GitPush();
15 ✔
823
  m_pushIsAutomatic = false;
15 ✔
824
}
15 ✔
825

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

828
void Pass::holdAutoPush(const QString &scope) {
92 ✔
829
  heldScopes().insert(scopePath(scope));
92 ✔
830
}
92 ✔
831

832
void Pass::releaseAutoPush(const QString &folder) {
91 ✔
833
  const QString root = scopePath(folder);
91 ✔
834
  QSet<QString> &scopes = heldScopes();
91 ✔
835
  for (auto it = scopes.begin(); it != scopes.end();) {
836
    it = isAtOrUnder(*it, root, root + QLatin1Char('/')) ? scopes.erase(it)
922 ✔
837
                                                         : std::next(it);
461 ✔
838
  }
839
}
91 ✔
840

841
auto Pass::refuseLinkedPath(const QString &path, LinkScope scope,
704 ✔
842
                            PathSpelling spelling) -> bool {
843
  const QString full = QDir::isAbsolutePath(path)
844
                           ? path
704 ✔
845
                           : QDir(m_settings.passStore).filePath(path);
116 ✔
846
  // The link check below walks only under the store as configured: a path
847
  // spelled through the root's link target would get no more than the
848
  // entry itself judged. No caller makes one; say so if one starts to.
849
  if (spelling == PathSpelling::Configured &&
1,167 ✔
850
      PathValidator::isTargetSpelled(m_settings.passStore, full)) {
463 ✔
851
    qCWarning(lcQtPass)
4 ✔
852
        << "Path spelled through the store root's link target, not as the "
853
           "store is configured; Pass operations expect the configured "
854
           "spelling:"
2 ✔
855
        << full;
2 ✔
856
  }
857
  if (!Util::isUnderLink(full, m_settings.passStore,
704 ✔
858
                         scope == LinkScope::EntryAndParents)) {
859
    return false;
860
  }
861
  const QString why =
862
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
×
863
         "points to is not part of the password store and is left alone.")
864
          .arg(QDir::toNativeSeparators(QDir::cleanPath(full)));
58 ✔
865
  refuseAsNotPartOfStore(why);
29 ✔
866
  return true;
867
}
868

869
auto Pass::refuseFolderOutsideStore(const QString &folder, QString *relative)
78 ✔
870
    -> bool {
871
  if (const std::optional<QString> inStore =
78 ✔
872
          PathValidator::storeRelativePath(m_settings.passStore, folder)) {
78 ✔
873
    if (relative != nullptr) {
73 ✔
874
      *relative = *inStore;
73 ✔
875
    }
876
    return false;
877
  }
878
  refuseAsNotPartOfStore(
5 ✔
879
      tr("%1 is not inside the password store. Recipients are set for the "
5 ✔
880
         "store or a folder in it.")
881
          .arg(QDir::toNativeSeparators(QDir::cleanPath(folder))));
10 ✔
882
  return true;
5 ✔
883
}
884

885
auto Pass::unfinishedGitOperationReason() -> QString {
706 ✔
886
  if (!m_settings.useGit) {
706 ✔
887
    return {};
498 ✔
888
  }
889
  // One git call names the path of each marker file or directory, whether or
890
  // not it exists; the backend runs it in the store (ImitatePass with
891
  // `-C <store>`, RealPass through `pass git`). The markers, paired with the
892
  // operation each one means, in the order git prints them back.
893
  // The names are Git's own commands, which the user then runs with --abort or
894
  // --continue; the translator comments say so.
895
  const std::array<std::pair<QLatin1String, QString>, 6> markers{{
896
      //: The Git command `git rebase`, inserted into "in the middle of a %1".
897
      //: Best kept as Git's command name.
898
      {QLatin1String("rebase-merge"), tr("rebase")},
208 ✔
899
      //: The Git command `git rebase`, inserted into "in the middle of a %1".
900
      //: Best kept as Git's command name.
901
      {QLatin1String("rebase-apply"), tr("rebase")},
208 ✔
902
      //: The Git command `git merge`, inserted into "in the middle of a %1".
903
      //: Best kept as Git's command name.
904
      {QLatin1String("MERGE_HEAD"), tr("merge")},
208 ✔
905
      //: The Git command `git cherry-pick`, inserted into "in the middle of a
906
      //: %1". Best kept as Git's command name.
907
      {QLatin1String("CHERRY_PICK_HEAD"), tr("cherry-pick")},
208 ✔
908
      //: The Git command `git revert`, inserted into "in the middle of a %1".
909
      //: Best kept as Git's command name.
910
      {QLatin1String("REVERT_HEAD"), tr("revert")},
208 ✔
911
      // A multi-commit cherry-pick or revert keeps its sequencer state after a
912
      // conflict resolution is committed, when CHERRY_PICK_HEAD/REVERT_HEAD is
913
      // already gone but `--continue` has more commits to apply. Checked last,
914
      // so the specific head above names the operation when it is still there.
915
      //: The Git commands `git cherry-pick` and `git revert`, inserted into
916
      //: "in the middle of a %1". Best kept as Git's command names.
917
      {QLatin1String("sequencer"), tr("cherry-pick or revert")},
208 ✔
918
  }};
×
919
  QStringList args{QStringLiteral("rev-parse")};
416 ✔
920
  for (const auto &marker : markers) {
1,456 ✔
921
    args << QStringLiteral("--git-path") << marker.first;
1,248 ✔
922
  }
923
  QString out;
208 ✔
924
  if (!storeGit(args, &out)) {
208 ✔
925
    // Git is off, the store is not a repository, or git could not be asked:
926
    // nothing is refused, as the operation would run anyway.
927
    return {};
14 ✔
928
  }
929
  const QStringList paths = out.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
194 ✔
930
  for (int i = 0; i < paths.size() && i < static_cast<int>(markers.size());
796 ✔
931
       ++i) {
932
    const QString path = paths.at(i).trimmed();
933
    const QString full = QDir::isAbsolutePath(path)
934
                             ? path
609 ✔
935
                             : QDir(m_settings.passStore).filePath(path);
609 ✔
936
    if (!QFileInfo::exists(full)) {
609 ✔
937
      continue;
938
    }
939
    //: %1 is a Git command name: rebase, merge, cherry-pick, revert, or
940
    //: "cherry-pick or revert".
941
    return tr("The password store's Git repository is in the middle of a %1. "
7 ✔
942
              "Finish or abort it with Git before changing the password store, "
943
              "or what you change may be lost.")
944
        .arg(markers.at(static_cast<size_t>(i)).second);
7 ✔
945
  }
946
  return {};
187 ✔
947
}
948

949
auto Pass::refusePendingPull() -> bool {
137 ✔
950
  if (!m_settings.useGit || !exec.hasQueued(Enums::GIT_PULL)) {
173 ✔
951
    return false;
952
  }
953
  const QString why =
954
      tr("The password store is being updated (a Git pull is in progress). "
955
         "Wait until it has finished, then try again.");
956
  // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
957
  // and is released by processErrorExit(); a refusal starts nothing.
958
  emit startingExecuteWrapper();
2 ✔
959
  emit critical(tr("Update in progress"), why);
2 ✔
960
  emit processErrorExit(1, why);
2 ✔
961
  return true;
962
}
963

964
auto Pass::refuseUnfinishedGitOperation() -> bool {
509 ✔
965
  const QString why = unfinishedGitOperationReason();
509 ✔
966
  if (why.isEmpty()) {
509 ✔
967
    return false;
968
  }
969
  // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
970
  // and is released by finished()/processErrorExit(); a refusal starts
971
  // nothing, so it emits both ends.
972
  emit startingExecuteWrapper();
5 ✔
973
  emit critical(tr("Unfinished Git operation"), why);
5 ✔
974
  emit processErrorExit(1, why);
5 ✔
975
  return true;
976
}
977

978
void Pass::refuseAsNotPartOfStore(const QString &why) {
34 ✔
979
  // The interface arms itself when an operation starts and is released by
980
  // finished or processErrorExit; a refusal starts nothing, so emits both.
981
  emit startingExecuteWrapper();
34 ✔
982
  emit critical(tr("Not part of the store"), why);
34 ✔
983
  emit processErrorExit(1, why);
34 ✔
984
}
34 ✔
985

986
auto Pass::getGpgIdPath(const QString &for_file, const QString &passStore)
363 ✔
987
    -> QString {
988
  return nearestGpgId(gpgIdLookup(for_file, passStore))
726 ✔
989
      .value_or(
990
          QDir(QDir::fromNativeSeparators(passStore)).filePath(".gpg-id"));
1,452 ✔
991
}
992

993
auto Pass::refuseSkippedGpgId(const QString &file, bool signing,
211 ✔
994
                              const QString &except) -> bool {
995
  // Without a signing key the parent's list applies, as it does for pass.
996
  if (!signing) {
211 ✔
997
    return false;
998
  }
999
  QString recordError;
59 ✔
1000
  const std::optional<QString> skipped =
1001
      skippedGpgId(file, m_settings.passStore, &recordError);
59 ✔
1002
  if (!skipped || (!except.isEmpty() &&
59 ✔
1003
                   QDir::cleanPath(*skipped) == QDir::cleanPath(except))) {
61 ✔
1004
    return false;
1005
  }
1006
  // The strings keep the context they were translated in.
1007
  if (!recordError.isEmpty()) {
4 ✔
UNCOV
1008
    emit critical(QCoreApplication::translate(
×
1009
                      "ImitatePass", "Cannot check the recipient list"),
UNCOV
1010
                  QCoreApplication::translate(
×
1011
                      "ImitatePass", "%1 Whether %2 was removed cannot be "
1012
                                     "told, so nothing was encrypted.")
UNCOV
1013
                      .arg(recordError, QDir::toNativeSeparators(*skipped)));
×
1014
    return true;
×
1015
  }
1016
  emit critical(
4 ✔
1017
      QCoreApplication::translate("ImitatePass", "Recipient list missing"),
8 ✔
1018
      QCoreApplication::translate(
4 ✔
1019
          "ImitatePass",
1020
          "The signed recipient list %1 is missing or is not a regular file. "
1021
          "QtPass does not fall back to a parent folder's list for it: that "
1022
          "list was not signed for this folder. If a link is under that name, "
1023
          "remove it. Then open Users for that folder and save its "
1024
          "recipients, which writes and signs a fresh list.")
1025
          .arg(QDir::toNativeSeparators(*skipped)));
8 ✔
1026
  return true;
4 ✔
1027
}
1028

1029
auto Pass::verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile,
47 ✔
1030
                            QByteArray *contents, QString *why) const -> bool {
1031
  if (!signer.verifyFile(gpgIdFile, contents)) {
47 ✔
1032
    return false;
1033
  }
1034
  // Authentic and unmodified is not the same as current: an older signed
1035
  // list put back into the store is refused once this device has seen a
1036
  // newer one, and one signed for another folder is refused here.
1037
  QString reason;
46 ✔
1038
  if (GpgIdGeneration::accept(gpgIdFile, *contents, m_settings.passStore,
46 ✔
1039
                              &reason) != GpgIdGeneration::Verdict::Accepted) {
1040
    if (why != nullptr) {
16 ✔
1041
      *why = reason;
16 ✔
1042
    }
1043
    return false;
16 ✔
1044
  }
1045
  return true;
1046
}
1047

1048
auto Pass::skippedGpgId(const QString &forFile, const QString &passStore,
88 ✔
1049
                        QString *recordError) -> std::optional<QString> {
1050
  const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
88 ✔
1051
  // The same walk as nearestGpgId(), stopping at the list it finds, and
1052
  // short of the store root: the root's own list has no parent to fall
1053
  // back to, and the signature check refuses it when it is missing. It
1054
  // starts at the folder asked for, not at its nearest existing one: a
1055
  // folder removed together with its list is asked of the record too.
1056
  QString dir = lookup.folder;
1057
  while (dir.startsWith(lookup.storePrefix, kPathCase)) {
119 ✔
1058
    const QFileInfo candidate(dir + QStringLiteral("/.gpg-id"));
130 ✔
1059
    if (isOwnGpgId(candidate)) {
65 ✔
1060
      return std::nullopt;
19 ✔
1061
    }
1062
    // A link under the name (dangling or not), or nothing under it where
1063
    // this device accepted a list before: both are the folder's list gone,
1064
    // not a folder that never had one.
1065
    if (candidate.isSymLink() || candidate.isJunction()) {
46 ✔
1066
      return candidate.absoluteFilePath();
10 ✔
1067
    }
1068
    // An unreadable record is not "never seen": whether a list was accepted
1069
    // here cannot be told, so this folder is refused too (fail closed), with
1070
    // the record's own reason for the caller to show.
1071
    QString why;
41 ✔
1072
    const std::optional<bool> seen =
1073
        GpgIdGeneration::seen(candidate.absoluteFilePath(), &why);
82 ✔
1074
    if (!seen) {
41 ✔
1075
      if (recordError != nullptr) {
1 ✔
1076
        *recordError =
1077
            why.isEmpty()
1078
                ? tr("The generation record of the recipient lists cannot "
2 ✔
1079
                     "be read.")
1080
                : why;
1081
      }
1082
      return candidate.absoluteFilePath();
2 ✔
1083
    }
1084
    if (*seen) {
40 ✔
1085
      return candidate.absoluteFilePath();
18 ✔
1086
    }
1087
    const QString parent = QDir::cleanPath(QFileInfo(dir).absolutePath());
62 ✔
1088
    if (parent == dir) {
31 ✔
1089
      break;
1090
    }
1091
    dir = parent;
31 ✔
1092
  }
65 ✔
1093
  return std::nullopt;
54 ✔
1094
}
88 ✔
1095

1096
auto Pass::linkedGpgId(const QString &forFile, const QString &passStore)
112 ✔
1097
    -> std::optional<QString> {
1098
  const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
112 ✔
1099
  // The walk of nearestGpgId(), root included, stopping at the list it
1100
  // finds.
1101
  QDir dir = lookup.start;
112 ✔
1102
  while (dir.exists() && isAtOrUnder(QDir::cleanPath(dir.absolutePath()),
798 ✔
1103
                                     lookup.storeDir, lookup.storePrefix)) {
1104
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
196 ✔
1105
    if (isOwnGpgId(candidate)) {
196 ✔
1106
      return std::nullopt;
35 ✔
1107
    }
1108
    if (candidate.isSymLink() || candidate.isJunction()) {
161 ✔
1109
      return candidate.absoluteFilePath();
14 ✔
1110
    }
1111
    if (!dir.cdUp()) {
154 ✔
1112
      break;
1113
    }
1114
  }
196 ✔
1115
  return std::nullopt;
70 ✔
1116
}
112 ✔
1117

1118
namespace {
1119

1120
/// What the Users dialog may preselect for a verified list, given what the
1121
/// generation record says about it.
1122
auto judgedRecipients(GpgIdGeneration::Verdict verdict,
7 ✔
1123
                      const QByteArray &contents, const QString &gpgIdPath,
1124
                      const QString &why) -> Pass::RecipientsForEditing {
1125
  using RecipientsForEditing = Pass::RecipientsForEditing;
1126
  RecipientsForEditing result;
7 ✔
1127
  switch (verdict) {
7 ✔
1128
  case GpgIdGeneration::Verdict::Accepted:
1 ✔
1129
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1130
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1131
    break;
1 ✔
1132
  case GpgIdGeneration::Verdict::Rollback:
1 ✔
1133
    // Authentic and this folder's, only older: the recovery goes through
1134
    // this dialog, so it is preselected, with the reason in view.
1135
    result.state = RecipientsForEditing::State::VerifiedRollback;
1 ✔
1136
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1137
    result.warning = why;
1 ✔
1138
    break;
1 ✔
1139
  case GpgIdGeneration::Verdict::Unbound:
5 ✔
1140
  case GpgIdGeneration::Verdict::Conflict:
1141
  case GpgIdGeneration::Verdict::WrongFolder:
1142
  case GpgIdGeneration::Verdict::WrongStore:
1143
  case GpgIdGeneration::Verdict::Malformed:
1144
  case GpgIdGeneration::Verdict::RecordUnavailable:
1145
    // Signed, but not shown to be this folder's list, not a list to trust,
1146
    // or nothing to judge it by: preselecting it would sign it in.
1147
    result.state = RecipientsForEditing::State::Rejected;
5 ✔
1148
    result.warning =
1149
        Pass::tr("%1 Nothing is preselected: saving would sign whatever is "
5 ✔
1150
                 "in it. Select the recipients yourself.")
1151
            .arg(why);
10 ✔
1152
    break;
5 ✔
1153
  }
1154
  return result;
7 ✔
1155
}
1156

1157
} // namespace
1158

1159
auto Pass::recipientsForEditing(const QString &dir, const QString &passStore)
59 ✔
1160
    -> RecipientsForEditing {
1161
  RecipientsForEditing result;
59 ✔
1162
  const QString folder = dir.isEmpty() ? QString() : dir;
59 ✔
1163
  const QString gpgIdPath = getGpgIdPath(folder, passStore);
59 ✔
1164
  const GpgIdSigner signer(
1165
      m_settings.gpgExecutable,
1166
      GpgIdSigner::keysFromSetting(m_settings.passSigningKey));
177 ✔
1167
  if (!signer.enabled()) {
59 ✔
1168
    // A list that is there but cannot be read as one (too large, not a
1169
    // regular file, unreadable) is not an empty list: preselecting nothing
1170
    // without a word would let OK write a new list over it, and later
1171
    // re-encryptions drop whoever it named.
1172
    // Read once and parsed from those bytes: a second read could find
1173
    // something else under the name. A link counts as there, dangling too.
1174
    const QFileInfo info(gpgIdPath);
49 ✔
1175
    if (!info.exists() && !info.isSymLink()) {
49 ✔
1176
      result.state = RecipientsForEditing::State::Unsigned;
1177
      return result;
14 ✔
1178
    }
1179
    const std::optional<QByteArray> bytes =
1180
        Util::readRegularFile(gpgIdPath, Util::kMaxGpgIdBytes);
35 ✔
1181
    if (!bytes) {
35 ✔
1182
      result.state = RecipientsForEditing::State::Rejected;
2 ✔
1183
      result.warning =
1184
          tr("%1 cannot be read as a recipient list (a regular file of at "
2 ✔
1185
             "most %2), so nothing is preselected. Check it before choosing "
1186
             "recipients here: OK writes a new list over it.")
1187
              .arg(gpgIdPath,
2 ✔
1188
                   QLocale().formattedDataSize(Util::kMaxGpgIdBytes));
4 ✔
1189
      return result;
2 ✔
1190
    }
1191
    result.state = RecipientsForEditing::State::Unsigned;
1192
    result.recipients = parseRecipients(*bytes, gpgIdPath);
33 ✔
1193
    return result;
33 ✔
1194
  }
49 ✔
1195
  QString recordError;
10 ✔
1196
  if (const std::optional<QString> skipped =
10 ✔
1197
          skippedGpgId(folder, passStore, &recordError)) {
10 ✔
1198
    // The folder's own list was removed or replaced by a link (or the record
1199
    // that would tell cannot be read): the list the walk found further up
1200
    // was not signed for this folder, so preselecting it would sign it in
1201
    // here with one click.
1202
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1203
    result.warning =
1204
        recordError.isEmpty()
1205
            ? tr("The recipient list %1 is missing or is not a regular file, "
2 ✔
1206
                 "so nothing is preselected: the list of a parent folder was "
1207
                 "not signed for this one. Select this folder's recipients "
1208
                 "yourself; OK writes and signs a fresh list.")
1209
                  .arg(*skipped)
1210
            : tr("%1 Nothing is preselected: whether %2 was removed cannot "
1 ✔
1211
                 "be told.")
1212
                  .arg(recordError, *skipped);
1213
    return result;
1 ✔
1214
  }
1215
  if (!QFileInfo::exists(gpgIdPath)) {
9 ✔
1216
    // A folder without a list yet (new store, new profile): nothing to
1217
    // verify and nothing to preselect.
1218
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1219
    return result;
1 ✔
1220
  }
1221
  QByteArray contents;
8 ✔
1222
  if (!signer.verifyFile(gpgIdPath, &contents)) {
8 ✔
1223
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1224
    result.warning =
1225
        tr("The recipient list %1 does not verify against the signing key, "
1 ✔
1226
           "so nothing is preselected: saving would sign whatever is in it. "
1227
           "Select the recipients yourself; OK writes and signs a fresh list.")
1228
            .arg(gpgIdPath);
2 ✔
1229
    return result;
1 ✔
1230
  }
1231
  QString why;
7 ✔
1232
  const GpgIdGeneration::Verdict verdict =
1233
      GpgIdGeneration::accept(gpgIdPath, contents, passStore, &why);
7 ✔
1234
  return judgedRecipients(verdict, contents, gpgIdPath, why);
7 ✔
1235
}
59 ✔
1236

1237
auto Pass::getRecipientList(const QString &for_file, const QString &passStore)
8 ✔
1238
    -> QStringList {
1239
  const QString gpgIdPath = getGpgIdPath(for_file, passStore);
8 ✔
1240
  // The root .gpg-id comes back whatever it is; a link is not a list.
1241
  if (Util::isLinkedFolder(gpgIdPath)) {
8 ✔
1242
    return {};
1 ✔
1243
  }
1244
  const std::optional<QByteArray> bytes =
1245
      Util::readRegularFile(gpgIdPath, Util::kMaxGpgIdBytes);
7 ✔
1246
  if (!bytes) {
7 ✔
UNCOV
1247
    return {};
×
1248
  }
1249
  return parseRecipients(*bytes, gpgIdPath);
7 ✔
1250
}
1251

1252
auto Pass::parseRecipients(const QByteArray &contents,
208 ✔
1253
                           const QString &sourceName) -> QStringList {
1254
  QStringList recipients;
208 ✔
1255
  const QString text = QString::fromUtf8(contents);
1256
  for (const QString &line : text.split(QLatin1Char('\n'))) {
6,737 ✔
1257
    QString recipient = line.split(QLatin1Char('#')).first().trimmed();
13,058 ✔
1258
    if (recipient.isEmpty()) {
6,529 ✔
1259
      continue;
261 ✔
1260
    }
1261
    if (!Util::isValidKeyId(recipient)) {
6,268 ✔
1262
      // Never drop a recipient silently: the list is written back verbatim
1263
      // by UsersDialog, so a skipped line disappears from .gpg-id.
1264
      qCWarning(lcQtPass) << "Skipping unusable recipient in" << sourceName
4 ✔
1265
                          << ":" << recipient;
2 ✔
1266
      continue;
2 ✔
1267
    }
2 ✔
1268
    recipients += recipient;
1269
  }
1270
  return recipients;
208 ✔
1271
}
1272

1273
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
1274
 */
1275

1276
auto Pass::boundedRandom(quint32 bound) -> quint32 {
7,620 ✔
1277
  if (bound < 2) {
7,620 ✔
1278
    return 0;
1279
  }
1280

1281
  quint32 randval;
1282
  // arc4random_uniform-style rejection against modulo bias: drop values
1283
  // below 2^32 % bound, which (1 + ~bound) % bound computes in quint32.
1284
  const quint32 rejectionThreshold = (1 + ~bound) % bound;
7,616 ✔
1285

1286
  do {
1287
    randval = QRandomGenerator::system()->generate();
1288
  } while (randval < rejectionThreshold);
7,616 ✔
1289

1290
  return randval % bound;
7,616 ✔
1291
}
1292

1293
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,209 ✔
1294
    -> QString {
1295
  if (charset.isEmpty() || length == 0U) {
1,209 ✔
1296
    return {};
2 ✔
1297
  }
1298
  QString out;
1,207 ✔
1299
  for (unsigned int i = 0; i < length; ++i) {
8,827 ✔
1300
    out.append(charset.at(static_cast<int>(
7,620 ✔
1301
        boundedRandom(static_cast<quint32>(charset.length())))));
7,620 ✔
1302
  }
1303
  return out;
1304
}
1305

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