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

IJHack / QtPass / 44081359370

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

push

github

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

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

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

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

Scan finding ANT-2026-3I1PV36T.

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

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

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

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

* CHANGELOG: untick removed recipients before saving a nested copy

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

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

* CHANGELOG: rewrap the Add folder upgrade note

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

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

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

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

7 existing lines in 2 files now uncovered.

8972 of 9310 relevant lines covered (96.37%)

756.22 hits per line

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

98.22
/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,585 ✔
50
}
51

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

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

66
  connect(&exec, &Executor::starting, this, &Pass::startingExecuteWrapper);
375 ✔
67
  connect(&exec, &Executor::drained, this, [this] {
375 ✔
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;
96 ✔
77
    emit idle();
96 ✔
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) {
375 ✔
83
    if (completes) {
247 ✔
84
      exec.setEnvironment(withCurrentGitPin(env));
241 ✔
85
    }
86
  });
247 ✔
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"),
750 ✔
95
      QStringLiteral("PASSWORD_STORE_SIGNING_KEY/u"),
375 ✔
96
      QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH/u"),
375 ✔
97
      QStringLiteral("PASSWORD_STORE_CHARACTER_SET/u"),
375 ✔
98
      QStringLiteral("PASSWORD_STORE_GPG_OPTS/u"),
375 ✔
99
      QStringLiteral("GIT_CEILING_DIRECTORIES/p"),
375 ✔
100
      QStringLiteral("GIT_LITERAL_PATHSPECS/u")};
3,000 ✔
101
  const QString existing = env.value(QStringLiteral("WSLENV"));
750 ✔
102
  if (existing.isEmpty()) {
375 ✔
103
    env.insert(QStringLiteral("WSLENV"), wslenvVars.join(':'));
748 ✔
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
}
375 ✔
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,
247 ✔
121
                          const QStringList &args, QString input,
122
                          bool readStdout, bool readStderr) {
123
  beforeExecute(id);
247 ✔
124
  qCDebug(lcQtPass) << app << loggableArgs(args);
247 ✔
125
  exec.execute(id, m_settings.passStore, app, args, std::move(input),
247 ✔
126
               readStdout, readStderr);
127
}
247 ✔
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*/) {}
66 ✔
158

159
void Pass::init(const AppSettings &settings) {
751 ✔
160
  m_settings = settings;
751 ✔
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,502 ✔
182
      QStringLiteral("GNUPGHOME"));
1,502 ✔
183
  const auto useInheritedHome = [this, &inheritedHome]() {
709 ✔
184
    if (inheritedHome.isEmpty()) {
709 ✔
185
      env.remove(QStringLiteral("GNUPGHOME"));
948 ✔
186
    } else {
187
      env.insert(QStringLiteral("GNUPGHOME"), inheritedHome);
470 ✔
188
    }
189
  };
1,460 ✔
190
  if (m_settings.gpgHome.isEmpty()) {
751 ✔
191
    useInheritedHome();
707 ✔
192
  } else {
193
    QDir absHome(m_settings.gpgHome);
44 ✔
194
    absHome.makeAbsolute();
44 ✔
195
    if (absHome.exists()) {
44 ✔
196
      env.insert(QStringLiteral("GNUPGHOME"), absHome.path());
84 ✔
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
  }
44 ✔
217
}
751 ✔
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> {
149 ✔
428
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
1,043 ✔
429
  args.append(secret ? "--list-secret-keys" : "--list-keys");
399 ✔
430

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

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

447
namespace {
448

449
auto containsAny(const QString &str, const QStringList &patterns) -> bool {
124 ✔
450
  for (const QString &p : patterns) {
343 ✔
451
    if (str.contains(p)) {
240 ✔
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)
102 ✔
460
    -> bool {
461
  const QString lower = str.toLower();
462
  for (const QString &p : patterns) {
252 ✔
463
    if (lower.contains(p)) {
161 ✔
464
      return true;
465
    }
466
  }
467
  return false;
468
}
469

470
} // namespace
471

472
auto gpgErrorMessage(const QString &err) -> QString {
46 ✔
473
  // Machine-readable status tokens added by --status-fd 2
474
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYEXPIRED"),
230 ✔
475
                        QStringLiteral("[GNUPG:] INV_RECP 5 ")}))
46 ✔
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"),
205 ✔
480
                        QStringLiteral("[GNUPG:] INV_RECP 4 ")}))
41 ✔
481
    return QCoreApplication::translate(
482
        "Pass", "Encryption failed: GPG key has been revoked.");
4 ✔
483
  if (containsAny(err, {QStringLiteral("[GNUPG:] NO_PUBKEY"),
185 ✔
484
                        QStringLiteral("[GNUPG:] INV_RECP")}))
37 ✔
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")))
25 ✔
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"),
96 ✔
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"),
92 ✔
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")}))
66 ✔
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"),
76 ✔
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")}))
42 ✔
518
    return QCoreApplication::translate(
519
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
520

521
  return {};
13 ✔
522
}
×
523

524
void Pass::finished(int id, int exitCode, const QString &out,
244 ✔
525
                    const QString &err) {
526
  auto pid = static_cast<PROCESS>(id);
244 ✔
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;
244 ✔
531
  if (pid == PASS_SHOW && !m_pendingShows.isEmpty()) {
244 ✔
532
    shownFile = m_pendingShows.dequeue();
73 ✔
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) {
244 ✔
538
    --m_insertsPending;
77 ✔
539
  }
540

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

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

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

557
  if (pid == PASS_INSERT) {
61 ✔
558
    const QString friendly = gpgErrorMessage(err);
18 ✔
559
    const QString why =
560
        friendly.isEmpty() ? err : formatInsertError(friendly, err);
18 ✔
561
    const bool written = insertWritten(err);
18 ✔
562
    emit insertFailed(why, written);
18 ✔
563
    if (written) {
18 ✔
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"),
8 ✔
569
                    tr("The entry is saved in the store, but recording it "
4 ✔
570
                       "in git failed. What was reported:\n\n%1")
571
                        .arg(err.trimmed()));
8 ✔
572
    }
573
    emit processErrorExit(exitCode, why);
18 ✔
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 {
44 ✔
584
  QStringList humanLines;
44 ✔
585
  for (const QString &line : err.split('\n')) {
178 ✔
586
    QString cleanedLine = line;
587
    cleanedLine.remove('\r');
90 ✔
588
    if (!cleanedLine.startsWith(QLatin1String("[GNUPG:]")))
90 ✔
589
      humanLines.append(cleanedLine);
590
  }
591
  return humanLines.join('\n');
44 ✔
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,
139 ✔
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 &&
139 ✔
605
      !Enums::processInfo(pid).secret) {
137 ✔
606
    emit finishedAnyWithPid(out, err, pid);
71 ✔
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
  };
145 ✔
624
  if (const Signal signal = kSignals.value(pid, nullptr)) {
139 ✔
625
    (this->*signal)(out, err);
135 ✔
626
  }
627
}
139 ✔
628

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

636
void Pass::updateEnv() {
378 ✔
637
  setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY"),
756 ✔
638
            m_settings.passSigningKey);
378 ✔
639
  setEnvVar(QStringLiteral("PASSWORD_STORE_DIR"), m_settings.passStore);
756 ✔
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"));
756 ✔
645

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

650
  setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET"),
756 ✔
651
            effectiveCharset(passConfig));
378 ✔
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()
378 ✔
657
                            .value(QStringLiteral("PASSWORD_STORE_GPG_OPTS"))
756 ✔
658
                            .split(QRegularExpression(QStringLiteral("\\s+")),
756 ✔
659
                                   Qt::SkipEmptyParts);
756 ✔
660
  gpgOpts << maxOutputArgs();
756 ✔
661
  setEnvVar(QStringLiteral("PASSWORD_STORE_GPG_OPTS"),
756 ✔
662
            gpgOpts.join(QLatin1Char(' ')));
378 ✔
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());
756 ✔
678
  setEnvVar(QStringLiteral("GIT_WORK_TREE"), QString());
756 ✔
679
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
378 ✔
680
    setEnvVar(QStringLiteral("GIT_CEILING_DIRECTORIES"),
34 ✔
681
              qEnvironmentVariable("GIT_CEILING_DIRECTORIES"));
34 ✔
682
  } else {
683
    for (const auto &[name, value] : Util::gitStoreVariables(
684
             m_settings.passStore, m_settings.gitExecutable)) {
1,087 ✔
685
      setEnvVar(name, value);
365 ✔
686
    }
687
  }
688

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

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

706
auto Pass::maxOutputArgs() -> QStringList {
1,031 ✔
707
  return {QStringLiteral("--max-output"), QString::number(kMaxPlaintextBytes)};
3,093 ✔
708
}
1,031 ✔
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,212 ✔
721
                 const QString &dirPrefix) -> bool {
722
  return path.compare(dir, kPathCase) == 0 ||
2,101 ✔
723
         path.startsWith(dirPrefix, kPathCase);
889 ✔
724
}
725

726
/// Where the lookup of a .gpg-id starts and the store that bounds it.
727
struct GpgIdLookup {
728
  QDir start;
729
  QString storeDir;
730
  QString storePrefix;
731
};
732

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

769
/// Whether @p candidate can be its folder's .gpg-id. A link under the name
770
/// is not: whoever planted it chose the recipients elsewhere.
771
auto isOwnGpgId(const QFileInfo &candidate) -> bool {
367 ✔
772
  return candidate.exists() && !candidate.isSymLink() &&
617 ✔
773
         !candidate.isJunction();
250 ✔
774
}
775

776
/// Walk up from the lookup's start to the first folder inside the store
777
/// that has its own .gpg-id; nothing when none does. A link under the name
778
/// is skipped, so the parent's list applies instead.
779
auto nearestGpgId(const GpgIdLookup &lookup) -> std::optional<QString> {
256 ✔
780
  QDir dir = lookup.start;
256 ✔
781
  while (dir.exists() && isAtOrUnder(QDir::cleanPath(dir.absolutePath()),
1,340 ✔
782
                                     lookup.storeDir, lookup.storePrefix)) {
335 ✔
783
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
311 ✔
784
    if (isOwnGpgId(candidate)) {
311 ✔
785
      return candidate.absoluteFilePath();
232 ✔
786
    }
787
    if (!dir.cdUp()) {
79 ✔
788
      break;
789
    }
790
  }
311 ✔
791
  return std::nullopt;
24 ✔
792
}
256 ✔
793

794
} // namespace
795

796
auto Pass::heldScopes() -> QSet<QString> & {
217 ✔
797
  static QSet<QString> scopes;
223 ✔
798
  return scopes;
217 ✔
799
}
800

801
auto Pass::scopePath(const QString &path) const -> QString {
217 ✔
802
  return QDir::cleanPath(QDir(m_settings.passStore).absoluteFilePath(path));
434 ✔
803
}
804

805
auto Pass::autoPushHeld() const -> bool {
57 ✔
806
  const QString store = scopePath(QString());
57 ✔
807
  const QSet<QString> &scopes = heldScopes();
57 ✔
808
  return std::any_of(scopes.cbegin(), scopes.cend(),
57 ✔
809
                     [&store](const QString &s) {
136 ✔
810
                       return isAtOrUnder(s, store, store + QLatin1Char('/'));
272 ✔
811
                     });
57 ✔
812
}
813

814
void Pass::GitPushAutomatic() {
11 ✔
815
  m_pushIsAutomatic = true;
11 ✔
816
  GitPush();
11 ✔
817
  m_pushIsAutomatic = false;
11 ✔
818
}
11 ✔
819

820
auto Pass::pushIsAutomatic() const -> bool { return m_pushIsAutomatic; }
4 ✔
821

822
void Pass::holdAutoPush(const QString &scope) {
86 ✔
823
  heldScopes().insert(scopePath(scope));
86 ✔
824
}
86 ✔
825

826
void Pass::releaseAutoPush(const QString &folder) {
74 ✔
827
  const QString root = scopePath(folder);
74 ✔
828
  QSet<QString> &scopes = heldScopes();
74 ✔
829
  for (auto it = scopes.begin(); it != scopes.end();) {
830
    it = isAtOrUnder(*it, root, root + QLatin1Char('/')) ? scopes.erase(it)
796 ✔
831
                                                         : std::next(it);
398 ✔
832
  }
833
}
74 ✔
834

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

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

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

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

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

972
void Pass::refuseAsNotPartOfStore(const QString &why) {
32 ✔
973
  // The interface arms itself when an operation starts and is released by
974
  // finished or processErrorExit; a refusal starts nothing, so emits both.
975
  emit startingExecuteWrapper();
32 ✔
976
  emit critical(tr("Not part of the store"), why);
32 ✔
977
  emit processErrorExit(1, why);
32 ✔
978
}
32 ✔
979

980
auto Pass::getGpgIdPath(const QString &for_file, const QString &passStore)
256 ✔
981
    -> QString {
982
  return nearestGpgId(gpgIdLookup(for_file, passStore))
512 ✔
983
      .value_or(
984
          QDir(QDir::fromNativeSeparators(passStore)).filePath(".gpg-id"));
1,024 ✔
985
}
986

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

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

1042
auto Pass::skippedGpgId(const QString &forFile, const QString &passStore,
81 ✔
1043
                        QString *recordError) -> std::optional<QString> {
1044
  const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
81 ✔
1045
  QDir dir = lookup.start;
81 ✔
1046
  // The same walk as nearestGpgId(), stopping at the list it finds, and
1047
  // short of the store root: the root's own list has no parent to fall
1048
  // back to, and the signature check refuses it when it is missing.
1049
  while (dir.exists() && QDir::cleanPath(dir.absolutePath())
324 ✔
1050
                             .startsWith(lookup.storePrefix, kPathCase)) {
108 ✔
1051
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
56 ✔
1052
    if (isOwnGpgId(candidate)) {
56 ✔
1053
      return std::nullopt;
18 ✔
1054
    }
1055
    // A link under the name (dangling or not), or nothing under it where
1056
    // this device accepted a list before: both are the folder's list gone,
1057
    // not a folder that never had one.
1058
    if (candidate.isSymLink() || candidate.isJunction()) {
38 ✔
1059
      return candidate.absoluteFilePath();
12 ✔
1060
    }
1061
    // An unreadable record is not "never seen": whether a list was accepted
1062
    // here cannot be told, so this folder is refused too (fail closed), with
1063
    // the record's own reason for the caller to show.
1064
    QString why;
32 ✔
1065
    const std::optional<qint64> seen =
1066
        GpgIdGeneration::remembered(candidate.absoluteFilePath(), &why);
64 ✔
1067
    if (!seen) {
32 ✔
1068
      if (recordError != nullptr) {
1 ✔
1069
        *recordError =
1070
            why.isEmpty()
1071
                ? tr("The generation record of the recipient lists cannot "
2 ✔
1072
                     "be read.")
1073
                : why;
1074
      }
1075
      return candidate.absoluteFilePath();
2 ✔
1076
    }
1077
    if (*seen > 0) {
31 ✔
1078
      return candidate.absoluteFilePath();
8 ✔
1079
    }
1080
    if (!dir.cdUp()) {
27 ✔
1081
      break;
1082
    }
1083
  }
56 ✔
1084
  return std::nullopt;
52 ✔
1085
}
81 ✔
1086

1087
namespace {
1088

1089
/// What the Users dialog may preselect for a verified list, given what the
1090
/// generation record says about it.
1091
auto judgedRecipients(GpgIdGeneration::Verdict verdict,
7 ✔
1092
                      const QByteArray &contents, const QString &gpgIdPath,
1093
                      const QString &why) -> Pass::RecipientsForEditing {
1094
  using RecipientsForEditing = Pass::RecipientsForEditing;
1095
  RecipientsForEditing result;
7 ✔
1096
  switch (verdict) {
7 ✔
1097
  case GpgIdGeneration::Verdict::Accepted:
1 ✔
1098
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1099
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1100
    break;
1 ✔
1101
  case GpgIdGeneration::Verdict::Rollback:
1 ✔
1102
    // Authentic and this folder's, only older: the recovery goes through
1103
    // this dialog, so it is preselected, with the reason in view.
1104
    result.state = RecipientsForEditing::State::VerifiedRollback;
1 ✔
1105
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1106
    result.warning = why;
1 ✔
1107
    break;
1 ✔
1108
  case GpgIdGeneration::Verdict::Unbound:
5 ✔
1109
  case GpgIdGeneration::Verdict::Conflict:
1110
  case GpgIdGeneration::Verdict::WrongFolder:
1111
  case GpgIdGeneration::Verdict::WrongStore:
1112
  case GpgIdGeneration::Verdict::Malformed:
1113
  case GpgIdGeneration::Verdict::RecordUnavailable:
1114
    // Signed, but not shown to be this folder's list, not a list to trust,
1115
    // or nothing to judge it by: preselecting it would sign it in.
1116
    result.state = RecipientsForEditing::State::Rejected;
5 ✔
1117
    result.warning =
1118
        Pass::tr("%1 Nothing is preselected: saving would sign whatever is "
5 ✔
1119
                 "in it. Select the recipients yourself.")
1120
            .arg(why);
10 ✔
1121
    break;
5 ✔
1122
  }
1123
  return result;
7 ✔
1124
}
1125

1126
} // namespace
1127

1128
auto Pass::recipientsForEditing(const QString &dir, const QString &passStore)
48 ✔
1129
    -> RecipientsForEditing {
1130
  RecipientsForEditing result;
48 ✔
1131
  const QString folder = dir.isEmpty() ? QString() : dir;
48 ✔
1132
  const QString gpgIdPath = getGpgIdPath(folder, passStore);
48 ✔
1133
  const GpgIdSigner signer(
1134
      m_settings.gpgExecutable,
1135
      GpgIdSigner::keysFromSetting(m_settings.passSigningKey));
144 ✔
1136
  if (!signer.enabled()) {
48 ✔
1137
    // A list that is there but cannot be read as one (too large, not a
1138
    // regular file, unreadable) is not an empty list: preselecting nothing
1139
    // without a word would let OK write a new list over it, and later
1140
    // re-encryptions drop whoever it named.
1141
    // Read once and parsed from those bytes: a second read could find
1142
    // something else under the name. A link counts as there, dangling too.
1143
    const QFileInfo info(gpgIdPath);
38 ✔
1144
    if (!info.exists() && !info.isSymLink()) {
38 ✔
1145
      result.state = RecipientsForEditing::State::Unsigned;
1146
      return result;
13 ✔
1147
    }
1148
    const std::optional<QByteArray> bytes =
1149
        Util::readRegularFile(gpgIdPath, Util::kMaxGpgIdBytes);
25 ✔
1150
    if (!bytes) {
25 ✔
1151
      result.state = RecipientsForEditing::State::Rejected;
2 ✔
1152
      result.warning =
1153
          tr("%1 cannot be read as a recipient list (a regular file of at "
2 ✔
1154
             "most %2), so nothing is preselected. Check it before choosing "
1155
             "recipients here: OK writes a new list over it.")
1156
              .arg(gpgIdPath,
2 ✔
1157
                   QLocale().formattedDataSize(Util::kMaxGpgIdBytes));
4 ✔
1158
      return result;
2 ✔
1159
    }
1160
    result.state = RecipientsForEditing::State::Unsigned;
1161
    result.recipients = parseRecipients(*bytes, gpgIdPath);
23 ✔
1162
    return result;
23 ✔
1163
  }
38 ✔
1164
  QString recordError;
10 ✔
1165
  if (const std::optional<QString> skipped =
10 ✔
1166
          skippedGpgId(folder, passStore, &recordError)) {
10 ✔
1167
    // The folder's own list was removed or replaced by a link (or the record
1168
    // that would tell cannot be read): the list the walk found further up
1169
    // was not signed for this folder, so preselecting it would sign it in
1170
    // here with one click.
1171
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1172
    result.warning =
1173
        recordError.isEmpty()
1174
            ? tr("The recipient list %1 is missing or is not a regular file, "
2 ✔
1175
                 "so nothing is preselected: the list of a parent folder was "
1176
                 "not signed for this one. Select this folder's recipients "
1177
                 "yourself; OK writes and signs a fresh list.")
1178
                  .arg(*skipped)
1179
            : tr("%1 Nothing is preselected: whether %2 was removed cannot "
1 ✔
1180
                 "be told.")
1181
                  .arg(recordError, *skipped);
1182
    return result;
1 ✔
1183
  }
1184
  if (!QFileInfo::exists(gpgIdPath)) {
9 ✔
1185
    // A folder without a list yet (new store, new profile): nothing to
1186
    // verify and nothing to preselect.
1187
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1188
    return result;
1 ✔
1189
  }
1190
  QByteArray contents;
8 ✔
1191
  if (!signer.verifyFile(gpgIdPath, &contents)) {
8 ✔
1192
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1193
    result.warning =
1194
        tr("The recipient list %1 does not verify against the signing key, "
1 ✔
1195
           "so nothing is preselected: saving would sign whatever is in it. "
1196
           "Select the recipients yourself; OK writes and signs a fresh list.")
1197
            .arg(gpgIdPath);
2 ✔
1198
    return result;
1 ✔
1199
  }
1200
  QString why;
7 ✔
1201
  const GpgIdGeneration::Verdict verdict =
1202
      GpgIdGeneration::accept(gpgIdPath, contents, passStore, &why);
7 ✔
1203
  return judgedRecipients(verdict, contents, gpgIdPath, why);
7 ✔
1204
}
48 ✔
1205

1206
auto Pass::getRecipientList(const QString &for_file, const QString &passStore)
8 ✔
1207
    -> QStringList {
1208
  const QString gpgIdPath = getGpgIdPath(for_file, passStore);
8 ✔
1209
  // The root .gpg-id comes back whatever it is; a link is not a list.
1210
  if (Util::isLinkedFolder(gpgIdPath)) {
8 ✔
1211
    return {};
1 ✔
1212
  }
1213
  const std::optional<QByteArray> bytes =
1214
      Util::readRegularFile(gpgIdPath, Util::kMaxGpgIdBytes);
7 ✔
1215
  if (!bytes) {
7 ✔
UNCOV
1216
    return {};
×
1217
  }
1218
  return parseRecipients(*bytes, gpgIdPath);
7 ✔
1219
}
1220

1221
auto Pass::parseRecipients(const QByteArray &contents,
160 ✔
1222
                           const QString &sourceName) -> QStringList {
1223
  QStringList recipients;
160 ✔
1224
  const QString text = QString::fromUtf8(contents);
1225
  for (const QString &line : text.split(QLatin1Char('\n'))) {
579 ✔
1226
    QString recipient = line.split(QLatin1Char('#')).first().trimmed();
838 ✔
1227
    if (recipient.isEmpty()) {
419 ✔
1228
      continue;
213 ✔
1229
    }
1230
    if (!Util::isValidKeyId(recipient)) {
206 ✔
1231
      // Never drop a recipient silently: the list is written back verbatim
1232
      // by UsersDialog, so a skipped line disappears from .gpg-id.
1233
      qCWarning(lcQtPass) << "Skipping unusable recipient in" << sourceName
4 ✔
1234
                          << ":" << recipient;
2 ✔
1235
      continue;
2 ✔
1236
    }
2 ✔
1237
    recipients += recipient;
1238
  }
1239
  return recipients;
160 ✔
1240
}
1241

1242
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
1243
 */
1244

1245
auto Pass::boundedRandom(quint32 bound) -> quint32 {
7,620 ✔
1246
  if (bound < 2) {
7,620 ✔
1247
    return 0;
1248
  }
1249

1250
  quint32 randval;
1251
  // arc4random_uniform-style rejection against modulo bias: drop values
1252
  // below 2^32 % bound, which (1 + ~bound) % bound computes in quint32.
1253
  const quint32 rejectionThreshold = (1 + ~bound) % bound;
7,616 ✔
1254

1255
  do {
1256
    randval = QRandomGenerator::system()->generate();
1257
  } while (randval < rejectionThreshold);
7,616 ✔
1258

1259
  return randval % bound;
7,616 ✔
1260
}
1261

1262
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,209 ✔
1263
    -> QString {
1264
  if (charset.isEmpty() || length == 0U) {
1,209 ✔
1265
    return {};
2 ✔
1266
  }
1267
  QString out;
1,207 ✔
1268
  for (unsigned int i = 0; i < length; ++i) {
8,827 ✔
1269
    out.append(charset.at(static_cast<int>(
7,620 ✔
1270
        boundedRandom(static_cast<quint32>(charset.length())))));
7,620 ✔
1271
  }
1272
  return out;
1273
}
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