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

IJHack / QtPass / 43475275928

13 Nov 2026 05:41PM UTC coverage: 92.709% (-0.02%) from 92.727%
43475275928

push

github

web-flow
coverage: let lcov ignore inconsistent data on system headers (#2136)

lcov 2.x on the CI runner (gcc 15 headers) fails the coverage job with
"lcov: ERROR: (inconsistent) ...: function ... is not hit but line ... has
a non-zero hit count" on files outside the project (e.g. /usr/include/c++/15
and Qt headers), aborting lcov_prepare before coverage of src/ is produced.

The captures already pass "--ignore-errors unused"; add "inconsistent" the
same way to the capture, extract and combine steps. Only the consistency
check on data that is filtered out anyway (-e src/*) is bypassed; src/
coverage is unchanged.

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

10452 of 11274 relevant lines covered (92.71%)

402.92 hits per line

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

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

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

25
#include "qtpasslogging.h"
26

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

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

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

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

57
  connect(&exec, &Executor::starting, this, &Pass::startingExecuteWrapper);
306 ✔
58
  connect(&exec, &Executor::drained, this, &Pass::idle);
306 ✔
59
  // Each queued process starts in the environment as the store is then:
60
  // the Git pin is judged at that moment (dequeuing() comes just before the
61
  // start, on this thread).
62
  connect(&exec, &Executor::dequeuing, this, [this](int, bool completes) {
306 ✔
63
    if (completes) {
162 ✔
64
      exec.setEnvironment(withCurrentGitPin(env));
159 ✔
65
    }
66
  });
162 ✔
67
  // Merge our vars into WSLENV rather than blindly appending a duplicate
68
  // entry. WSLENV flags: /p translates the path, /u forwards from Windows
69
  // into WSL only; /w would be the other direction, from WSL out, and leaves
70
  // pass inside WSL without the value. Everything updateEnv() sets for pass
71
  // has to cross, the signing key above all: without it pass does not check
72
  // the .gpg-id signature.
73
  const QStringList wslenvVars = {
74
      QStringLiteral("PASSWORD_STORE_DIR/p"),
612 ✔
75
      QStringLiteral("PASSWORD_STORE_SIGNING_KEY/u"),
306 ✔
76
      QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH/u"),
306 ✔
77
      QStringLiteral("PASSWORD_STORE_CHARACTER_SET/u"),
306 ✔
78
      QStringLiteral("PASSWORD_STORE_GPG_OPTS/u"),
306 ✔
79
      QStringLiteral("GIT_CEILING_DIRECTORIES/p"),
306 ✔
80
      QStringLiteral("GIT_LITERAL_PATHSPECS/u")};
2,448 ✔
81
  const QString existing = env.value(QStringLiteral("WSLENV"));
612 ✔
82
  if (existing.isEmpty()) {
306 ✔
83
    env.insert(QStringLiteral("WSLENV"), wslenvVars.join(':'));
610 ✔
84
  } else {
85
    QStringList parts = existing.split(':', Qt::SkipEmptyParts);
1 ✔
86
    for (const QString &v : wslenvVars) {
8 ✔
87
      if (!parts.contains(v))
7 ✔
88
        parts.append(v);
89
    }
90
    env.insert(QStringLiteral("WSLENV"), parts.join(':'));
2 ✔
91
  }
92
}
306 ✔
93

94
void Pass::executeWrapper(PROCESS id, const QString &app,
2 ✔
95
                          const QStringList &args, bool readStdout,
96
                          bool readStderr) {
97
  executeWrapper(id, app, args, QString(), readStdout, readStderr);
2 ✔
98
}
2 ✔
99

100
void Pass::executeWrapper(PROCESS id, const QString &app,
162 ✔
101
                          const QStringList &args, QString input,
102
                          bool readStdout, bool readStderr) {
103
  beforeExecute(id);
162 ✔
104
  qCDebug(lcQtPass) << app << loggableArgs(args);
162 ✔
105
  exec.execute(id, m_settings.passStore, app, args, std::move(input),
162 ✔
106
               readStdout, readStderr);
107
}
162 ✔
108

109
auto Pass::loggableArgs(const QStringList &args) -> QStringList {
4 ✔
110
  // Secrets travel on stdin (Insert's content, KeygenDialog's batch file),
111
  // never in argv; this keeps the log honest should that ever change.
112
  static const QStringList secretOptions{
113
      QStringLiteral("--passphrase"), QStringLiteral("--override-session-key")};
13 ✔
114
  QStringList out;
4 ✔
115
  bool hide = false;
116
  for (const QString &arg : args) {
12 ✔
117
    if (hide) {
8 ✔
118
      out << QStringLiteral("<redacted>");
1 ✔
119
      hide = false;
120
      continue;
1 ✔
121
    }
122
    if (arg.startsWith(QStringLiteral("otpauth://"))) {
14 ✔
123
      out << QStringLiteral("<redacted>");
1 ✔
124
      continue;
1 ✔
125
    }
126
    if (arg.startsWith(QStringLiteral("--passphrase=")) ||
12 ✔
127
        arg.startsWith(QStringLiteral("--override-session-key="))) {
11 ✔
128
      out << arg.left(arg.indexOf(u'=') + 1) + QStringLiteral("<redacted>");
2 ✔
129
      continue;
1 ✔
130
    }
131
    hide = secretOptions.contains(arg);
132
    out << arg;
133
  }
134
  return out;
4 ✔
135
}
136

137
void Pass::beforeExecute(PROCESS /*id*/) {}
29 ✔
138

139
void Pass::init(const AppSettings &settings) {
576 ✔
140
  m_settings = settings;
576 ✔
141
#ifdef __APPLE__
142
  // If it exists, prepend gpgtools to PATH
143
  if (QFile(QStringLiteral("/usr/local/MacGPG2/bin")).exists())
144
    env.insert(QStringLiteral("PATH"),
145
               QStringLiteral("/usr/local/MacGPG2/bin:") +
146
                   env.value(QStringLiteral("PATH")));
147
  // Add missing /usr/local/bin (exact component match, no leading colon)
148
  const QString currentPath = env.value(QStringLiteral("PATH"));
149
  if (!currentPath.split(':', Qt::SkipEmptyParts)
150
           .contains(QStringLiteral("/usr/local/bin"))) {
151
    env.insert(QStringLiteral("PATH"),
152
               currentPath.isEmpty()
153
                   ? QStringLiteral("/usr/local/bin")
154
                   : QStringLiteral("/usr/local/bin:") + currentPath);
155
  }
156
#endif
157

158
  // The configured gpgHome wins over GNUPGHOME only when it exists: a stale
159
  // one (#1711) fails every gpg call with "No secret key". Clearing the
160
  // setting restores the inherited value rather than keeping the old path.
161
  const QString inheritedHome = QProcessEnvironment::systemEnvironment().value(
1,152 ✔
162
      QStringLiteral("GNUPGHOME"));
1,152 ✔
163
  const auto useInheritedHome = [this, &inheritedHome]() {
536 ✔
164
    if (inheritedHome.isEmpty()) {
536 ✔
165
      env.remove(QStringLiteral("GNUPGHOME"));
734 ✔
166
    } else {
167
      env.insert(QStringLiteral("GNUPGHOME"), inheritedHome);
338 ✔
168
    }
169
  };
1,112 ✔
170
  if (m_settings.gpgHome.isEmpty()) {
576 ✔
171
    useInheritedHome();
534 ✔
172
  } else {
173
    QDir absHome(m_settings.gpgHome);
42 ✔
174
    absHome.makeAbsolute();
42 ✔
175
    if (absHome.exists()) {
42 ✔
176
      env.insert(QStringLiteral("GNUPGHOME"), absHome.path());
80 ✔
177
    } else {
178
      if (inheritedHome.isEmpty()) {
2 ✔
179
        qCWarning(lcQtPass) << "gpgHome" << absHome.path()
2 ✔
180
                            << "does not exist; using the default GnuPG home";
1 ✔
181
        emit statusMsg(tr("Configured GPG home %1 does not exist, using the "
1 ✔
182
                          "default keyring")
183
                           .arg(absHome.path()),
2 ✔
184
                       5000);
185
      } else {
186
        qCWarning(lcQtPass)
2 ✔
187
            << "gpgHome" << absHome.path() << "does not exist; using GNUPGHOME"
2 ✔
188
            << inheritedHome << "from the environment";
1 ✔
189
        emit statusMsg(tr("Configured GPG home %1 does not exist, using "
1 ✔
190
                          "GNUPGHOME %2 from the environment")
191
                           .arg(absHome.path(), inheritedHome),
2 ✔
192
                       5000);
193
      }
194
      useInheritedHome();
2 ✔
195
    }
196
  }
42 ✔
197
}
576 ✔
198

199
auto Pass::generatePassword(unsigned int length, const QString &charset)
1,211 ✔
200
    -> QString {
201
  if (length == 0) {
1,211 ✔
202
    emit critical(tr("Invalid password length"),
2 ✔
203
                  tr("Can't generate password with zero length."));
1 ✔
204
    return {};
1 ✔
205
  }
206
  QString passwd;
1,210 ✔
207
  if (m_settings.usePwgen) {
1,210 ✔
208
    // --secure goes first as it overrides --no-* otherwise
209
    QStringList args;
3 ✔
210
    args.append("-1");
3 ✔
211
    if (!m_settings.lessRandom) {
3 ✔
212
      args.append("--secure");
4 ✔
213
    }
214
    args.append(m_settings.avoidCapitals ? "--no-capitalize" : "--capitalize");
5 ✔
215
    args.append(m_settings.avoidNumbers ? "--no-numerals" : "--numerals");
5 ✔
216
    if (m_settings.useSymbols) {
3 ✔
217
      args.append("--symbols");
2 ✔
218
    }
219
    args.append(QString::number(length));
3 ✔
220
    if (Executor::executeBlocking(m_settings.pwgenExecutable, args, &passwd) ==
3 ✔
221
        0) {
222
      static const QRegularExpression literalNewLines{"[\\n\\r]"};
3 ✔
223
      passwd.remove(literalNewLines);
2 ✔
224
    } else {
225
      passwd.clear();
1 ✔
226
      qCDebug(lcQtPass) << "pwgen fail";
1 ✔
227
    }
228
  } else {
229
    // An empty CUSTOM charset falls back to ALLCHARS, not a weak password
230
    // (#780).
231
    const QString cs = fallbackCharset(
232
        charset, m_settings.passwordConfiguration
233
                     .Characters[PasswordConfiguration::ALLCHARS]);
1,207 ✔
234
    if (cs.length() > 0) {
1,207 ✔
235
      passwd = generateRandomPassword(cs, length);
2,412 ✔
236
    } else {
237
      emit critical(
1 ✔
238
          tr("No characters chosen"),
1 ✔
239
          tr("Can't generate password, there are no characters to choose from "
1 ✔
240
             "set in the configuration!"));
241
    }
242
  }
243
  return passwd;
244
}
245

246
bool Pass::gpgSupportsEd25519(const QString &gpgExecutable) {
33 ✔
247
  const QString exe =
248
      gpgExecutable.isEmpty() ? QStringLiteral("gpg") : gpgExecutable;
33 ✔
249
  QString out, err;
33 ✔
250
  if (Executor::executeBlocking(exe, {"--version"}, &out, &err) != 0) {
132 ✔
251
    return false;
252
  }
253
  QRegularExpression versionRegex(R"(gpg \(GnuPG\) (\d+)\.(\d+))");
31 ✔
254
  QRegularExpressionMatch match = versionRegex.match(out);
31 ✔
255
  if (!match.hasMatch()) {
31 ✔
256
    return false;
257
  }
258
  int major = match.captured(1).toInt();
30 ✔
259
  int minor = match.captured(2).toInt();
30 ✔
260
  return major > 2 || (major == 2 && minor >= 1);
30 ✔
261
}
31 ✔
262

263
// ed25519 (GnuPG 2.1+) generates much faster than RSA.
264
QString Pass::getDefaultKeyTemplate(const QString &gpgExecutable) {
29 ✔
265
  if (gpgSupportsEd25519(gpgExecutable)) {
29 ✔
266
    return QStringLiteral("%echo Generating a default key\n"
26 ✔
267
                          "Key-Type: EdDSA\n"
268
                          "Key-Curve: Ed25519\n"
269
                          "Subkey-Type: ECDH\n"
270
                          "Subkey-Curve: Curve25519\n"
271
                          "Name-Real: \n"
272
                          "Name-Comment: QtPass\n"
273
                          "Name-Email: \n"
274
                          "Expire-Date: 0\n"
275
                          "%no-protection\n"
276
                          "%commit\n"
277
                          "%echo done");
278
  }
279
  return QStringLiteral("%echo Generating a default key\n"
3 ✔
280
                        "Key-Type: RSA\n"
281
                        "Subkey-Type: RSA\n"
282
                        "Name-Real: \n"
283
                        "Name-Comment: QtPass\n"
284
                        "Name-Email: \n"
285
                        "Expire-Date: 0\n"
286
                        "%no-protection\n"
287
                        "%commit\n"
288
                        "%echo done");
289
}
290

291
namespace {
292
auto resolveWslGpgconfPath(const QString &lastPart) -> QString {
8 ✔
293
  qsizetype lastSep = lastPart.lastIndexOf('/');
8 ✔
294
  if (lastSep < 0) {
8 ✔
295
    lastSep = lastPart.lastIndexOf('\\');
5 ✔
296
  }
297
  if (lastSep >= 0) {
5 ✔
298
    return lastPart.left(lastSep + 1) + "gpgconf";
6 ✔
299
  }
300
  return QStringLiteral("gpgconf");
5 ✔
301
}
302

303
QString findGpgconfInGpgDir(const QString &gpgPath) {
8 ✔
304
  QFileInfo gpgInfo(gpgPath);
8 ✔
305
  if (!gpgInfo.isAbsolute()) {
8 ✔
306
    return {};
1 ✔
307
  }
308

309
  QDir dir(gpgInfo.absolutePath());
7 ✔
310

311
#ifdef Q_OS_WIN
312
  QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
313
  if (candidateExe.isExecutable()) {
314
    return candidateExe.filePath();
315
  }
316
#endif
317

318
  QFileInfo candidate(dir.filePath("gpgconf"));
7 ✔
319
  if (candidate.isExecutable()) {
7 ✔
320
    return candidate.filePath();
5 ✔
321
  }
322
  return {};
2 ✔
323
}
8 ✔
324

325
} // namespace
326

327
auto Pass::resolveGpgconfCommand(const QString &gpgPath)
22 ✔
328
    -> ResolvedGpgconfCommand {
329
  if (gpgPath.trimmed().isEmpty()) {
22 ✔
330
    return {"gpgconf", {}};
331
  }
332

333
  // WSL: gpgconf next to the configured gpg, same distribution, via --exec
334
  // not the shell. An unparsed form (`wsl sh -c ...`, bare `wsl`) falls back
335
  // to gpgconf on the Windows PATH.
336
  if (const auto wsl = Executor::parseWslCommand(gpgPath)) {
21 ✔
337
    if (!QFileInfo(wsl->command).fileName().startsWith("gpg")) {
18 ✔
338
      return {"gpgconf", {}};
339
    }
340
    const auto gpgconf = wsl->with(resolveWslGpgconfPath(wsl->command));
16 ✔
341
    return {gpgconf.launcher, gpgconf.argv({})};
×
342
  }
8 ✔
343

344
  const QStringList parts = QProcess::splitCommand(gpgPath);
12 ✔
345
  if (parts.isEmpty()) {
12 ✔
346
    return {"gpgconf", {}};
347
  }
348
  const QString first = parts.first();
349
  if (QFileInfo(first).fileName().compare("wsl", Qt::CaseInsensitive) == 0 ||
33 ✔
350
      QFileInfo(first).fileName().compare("wsl.exe", Qt::CaseInsensitive) ==
30 ✔
351
          0) {
352
    return {"gpgconf", {}};
353
  }
354

355
  if (!first.contains('/') && !first.contains('\\')) {
9 ✔
356
    return {"gpgconf", {}};
357
  }
358

359
  QString gpgconfPath = findGpgconfInGpgDir(first);
8 ✔
360
  if (!gpgconfPath.isEmpty()) {
8 ✔
361
    return {gpgconfPath, {}};
5 ✔
362
  }
363

364
  return {"gpgconf", {}};
365
}
22 ✔
366

367
void Pass::GenerateGPGKeys(QString batch) {
11 ✔
368
  const QString gpgPath = m_settings.gpgExecutable;
369
  if (gpgPath.isEmpty()) {
11 ✔
370
    // The executor would fail an empty executable with a generic process
371
    // error; the keygen dialog waits for generateGPGKeysFailed and a reason
372
    // it can show. Queued so we do not re-enter KeygenDialog::done(), which
373
    // drives key generation synchronously.
374
    QMetaObject::invokeMethod(
9 ✔
375
        this,
376
        [this]() {
9 ✔
377
          emit generateGPGKeysFailed(tr("No GPG executable configured"));
5 ✔
378
          emit processErrorExit(1, tr("No GPG executable configured"));
5 ✔
379
        },
5 ✔
380
        Qt::QueuedConnection);
381
    return;
382
  }
383

384
  // A stale gpg-agent holding the key database lock causes "database locked"
385
  // timeouts during key generation.
386
  ResolvedGpgconfCommand resolvedGpgconf = resolveGpgconfCommand(gpgPath);
2 ✔
387
  QStringList killArgs = resolvedGpgconf.arguments;
388
  killArgs << "--kill";
2 ✔
389
  killArgs << "gpg-agent";
2 ✔
390
  // Use same environment as key generation to target correct gpg-agent
391
  if (Executor::executeBlocking(env, resolvedGpgconf.program, killArgs) != 0) {
2 ✔
392
    qCWarning(lcQtPass) << "Failed to kill gpg-agent";
2 ✔
393
  }
394

395
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
16 ✔
396
                 std::move(batch), true, true);
397
}
398

399
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
101 ✔
400
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
707 ✔
401
  args.append(secret ? "--list-secret-keys" : "--list-keys");
263 ✔
402

403
  for (const QString &keystring : std::as_const(keystrings)) {
209 ✔
404
    if (!keystring.isEmpty()) {
108 ✔
405
      args.append(keystring);
406
    }
407
  }
408
  QString p_out;
101 ✔
409
  if (Executor::executeBlocking(m_settings.gpgExecutable, args, &p_out) != 0) {
101 ✔
410
    return {};
3 ✔
411
  }
412
  return parseGpgColonOutput(p_out, secret);
98 ✔
413
}
414

415
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
82 ✔
416
  return listKeys(QStringList(keystring), secret);
164 ✔
417
}
418

419
namespace {
420

421
auto containsAny(const QString &str, const QStringList &patterns) -> bool {
88 ✔
422
  for (const QString &p : patterns) {
245 ✔
423
    if (str.contains(p)) {
168 ✔
424
      return true;
425
    }
426
  }
427
  return false;
428
}
429

430
// @p patterns must already be lowercase; only @p str is lowered.
431
auto containsAnyCaseInsensitive(const QString &str, const QStringList &patterns)
93 ✔
432
    -> bool {
433
  const QString lower = str.toLower();
434
  for (const QString &p : patterns) {
230 ✔
435
    if (lower.contains(p)) {
147 ✔
436
      return true;
437
    }
438
  }
439
  return false;
440
}
441

442
} // namespace
443

444
auto gpgErrorMessage(const QString &err) -> QString {
34 ✔
445
  // Machine-readable status tokens added by --status-fd 2
446
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYEXPIRED"),
170 ✔
447
                        QStringLiteral("[GNUPG:] INV_RECP 5 ")}))
34 ✔
448
    return QCoreApplication::translate(
449
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
450
                "replace it.");
5 ✔
451
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYREVOKED"),
145 ✔
452
                        QStringLiteral("[GNUPG:] INV_RECP 4 ")}))
29 ✔
453
    return QCoreApplication::translate(
454
        "Pass", "Encryption failed: GPG key has been revoked.");
4 ✔
455
  if (containsAny(err, {QStringLiteral("[GNUPG:] NO_PUBKEY"),
125 ✔
456
                        QStringLiteral("[GNUPG:] INV_RECP")}))
25 ✔
457
    return QCoreApplication::translate(
458
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
459
                "Check that the key ID in .gpg-id is correct and imported.");
2 ✔
460
  if (err.contains(QStringLiteral("[GNUPG:] FAILURE")))
23 ✔
461
    return QCoreApplication::translate(
462
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
463

464
  // Locale-dependent fallbacks
465
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has expired"),
88 ✔
466
                                       QLatin1String("key expired")}))
467
    return QCoreApplication::translate(
468
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
469
                "replace it.");
1 ✔
470
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has been revoked"),
84 ✔
471
                                       QLatin1String("revoked")}))
472
    return QCoreApplication::translate(
473
        "Pass", "Encryption failed: GPG key has been revoked.");
1 ✔
474
  // pass passes no --status-fd, so this is all gpg says about a key that is
475
  // present but cannot encrypt: expired, revoked, without an encryption
476
  // subkey, or not trusted ("There is no assurance this key belongs to the
477
  // named user"). "Not found ... imported" would send the user the wrong
478
  // way; gpg's own lines, shown below this, say which it is.
479
  if (containsAnyCaseInsensitive(err, {QLatin1String("unusable public key")}))
60 ✔
480
    return QCoreApplication::translate(
481
        "Pass", "Encryption failed: a recipient's GPG key cannot be used. It "
482
                "may have expired or been revoked, have no encryption subkey, "
483
                "or not be trusted; gpg's message below says which.");
3 ✔
484
  if (containsAnyCaseInsensitive(err, {QLatin1String("no public key"),
68 ✔
485
                                       QLatin1String("no secret key")}))
486
    return QCoreApplication::translate(
487
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
488
                "Check that the key ID in .gpg-id is correct and imported.");
4 ✔
489
  if (containsAnyCaseInsensitive(err, {QLatin1String("encryption failed")}))
39 ✔
490
    return QCoreApplication::translate(
491
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
492

493
  return {};
12 ✔
494
}
×
495

496
void Pass::finished(int id, int exitCode, const QString &out,
170 ✔
497
                    const QString &err) {
498
  auto pid = static_cast<PROCESS>(id);
170 ✔
499

500
  // Pop the Show() this completion belongs to whether it worked or not, or
501
  // the next result would be attributed to the wrong file.
502
  QString shownFile;
170 ✔
503
  if (pid == PASS_SHOW && !m_pendingShows.isEmpty()) {
170 ✔
504
    shownFile = m_pendingShows.dequeue();
45 ✔
505
  }
506

507
  if (exitCode != 0) {
170 ✔
508
    handleProcessError(pid, exitCode, out, err);
35 ✔
509
    return;
510
  }
511

512
  if (pid == PASS_SHOW) {
135 ✔
513
    emit finishedShow(out, shownFile);
32 ✔
514
    return;
515
  }
516
  emitProcessFinishedSignal(pid, out, err);
103 ✔
517
}
518

519
void Pass::handleProcessError(PROCESS pid, int exitCode, const QString &out,
35 ✔
520
                              const QString &err) {
521
  Q_UNUSED(out);
522

523
  if (pid == PASS_INSERT) {
35 ✔
524
    const QString friendly = gpgErrorMessage(err);
16 ✔
525
    const QString why =
526
        friendly.isEmpty() ? err : formatInsertError(friendly, err);
16 ✔
527
    const bool written = insertWritten(err);
16 ✔
528
    emit insertFailed(why, written);
16 ✔
529
    if (written) {
16 ✔
530
      // The entry is in the store; a git step after it failed (a commit
531
      // that could not be signed, with pass.signcommits, say). The dialog
532
      // closes on this, so say it here rather than only in the output
533
      // panel.
534
      emit critical(tr("Saved, not committed"),
8 ✔
535
                    tr("The entry is saved in the store, but recording it "
4 ✔
536
                       "in git failed. What was reported:\n\n%1")
537
                        .arg(err.trimmed()));
8 ✔
538
    }
539
    emit processErrorExit(exitCode, why);
16 ✔
540
    return;
541
  }
542

543
  if (pid == GPG_GENKEYS) {
19 ✔
544
    emit generateGPGKeysFailed(err);
1 ✔
545
  }
546
  emit processErrorExit(exitCode, err);
19 ✔
547
}
548

549
auto Pass::formatInsertError(const QString &friendly, const QString &err)
5 ✔
550
    -> QString {
551
  QStringList humanLines;
5 ✔
552
  for (const QString &line : err.split('\n')) {
23 ✔
553
    QString cleanedLine = line;
554
    cleanedLine.remove('\r');
13 ✔
555
    if (!cleanedLine.startsWith(QLatin1String("[GNUPG:]")))
13 ✔
556
      humanLines.append(cleanedLine);
557
  }
558
  const QString humanErr = humanLines.join('\n').trimmed();
10 ✔
559
  return humanErr.isEmpty() ? friendly : friendly + "\n\n" + humanErr;
15 ✔
560
}
561

562
void Pass::emitProcessFinishedSignal(PROCESS pid, const QString &out,
103 ✔
563
                                     const QString &err) {
564
  // Only output that cannot contain a secret reaches the generic listeners
565
  // (the output panel among them); Enums::processInfo is the one table.
566
  if (pid >= 0 && pid < Enums::PROCESS_COUNT &&
103 ✔
567
      !Enums::processInfo(pid).secret) {
101 ✔
568
    emit finishedAnyWithPid(out, err, pid);
41 ✔
569
  }
570

571
  // The kind-specific signal. PASS_SHOW is emitted by finished(), which
572
  // knows the file. Content search runs in-process (NativeGrep), not
573
  // through `pass grep`, and emits finishedGrep itself.
574
  using Signal = void (Pass::*)(const QString &, const QString &);
575
  static const QHash<int, Signal> kSignals{
576
      {GIT_INIT, &Pass::finishedGitInit},
577
      {GIT_PULL, &Pass::finishedGitPull},
578
      {GIT_PUSH, &Pass::finishedGitPush},
579
      {PASS_INSERT, &Pass::finishedInsert},
580
      {PASS_REMOVE, &Pass::finishedRemove},
581
      {PASS_INIT, &Pass::finishedInit},
582
      {PASS_MOVE, &Pass::finishedMove},
583
      {PASS_COPY, &Pass::finishedCopy},
584
      {GPG_GENKEYS, &Pass::finishedGenerateGPGKeys},
585
  };
109 ✔
586
  if (const Signal signal = kSignals.value(pid, nullptr)) {
103 ✔
587
    (this->*signal)(out, err);
99 ✔
588
  }
589
}
103 ✔
590

591
void Pass::setEnvVar(const QString &name, const QString &value) {
2,764 ✔
592
  if (value.isEmpty())
2,764 ✔
593
    env.remove(name);
918 ✔
594
  else
595
    env.insert(name, value);
1,846 ✔
596
}
2,764 ✔
597

598
void Pass::updateEnv() {
306 ✔
599
  setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY"),
612 ✔
600
            m_settings.passSigningKey);
306 ✔
601
  setEnvVar(QStringLiteral("PASSWORD_STORE_DIR"), m_settings.passStore);
612 ✔
602
  // Every path QtPass hands git names one file or folder: an entry called
603
  // "a*.gpg" must not make `git rm -f -- a*.gpg` remove every entry that
604
  // matches. Also reaches the git that pass runs, which passes names the
605
  // same way.
606
  setEnvVar(QStringLiteral("GIT_LITERAL_PATHSPECS"), QStringLiteral("1"));
612 ✔
607

608
  const PasswordConfiguration &passConfig = m_settings.passwordConfiguration;
306 ✔
609
  setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH"),
612 ✔
610
            QString::number(passConfig.length));
306 ✔
611

612
  setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET"),
612 ✔
613
            effectiveCharset(passConfig));
306 ✔
614

615
  // pass hands PASSWORD_STORE_GPG_OPTS to every gpg it runs: the user's own
616
  // options (split as pass's shell splits them: spaces, tabs, newlines),
617
  // then the output limit ImitatePass passes directly.
618
  QStringList gpgOpts = QProcessEnvironment::systemEnvironment()
306 ✔
619
                            .value(QStringLiteral("PASSWORD_STORE_GPG_OPTS"))
612 ✔
620
                            .split(QRegularExpression(QStringLiteral("\\s+")),
612 ✔
621
                                   Qt::SkipEmptyParts);
612 ✔
622
  gpgOpts << maxOutputArgs();
612 ✔
623
  setEnvVar(QStringLiteral("PASSWORD_STORE_GPG_OPTS"),
612 ✔
624
            gpgOpts.join(QLatin1Char(' ')));
306 ✔
625

626
  // As pass does: git never looks for a repository above the store's own
627
  // parent. A store that is not a repository itself but lies inside one (a
628
  // dotfiles repository in the home folder) would otherwise have its entries
629
  // committed and pushed there by native git mode. Only in the environment
630
  // of the processes QtPass runs for the store, never QtPass's own, which a
631
  // file manager or terminal it opens would inherit. pass sets its own
632
  // ceiling whatever this says. A store kept inside a larger repository on
633
  // purpose opts out (gitUseParentRepository), and then, as without a
634
  // store, whatever ceiling QtPass was started with applies.
635
  // A ceiling git cannot take as one entry (the parent's path holds the
636
  // list separator) is backed by GIT_DIR and GIT_WORK_TREE naming the
637
  // store's own repository (Util::gitStoreVariables()); pass unsets those
638
  // for itself and keeps its own ceiling.
639
  setEnvVar(QStringLiteral("GIT_DIR"), QString());
612 ✔
640
  setEnvVar(QStringLiteral("GIT_WORK_TREE"), QString());
612 ✔
641
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
306 ✔
642
    setEnvVar(QStringLiteral("GIT_CEILING_DIRECTORIES"),
34 ✔
643
              qEnvironmentVariable("GIT_CEILING_DIRECTORIES"));
34 ✔
644
  } else {
645
    for (const auto &[name, value] : Util::gitStoreVariables(
646
             m_settings.passStore, m_settings.gitExecutable)) {
871 ✔
647
      setEnvVar(name, value);
293 ✔
648
    }
649
  }
650

651
  exec.setEnvironment(env);
306 ✔
652
}
306 ✔
653

654
auto Pass::withCurrentGitPin(QProcessEnvironment base) const
736 ✔
655
    -> QProcessEnvironment {
656
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
736 ✔
657
    return base;
×
658
  }
659
  base.remove(QStringLiteral("GIT_DIR"));
1,472 ✔
660
  base.remove(QStringLiteral("GIT_WORK_TREE"));
1,472 ✔
661
  for (const auto &[name, value] : Util::gitStoreVariables(
662
           m_settings.passStore, m_settings.gitExecutable)) {
2,218 ✔
663
    base.insert(name, value);
746 ✔
664
  }
665
  return base;
736 ✔
666
}
667

668
auto Pass::maxOutputArgs() -> QStringList {
894 ✔
669
  return {QStringLiteral("--max-output"), QString::number(kMaxPlaintextBytes)};
2,682 ✔
670
}
894 ✔
671

672
namespace {
673
/// File names compare the way the platform's file system compares them:
674
/// "C:/Store" and "c:/store" are the same directory on Windows.
675
#ifdef Q_OS_WIN
676
constexpr auto kPathCase = Qt::CaseInsensitive;
677
#else
678
constexpr auto kPathCase = Qt::CaseSensitive;
679
#endif
680

681
/// Whether @p path is @p dir or lies under it.
682
auto isAtOrUnder(const QString &path, const QString &dir,
640 ✔
683
                 const QString &dirPrefix) -> bool {
684
  return path.compare(dir, kPathCase) == 0 ||
1,033 ✔
685
         path.startsWith(dirPrefix, kPathCase);
393 ✔
686
}
687

688
/// Where the lookup of a .gpg-id starts and the store that bounds it.
689
struct GpgIdLookup {
690
  QDir start;
691
  QString storeDir;
692
  QString storePrefix;
693
};
694

695
/// The folder whose list @p for_file wants: its own for a folder, its
696
/// folder's for an entry.
697
auto gpgIdLookup(const QString &for_file, const QString &passStore)
315 ✔
698
    -> GpgIdLookup {
699
  const QString normalizedFile = QDir::fromNativeSeparators(for_file);
315 ✔
700
  // Inside the store means at a path boundary: "/store-other/x" is not
701
  // under "/store", however the prefix compares.
702
  const QString storeDir =
703
      QDir::cleanPath(QDir::fromNativeSeparators(passStore));
315 ✔
704
  const QString storePrefix = storeDir.endsWith(QLatin1Char('/'))
315 ✔
705
                                  ? storeDir
315 ✔
706
                                  : storeDir + QLatin1Char('/');
315 ✔
707
  const QString cleanFile = QDir::cleanPath(normalizedFile);
315 ✔
708
  const bool insideStore = isAtOrUnder(cleanFile, storeDir, storePrefix);
315 ✔
709
  // A relative name is one inside the store; an absolute path outside it
710
  // stays what it is and the walk stops at once.
711
  const QString fullPath = insideStore || QDir::isAbsolutePath(cleanFile)
15 ✔
712
                               ? cleanFile
315 ✔
713
                               : storePrefix + cleanFile;
10 ✔
714
  // A folder (trailing separator, which cleanPath() dropped, or an existing
715
  // directory) wants its own list; an entry wants its folder's.
716
  const bool isFolder =
717
      normalizedFile.endsWith(QLatin1Char('/')) || QFileInfo(fullPath).isDir();
315 ✔
718
  // A folder that does not exist yet (an entry saved into a new folder, a
719
  // move to one) starts the walk at its nearest existing ancestor in the
720
  // store, as pass's set_gpg_recipients does: otherwise the walk ended at
721
  // once and the store root's list was taken over the one in between.
722
  QString start = isFolder ? fullPath : QFileInfo(fullPath).absolutePath();
315 ✔
723
  while (!QFileInfo(start).exists() &&
327 ✔
724
         isAtOrUnder(QDir::cleanPath(start), storeDir, storePrefix) &&
648 ✔
725
         QDir::cleanPath(start) != storeDir) {
327 ✔
726
    start = QFileInfo(start).absolutePath();
12 ✔
727
  }
728
  return {QDir(start), storeDir, storePrefix};
315 ✔
729
}
315 ✔
730

731
/// Whether @p candidate can be its folder's .gpg-id. A link under the name
732
/// is not: whoever planted it chose the recipients elsewhere.
733
auto isOwnGpgId(const QFileInfo &candidate) -> bool {
346 ✔
734
  return candidate.exists() && !candidate.isSymLink() &&
577 ✔
735
         !candidate.isJunction();
231 ✔
736
}
737

738
/// Walk up from the lookup's start to the first folder inside the store
739
/// that has its own .gpg-id; nothing when none does. A link under the name
740
/// is skipped, so the parent's list applies instead.
741
auto nearestGpgId(const GpgIdLookup &lookup) -> std::optional<QString> {
238 ✔
742
  QDir dir = lookup.start;
238 ✔
743
  while (dir.exists() && isAtOrUnder(QDir::cleanPath(dir.absolutePath()),
1,276 ✔
744
                                     lookup.storeDir, lookup.storePrefix)) {
319 ✔
745
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
294 ✔
746
    if (isOwnGpgId(candidate)) {
294 ✔
747
      return candidate.absoluteFilePath();
213 ✔
748
    }
749
    if (!dir.cdUp()) {
81 ✔
750
      break;
751
    }
752
  }
294 ✔
753
  return std::nullopt;
25 ✔
754
}
238 ✔
755

756
} // namespace
757

758
auto Pass::refuseLinkedPath(const QString &path, LinkScope scope,
421 ✔
759
                            PathSpelling spelling) -> bool {
760
  const QString full = QDir::isAbsolutePath(path)
761
                           ? path
421 ✔
762
                           : QDir(m_settings.passStore).filePath(path);
76 ✔
763
  // The link check below walks only under the store as configured: a path
764
  // spelled through the root's link target would get no more than the
765
  // entry itself judged. No caller makes one; say so if one starts to.
766
  if (spelling == PathSpelling::Configured &&
697 ✔
767
      PathValidator::isTargetSpelled(m_settings.passStore, full)) {
276 ✔
768
    qCWarning(lcQtPass)
4 ✔
769
        << "Path spelled through the store root's link target, not as the "
770
           "store is configured; Pass operations expect the configured "
771
           "spelling:"
2 ✔
772
        << full;
2 ✔
773
  }
774
  if (!Util::isUnderLink(full, m_settings.passStore,
421 ✔
775
                         scope == LinkScope::EntryAndParents)) {
776
    return false;
777
  }
778
  const QString why =
779
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
×
780
         "points to is not part of the password store and is left alone.")
781
          .arg(QDir::toNativeSeparators(QDir::cleanPath(full)));
54 ✔
782
  refuseAsNotPartOfStore(why);
27 ✔
783
  return true;
784
}
785

786
auto Pass::refuseFolderOutsideStore(const QString &folder, QString *relative)
46 ✔
787
    -> bool {
788
  if (const std::optional<QString> inStore =
46 ✔
789
          PathValidator::storeRelativePath(m_settings.passStore, folder)) {
46 ✔
790
    if (relative != nullptr) {
41 ✔
791
      *relative = *inStore;
41 ✔
792
    }
793
    return false;
794
  }
795
  refuseAsNotPartOfStore(
5 ✔
796
      tr("%1 is not inside the password store. Recipients are set for the "
5 ✔
797
         "store or a folder in it.")
798
          .arg(QDir::toNativeSeparators(QDir::cleanPath(folder))));
10 ✔
799
  return true;
5 ✔
800
}
801

802
void Pass::refuseAsNotPartOfStore(const QString &why) {
32 ✔
803
  // The interface arms itself when an operation starts and is released by
804
  // finished or processErrorExit; a refusal starts nothing, so emits both.
805
  emit startingExecuteWrapper();
32 ✔
806
  emit critical(tr("Not part of the store"), why);
32 ✔
807
  emit processErrorExit(1, why);
32 ✔
808
}
32 ✔
809

810
auto Pass::getGpgIdPath(const QString &for_file, const QString &passStore)
238 ✔
811
    -> QString {
812
  return nearestGpgId(gpgIdLookup(for_file, passStore))
476 ✔
813
      .value_or(
814
          QDir(QDir::fromNativeSeparators(passStore)).filePath(".gpg-id"));
952 ✔
815
}
816

817
auto Pass::refuseSkippedGpgId(const QString &file, bool signing,
152 ✔
818
                              const QString &except) -> bool {
819
  // Without a signing key the parent's list applies, as it does for pass.
820
  if (!signing) {
152 ✔
821
    return false;
822
  }
823
  QString recordError;
56 ✔
824
  const std::optional<QString> skipped =
825
      skippedGpgId(file, m_settings.passStore, &recordError);
56 ✔
826
  if (!skipped || (!except.isEmpty() &&
56 ✔
827
                   QDir::cleanPath(*skipped) == QDir::cleanPath(except))) {
58 ✔
828
    return false;
829
  }
830
  // The strings keep the context they were translated in.
831
  if (!recordError.isEmpty()) {
5 ✔
832
    emit critical(QCoreApplication::translate(
×
833
                      "ImitatePass", "Cannot check the recipient list"),
834
                  QCoreApplication::translate(
×
835
                      "ImitatePass", "%1 Whether %2 was removed cannot be "
836
                                     "told, so nothing was encrypted.")
837
                      .arg(recordError, QDir::toNativeSeparators(*skipped)));
×
838
    return true;
×
839
  }
840
  emit critical(
5 ✔
841
      QCoreApplication::translate("ImitatePass", "Recipient list missing"),
10 ✔
842
      QCoreApplication::translate(
5 ✔
843
          "ImitatePass",
844
          "The signed recipient list %1 is missing or is not a regular file. "
845
          "QtPass does not fall back to a parent folder's list for it: that "
846
          "list was not signed for this folder. If a link is under that name, "
847
          "remove it. Then open Users for that folder and save its "
848
          "recipients, which writes and signs a fresh list.")
849
          .arg(QDir::toNativeSeparators(*skipped)));
10 ✔
850
  return true;
5 ✔
851
}
852

853
auto Pass::verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile,
44 ✔
854
                            QByteArray *contents, QString *why) const -> bool {
855
  if (!signer.verifyFile(gpgIdFile, contents)) {
44 ✔
856
    return false;
857
  }
858
  // Authentic and unmodified is not the same as current: an older signed
859
  // list put back into the store is refused once this device has seen a
860
  // newer one, and one signed for another folder is refused here.
861
  QString reason;
43 ✔
862
  if (GpgIdGeneration::accept(gpgIdFile, *contents, m_settings.passStore,
43 ✔
863
                              &reason) != GpgIdGeneration::Verdict::Accepted) {
864
    if (why != nullptr) {
16 ✔
865
      *why = reason;
16 ✔
866
    }
867
    return false;
16 ✔
868
  }
869
  return true;
870
}
871

872
auto Pass::skippedGpgId(const QString &forFile, const QString &passStore,
77 ✔
873
                        QString *recordError) -> std::optional<QString> {
874
  const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
77 ✔
875
  QDir dir = lookup.start;
77 ✔
876
  // The same walk as nearestGpgId(), stopping at the list it finds, and
877
  // short of the store root: the root's own list has no parent to fall
878
  // back to, and the signature check refuses it when it is missing.
879
  while (dir.exists() && QDir::cleanPath(dir.absolutePath())
300 ✔
880
                             .startsWith(lookup.storePrefix, kPathCase)) {
100 ✔
881
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
52 ✔
882
    if (isOwnGpgId(candidate)) {
52 ✔
883
      return std::nullopt;
18 ✔
884
    }
885
    // A link under the name (dangling or not), or nothing under it where
886
    // this device accepted a list before: both are the folder's list gone,
887
    // not a folder that never had one.
888
    if (candidate.isSymLink() || candidate.isJunction()) {
34 ✔
889
      return candidate.absoluteFilePath();
12 ✔
890
    }
891
    // An unreadable record is not "never seen": whether a list was accepted
892
    // here cannot be told, so this folder is refused too (fail closed), with
893
    // the record's own reason for the caller to show.
894
    QString why;
28 ✔
895
    const std::optional<qint64> seen =
896
        GpgIdGeneration::remembered(candidate.absoluteFilePath(), &why);
56 ✔
897
    if (!seen) {
28 ✔
898
      if (recordError != nullptr) {
1 ✔
899
        *recordError =
900
            why.isEmpty()
901
                ? tr("The generation record of the recipient lists cannot "
2 ✔
902
                     "be read.")
903
                : why;
904
      }
905
      return candidate.absoluteFilePath();
2 ✔
906
    }
907
    if (*seen > 0) {
27 ✔
908
      return candidate.absoluteFilePath();
8 ✔
909
    }
910
    if (!dir.cdUp()) {
23 ✔
911
      break;
912
    }
913
  }
52 ✔
914
  return std::nullopt;
48 ✔
915
}
77 ✔
916

917
namespace {
918

919
/// What the Users dialog may preselect for a verified list, given what the
920
/// generation record says about it.
921
auto judgedRecipients(GpgIdGeneration::Verdict verdict,
7 ✔
922
                      const QByteArray &contents, const QString &gpgIdPath,
923
                      const QString &why) -> Pass::RecipientsForEditing {
924
  using RecipientsForEditing = Pass::RecipientsForEditing;
925
  RecipientsForEditing result;
7 ✔
926
  switch (verdict) {
7 ✔
927
  case GpgIdGeneration::Verdict::Accepted:
1 ✔
928
    result.state = RecipientsForEditing::State::Verified;
1 ✔
929
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
930
    break;
1 ✔
931
  case GpgIdGeneration::Verdict::Rollback:
1 ✔
932
    // Authentic and this folder's, only older: the recovery goes through
933
    // this dialog, so it is preselected, with the reason in view.
934
    result.state = RecipientsForEditing::State::VerifiedRollback;
1 ✔
935
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
936
    result.warning = why;
1 ✔
937
    break;
1 ✔
938
  case GpgIdGeneration::Verdict::Unbound:
5 ✔
939
  case GpgIdGeneration::Verdict::Conflict:
940
  case GpgIdGeneration::Verdict::WrongFolder:
941
  case GpgIdGeneration::Verdict::WrongStore:
942
  case GpgIdGeneration::Verdict::Malformed:
943
  case GpgIdGeneration::Verdict::RecordUnavailable:
944
    // Signed, but not shown to be this folder's list, not a list to trust,
945
    // or nothing to judge it by: preselecting it would sign it in.
946
    result.state = RecipientsForEditing::State::Rejected;
5 ✔
947
    result.warning =
948
        Pass::tr("%1 Nothing is preselected: saving would sign whatever is "
5 ✔
949
                 "in it. Select the recipients yourself.")
950
            .arg(why);
10 ✔
951
    break;
5 ✔
952
  }
953
  return result;
7 ✔
954
}
955

956
} // namespace
957

958
auto Pass::recipientsForEditing(const QString &dir, const QString &passStore)
40 ✔
959
    -> RecipientsForEditing {
960
  RecipientsForEditing result;
40 ✔
961
  const QString folder = dir.isEmpty() ? QString() : dir;
40 ✔
962
  const QString gpgIdPath = getGpgIdPath(folder, passStore);
40 ✔
963
  const GpgIdSigner signer(
964
      m_settings.gpgExecutable,
965
      GpgIdSigner::keysFromSetting(m_settings.passSigningKey));
120 ✔
966
  if (!signer.enabled()) {
40 ✔
967
    // A list that is there but cannot be read as one (too large, not a
968
    // regular file, unreadable) is not an empty list: preselecting nothing
969
    // without a word would let OK write a new list over it, and later
970
    // re-encryptions drop whoever it named.
971
    // Read once and parsed from those bytes: a second read could find
972
    // something else under the name. A link counts as there, dangling too.
973
    const QFileInfo info(gpgIdPath);
30 ✔
974
    if (!info.exists() && !info.isSymLink()) {
30 ✔
975
      result.state = RecipientsForEditing::State::Unsigned;
976
      return result;
13 ✔
977
    }
978
    const std::optional<QByteArray> bytes =
979
        Util::readRegularFile(gpgIdPath, Util::kMaxGpgIdBytes);
17 ✔
980
    if (!bytes) {
17 ✔
981
      result.state = RecipientsForEditing::State::Rejected;
2 ✔
982
      result.warning =
983
          tr("%1 cannot be read as a recipient list (a regular file of at "
2 ✔
984
             "most %2), so nothing is preselected. Check it before choosing "
985
             "recipients here: OK writes a new list over it.")
986
              .arg(gpgIdPath,
2 ✔
987
                   QLocale().formattedDataSize(Util::kMaxGpgIdBytes));
4 ✔
988
      return result;
2 ✔
989
    }
990
    result.state = RecipientsForEditing::State::Unsigned;
991
    result.recipients = parseRecipients(*bytes, gpgIdPath);
15 ✔
992
    return result;
15 ✔
993
  }
30 ✔
994
  QString recordError;
10 ✔
995
  if (const std::optional<QString> skipped =
10 ✔
996
          skippedGpgId(folder, passStore, &recordError)) {
10 ✔
997
    // The folder's own list was removed or replaced by a link (or the record
998
    // that would tell cannot be read): the list the walk found further up
999
    // was not signed for this folder, so preselecting it would sign it in
1000
    // here with one click.
1001
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1002
    result.warning =
1003
        recordError.isEmpty()
1004
            ? tr("The recipient list %1 is missing or is not a regular file, "
2 ✔
1005
                 "so nothing is preselected: the list of a parent folder was "
1006
                 "not signed for this one. Select this folder's recipients "
1007
                 "yourself; OK writes and signs a fresh list.")
1008
                  .arg(*skipped)
1009
            : tr("%1 Nothing is preselected: whether %2 was removed cannot "
1 ✔
1010
                 "be told.")
1011
                  .arg(recordError, *skipped);
1012
    return result;
1 ✔
1013
  }
1014
  if (!QFileInfo::exists(gpgIdPath)) {
9 ✔
1015
    // A folder without a list yet (new store, new profile): nothing to
1016
    // verify and nothing to preselect.
1017
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1018
    return result;
1 ✔
1019
  }
1020
  QByteArray contents;
8 ✔
1021
  if (!signer.verifyFile(gpgIdPath, &contents)) {
8 ✔
1022
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1023
    result.warning =
1024
        tr("The recipient list %1 does not verify against the signing key, "
1 ✔
1025
           "so nothing is preselected: saving would sign whatever is in it. "
1026
           "Select the recipients yourself; OK writes and signs a fresh list.")
1027
            .arg(gpgIdPath);
2 ✔
1028
    return result;
1 ✔
1029
  }
1030
  QString why;
7 ✔
1031
  const GpgIdGeneration::Verdict verdict =
1032
      GpgIdGeneration::accept(gpgIdPath, contents, passStore, &why);
7 ✔
1033
  return judgedRecipients(verdict, contents, gpgIdPath, why);
7 ✔
1034
}
40 ✔
1035

1036
auto Pass::getRecipientList(const QString &for_file, const QString &passStore)
18 ✔
1037
    -> QStringList {
1038
  const QString gpgIdPath = getGpgIdPath(for_file, passStore);
18 ✔
1039
  // The root .gpg-id comes back whatever it is; a link is not a list.
1040
  if (Util::isLinkedFolder(gpgIdPath)) {
18 ✔
1041
    return {};
1 ✔
1042
  }
1043
  const std::optional<QByteArray> bytes =
1044
      Util::readRegularFile(gpgIdPath, Util::kMaxGpgIdBytes);
17 ✔
1045
  if (!bytes) {
17 ✔
1046
    return {};
1 ✔
1047
  }
1048
  return parseRecipients(*bytes, gpgIdPath);
16 ✔
1049
}
1050

1051
auto Pass::parseRecipients(const QByteArray &contents,
144 ✔
1052
                           const QString &sourceName) -> QStringList {
1053
  QStringList recipients;
144 ✔
1054
  const QString text = QString::fromUtf8(contents);
1055
  for (const QString &line : text.split(QLatin1Char('\n'))) {
512 ✔
1056
    QString recipient = line.split(QLatin1Char('#')).first().trimmed();
736 ✔
1057
    if (recipient.isEmpty()) {
368 ✔
1058
      continue;
203 ✔
1059
    }
1060
    if (!Util::isValidKeyId(recipient)) {
165 ✔
1061
      // Never drop a recipient silently: the list is written back verbatim
1062
      // by UsersDialog, so a skipped line disappears from .gpg-id.
1063
      qCWarning(lcQtPass) << "Skipping unusable recipient in" << sourceName
4 ✔
1064
                          << ":" << recipient;
2 ✔
1065
      continue;
2 ✔
1066
    }
2 ✔
1067
    recipients += recipient;
1068
  }
1069
  return recipients;
144 ✔
1070
}
1071

1072
auto Pass::seedGpgIdFile(const QString &newDir, const QString &passStore)
8 ✔
1073
    -> bool {
1074
  const QString gpgIdFile = QDir(newDir).absoluteFilePath(".gpg-id");
16 ✔
1075
  if (QFileInfo::exists(gpgIdFile)) {
8 ✔
1076
    return false;
1077
  }
1078
  // Resolving from the file to be created finds the parent's .gpg-id whether
1079
  // or not newDir has a trailing separator.
1080
  const QStringList recipients = getRecipientList(gpgIdFile, passStore);
7 ✔
1081
  if (recipients.isEmpty()) {
7 ✔
1082
    return false;
1083
  }
1084
  // Only reached without a signing key, so no generation header: a plain
1085
  // list stays readable for clients that take a comment for a recipient.
1086
  // Staged and replacing nothing: a link planted after the exists() above
1087
  // (a dangling one passes it) fails the seed instead of being written through.
1088
  return Util::writeFileReplacing(
4 ✔
1089
      gpgIdFile,
1090
      (recipients.join(QLatin1Char('\n')) + QLatin1Char('\n')).toUtf8(), false);
8 ✔
1091
}
1092

1093
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
1094
 */
1095

1096
auto Pass::boundedRandom(quint32 bound) -> quint32 {
7,620 ✔
1097
  if (bound < 2) {
7,620 ✔
1098
    return 0;
1099
  }
1100

1101
  quint32 randval;
1102
  // arc4random_uniform-style rejection against modulo bias: drop values
1103
  // below 2^32 % bound, which (1 + ~bound) % bound computes in quint32.
1104
  const quint32 rejectionThreshold = (1 + ~bound) % bound;
7,616 ✔
1105

1106
  do {
1107
    randval = QRandomGenerator::system()->generate();
1108
  } while (randval < rejectionThreshold);
7,616 ✔
1109

1110
  return randval % bound;
7,616 ✔
1111
}
1112

1113
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,209 ✔
1114
    -> QString {
1115
  if (charset.isEmpty() || length == 0U) {
1,209 ✔
1116
    return {};
2 ✔
1117
  }
1118
  QString out;
1,207 ✔
1119
  for (unsigned int i = 0; i < length; ++i) {
8,827 ✔
1120
    out.append(charset.at(static_cast<int>(
7,620 ✔
1121
        boundedRandom(static_cast<quint32>(charset.length())))));
7,620 ✔
1122
  }
1123
  return out;
1124
}
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