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

IJHack / QtPass / 27660975269

17 Jun 2026 02:06AM UTC coverage: 57.452% (-0.03%) from 57.477%
27660975269

Pull #1551

github

web-flow
Merge 1c61e7f1d into 4da97561f
Pull Request #1551: refactor(pass): inject AppSettings into Pass hierarchy (PR A of #1511)

44 of 84 new or added lines in 4 files covered. (52.38%)

13 existing lines in 6 files now uncovered.

3982 of 6931 relevant lines covered (57.45%)

23.91 hits per line

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

69.3
/src/pass.cpp
1
// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
#include "pass.h"
4
#include "gpgkeystate.h"
5
#include "qtpasssettings.h" // TODO(#1511 PR-C): remove once getGpgIdPath is migrated
6
#include "util.h"
7
#include <QCoreApplication>
8
#include <QDebug>
9
#include <QDir>
10
#include <QFileInfo>
11
#include <QProcess>
12
#include <QRandomGenerator>
13
#include <QRegularExpression>
14
#include <utility>
15

16
#ifdef QT_DEBUG
17
#include "debughelper.h"
18
#endif
19

20
using Enums::GIT_INIT;
21
using Enums::GIT_PULL;
22
using Enums::GIT_PUSH;
23
using Enums::GPG_GENKEYS;
24
using Enums::PASS_COPY;
25
using Enums::PASS_GREP;
26
using Enums::PASS_INIT;
27
using Enums::PASS_INSERT;
28
using Enums::PASS_MOVE;
29
using Enums::PASS_OTP_GENERATE;
30
using Enums::PASS_REMOVE;
31
using Enums::PASS_SHOW;
32

33
namespace {
34
/**
35
 * @brief Returns a non-empty charset value, using a fallback when needed.
36
 * @param input Preferred charset value.
37
 * @param fallback Charset to use when @p input is empty.
38
 * @return @p input if it is not empty; otherwise @p fallback.
39
 */
40
auto fallbackCharset(const QString &input, const QString &fallback) -> QString {
41
  return input.isEmpty() ? fallback : input;
1,239✔
42
}
43

44
/**
45
 * @brief Resolve the effective password character set from configuration.
46
 *
47
 * Uses the selected charset index from @p passConfig when it is within range;
48
 * otherwise falls back to the ALLCHARS entry. If the resolved charset string
49
 * is empty, falls back again to the ALLCHARS value.
50
 *
51
 * @param passConfig Password generation configuration.
52
 * @return Non-empty charset string to use for password generation.
53
 */
54
auto effectiveCharset(const PasswordConfiguration &passConfig) -> QString {
35✔
55
  int sel = passConfig.selected;
35✔
56
  if (sel < 0 || sel >= PasswordConfiguration::CHARSETS_COUNT)
35✔
57
    sel = PasswordConfiguration::ALLCHARS;
58
  return fallbackCharset(
59
      passConfig.Characters[sel],
35✔
60
      passConfig.Characters[PasswordConfiguration::ALLCHARS]);
35✔
61
}
62
} // namespace
63

64
/**
65
 * @brief Pass::Pass wrapper for using either pass or the pass imitation
66
 */
67
Pass::Pass() : env(QProcessEnvironment::systemEnvironment()) {
39✔
68
  connect(&exec,
39✔
69
          static_cast<void (Executor::*)(int, int, const QString &,
70
                                         const QString &)>(&Executor::finished),
71
          this, &Pass::finished);
39✔
72

73
  // This was previously using direct QProcess signals.
74
  // The code now uses Executor instead of raw QProcess for better control.
75
  // connect(&process, SIGNAL(error(QProcess::ProcessError)), this,
76
  //        SIGNAL(error(QProcess::ProcessError)));
77

78
  connect(&exec, &Executor::starting, this, &Pass::startingExecuteWrapper);
39✔
79
  // Merge our vars into WSLENV rather than blindly appending a duplicate entry
80
  const QStringList wslenvVars = {
81
      QStringLiteral("PASSWORD_STORE_DIR/p"),
78✔
82
      QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH/w"),
39✔
83
      QStringLiteral("PASSWORD_STORE_CHARACTER_SET/w")};
156✔
84
  const QString existing = env.value(QStringLiteral("WSLENV"));
78✔
85
  if (existing.isEmpty()) {
39✔
86
    env.insert(QStringLiteral("WSLENV"), wslenvVars.join(':'));
78✔
87
  } else {
88
    QStringList parts = existing.split(':', Qt::SkipEmptyParts);
×
89
    for (const QString &v : wslenvVars) {
×
90
      if (!parts.contains(v))
×
91
        parts.append(v);
92
    }
93
    env.insert(QStringLiteral("WSLENV"), parts.join(':'));
×
94
  }
95
}
39✔
96

97
/**
98
 * @brief Executes a wrapper command.
99
 * @param id Process ID
100
 * @param app Application to execute
101
 * @param args Arguments
102
 * @param readStdout Whether to read stdout
103
 * @param readStderr Whether to read stderr
104
 */
105
void Pass::executeWrapper(PROCESS id, const QString &app,
×
106
                          const QStringList &args, bool readStdout,
107
                          bool readStderr) {
108
  executeWrapper(id, app, args, QString(), readStdout, readStderr);
×
109
}
×
110

111
void Pass::executeWrapper(PROCESS id, const QString &app,
31✔
112
                          const QStringList &args, QString input,
113
                          bool readStdout, bool readStderr) {
114
  beforeExecute(id);
31✔
115
#ifdef QT_DEBUG
116
  dbg() << app << args;
117
#endif
118
  exec.execute(id, m_settings.passStore, app, args, std::move(input),
31✔
119
               readStdout, readStderr);
120
}
31✔
121

122
void Pass::beforeExecute(PROCESS /*id*/) {}
×
123

124
/**
125
 * @brief Initializes the pass wrapper with a settings snapshot.
126
 * @param settings Application settings to use for this backend lifetime.
127
 */
128
void Pass::init(const AppSettings &settings) {
31✔
129
  m_settings = settings;
31✔
130
#ifdef __APPLE__
131
  // If it exists, prepend gpgtools to PATH
132
  if (QFile(QStringLiteral("/usr/local/MacGPG2/bin")).exists())
133
    env.insert(QStringLiteral("PATH"),
134
               QStringLiteral("/usr/local/MacGPG2/bin:") +
135
                   env.value(QStringLiteral("PATH")));
136
  // Add missing /usr/local/bin (exact component match, no leading colon)
137
  const QString currentPath = env.value(QStringLiteral("PATH"));
138
  if (!currentPath.split(':', Qt::SkipEmptyParts)
139
           .contains(QStringLiteral("/usr/local/bin"))) {
140
    env.insert(QStringLiteral("PATH"),
141
               currentPath.isEmpty()
142
                   ? QStringLiteral("/usr/local/bin")
143
                   : QStringLiteral("/usr/local/bin:") + currentPath);
144
  }
145
#endif
146

147
  if (!m_settings.gpgHome.isEmpty()) {
31✔
148
    QDir absHome(m_settings.gpgHome);
15✔
149
    absHome.makeAbsolute();
15✔
150
    env.insert(QStringLiteral("GNUPGHOME"), absHome.path());
30✔
151
  }
15✔
152
}
31✔
153

154
/**
155
 * @brief Pass::Generate use either pwgen or internal password
156
 * generator
157
 * @param length of the desired password
158
 * @param charset to use for generation
159
 * @return the password
160
 */
161
auto Pass::generatePassword(unsigned int length, const QString &charset)
1,205✔
162
    -> QString {
163
  if (length == 0) {
1,205✔
164
    emit critical(tr("Invalid password length"),
2✔
165
                  tr("Can't generate password with zero length."));
1✔
166
    return {};
167
  }
168
  QString passwd;
1,204✔
169
  if (m_settings.usePwgen) {
1,204✔
170
    // --secure goes first as it overrides --no-* otherwise
171
    QStringList args;
×
172
    args.append("-1");
×
NEW
173
    if (!m_settings.lessRandom) {
×
174
      args.append("--secure");
×
175
    }
NEW
176
    args.append(m_settings.avoidCapitals ? "--no-capitalize" : "--capitalize");
×
NEW
177
    args.append(m_settings.avoidNumbers ? "--no-numerals" : "--numerals");
×
NEW
178
    if (m_settings.useSymbols) {
×
UNCOV
179
      args.append("--symbols");
×
180
    }
181
    args.append(QString::number(length));
×
182
    // executeBlocking returns 0 on success, non-zero on failure
NEW
183
    if (Executor::executeBlocking(m_settings.pwgenExecutable, args,
×
184
                                  &passwd) == 0) {
185
      static const QRegularExpression literalNewLines{"[\\n\\r]"};
×
186
      passwd.remove(literalNewLines);
×
187
    } else {
188
      passwd.clear();
×
189
#ifdef QT_DEBUG
190
      qDebug() << __FILE__ << ":" << __LINE__ << "\t"
191
               << "pwgen fail";
192
#endif
193
      // Error is already handled by clearing passwd; no need for critical
194
      // signal here
195
    }
196
  } else {
197
    // Validate charset - if CUSTOM is selected but chars are empty,
198
    // fall back to ALLCHARS to prevent weak passwords (issue #780)
199
    const QString cs = fallbackCharset(
200
        charset,
201
        m_settings.passwordConfiguration.Characters[PasswordConfiguration::ALLCHARS]);
1,204✔
202
    if (cs.length() > 0) {
1,204✔
203
      passwd = generateRandomPassword(cs, length);
2,408✔
204
    } else {
205
      emit critical(
×
206
          tr("No characters chosen"),
×
207
          tr("Can't generate password, there are no characters to choose from "
×
208
             "set in the configuration!"));
209
    }
210
  }
211
  return passwd;
212
}
213

214
/**
215
 * @brief Pass::gpgSupportsEd25519 check if GPG supports ed25519 (ECC)
216
 * GPG 2.1+ supports ed25519 which is much faster for key generation
217
 * @return true if ed25519 is supported
218
 */
219
bool Pass::gpgSupportsEd25519(const QString &gpgExecutable) {
12✔
220
  const QString exe = gpgExecutable.isEmpty() ? QStringLiteral("gpg") : gpgExecutable;
12✔
221
  QString out, err;
12✔
222
  if (Executor::executeBlocking(exe, {"--version"}, &out, &err) != 0) {
36✔
223
    return false;
224
  }
225
  QRegularExpression versionRegex(R"(gpg \(GnuPG\) (\d+)\.(\d+))");
24✔
226
  QRegularExpressionMatch match = versionRegex.match(out);
12✔
227
  if (!match.hasMatch()) {
12✔
228
    return false;
229
  }
230
  int major = match.captured(1).toInt();
12✔
231
  int minor = match.captured(2).toInt();
12✔
232
  return major > 2 || (major == 2 && minor >= 1);
12✔
233
}
24✔
234

235
/**
236
 * @brief Pass::getDefaultKeyTemplate return default key generation template
237
 * Uses ed25519 if supported, otherwise falls back to RSA
238
 * @return GPG batch template string
239
 */
240
QString Pass::getDefaultKeyTemplate(const QString &gpgExecutable) {
11✔
241
  if (gpgSupportsEd25519(gpgExecutable)) {
11✔
242
    return QStringLiteral("%echo Generating a default key\n"
11✔
243
                          "Key-Type: EdDSA\n"
244
                          "Key-Curve: Ed25519\n"
245
                          "Subkey-Type: ECDH\n"
246
                          "Subkey-Curve: Curve25519\n"
247
                          "Name-Real: \n"
248
                          "Name-Comment: QtPass\n"
249
                          "Name-Email: \n"
250
                          "Expire-Date: 0\n"
251
                          "%no-protection\n"
252
                          "%commit\n"
253
                          "%echo done");
254
  }
UNCOV
255
  return QStringLiteral("%echo Generating a default key\n"
×
256
                        "Key-Type: RSA\n"
257
                        "Subkey-Type: RSA\n"
258
                        "Name-Real: \n"
259
                        "Name-Comment: QtPass\n"
260
                        "Name-Email: \n"
261
                        "Expire-Date: 0\n"
262
                        "%no-protection\n"
263
                        "%commit\n"
264
                        "%echo done");
265
}
266

267
namespace {
268
/**
269
 * @brief Resolve a candidate gpgconf path from the trailing WSL path segment.
270
 *
271
 * Takes the directory portion of @p lastPart (separated by '/' or '\\') and
272
 * appends "gpgconf"; if no separator is present, returns the bare executable
273
 * name "gpgconf".
274
 *
275
 * @param lastPart Path fragment that may contain a directory and executable.
276
 * @return Full path ending in "gpgconf", or "gpgconf" as a fallback.
277
 */
278
auto resolveWslGpgconfPath(const QString &lastPart) -> QString {
3✔
279
  qsizetype lastSep = lastPart.lastIndexOf('/');
3✔
280
  if (lastSep < 0) {
3✔
281
    lastSep = lastPart.lastIndexOf('\\');
2✔
282
  }
283
  if (lastSep >= 0) {
2✔
284
    return lastPart.left(lastSep + 1) + "gpgconf";
2✔
285
  }
286
  return QStringLiteral("gpgconf");
2✔
287
}
288

289
/**
290
 * @brief Finds the path to the gpgconf executable in the same directory as the
291
 * given GPG path.
292
 * @example
293
 * QString result = findGpgconfInGpgDir(gpgPath);
294
 * std::cout << result.toStdString() << std::endl; // Expected output: path to
295
 * gpgconf or empty string
296
 *
297
 * @param gpgPath - Absolute path to a GPG executable or related file used to
298
 * locate gpgconf.
299
 * @return QString - The full path to gpgconf if found and executable; otherwise
300
 * an empty QString.
301
 */
302
QString findGpgconfInGpgDir(const QString &gpgPath) {
1✔
303
  QFileInfo gpgInfo(gpgPath);
1✔
304
  if (!gpgInfo.isAbsolute()) {
1✔
305
    return {};
306
  }
307

308
  QDir dir(gpgInfo.absolutePath());
1✔
309

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

317
  QFileInfo candidate(dir.filePath("gpgconf"));
1✔
318
  if (candidate.isExecutable()) {
1✔
319
    return candidate.filePath();
×
320
  }
321
  return {};
322
}
1✔
323

324
// Compatibility shim for Qt < 5.15 where QProcess::splitCommand is not
325
// available. Keep this fallback while supporting pre-5.15 builds; remove once
326
// the project's minimum supported Qt version is raised to 5.15 or newer.
327
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
328
/**
329
 * @brief Splits a command string into arguments while respecting quotes and
330
 * escape characters.
331
 * @example
332
 * QStringList result = splitCommandCompat("cmd \"arg one\" 'arg two'
333
 * escaped\\ space");
334
 * // Expected output: ["cmd", "arg one", "arg two", "escaped space"]
335
 *
336
 * @param command - The input command string to split into individual arguments.
337
 * @return QStringList - A list of parsed command arguments.
338
 */
339
QStringList splitCommandCompat(const QString &command) {
340
  QStringList result;
341
  QString current;
342
  bool inSingleQuote = false;
343
  bool inDoubleQuote = false;
344
  bool escaping = false;
345
  for (QChar ch : command) {
346
    if (escaping) {
347
      current.append(ch);
348
      escaping = false;
349
      continue;
350
    }
351
    if (ch == '\\') {
352
      escaping = true;
353
      continue;
354
    }
355
    if (ch == '\'' && !inDoubleQuote) {
356
      inSingleQuote = !inSingleQuote;
357
      continue;
358
    }
359
    if (ch == '"' && !inSingleQuote) {
360
      inDoubleQuote = !inDoubleQuote;
361
      continue;
362
    }
363
    if (ch.isSpace() && !inSingleQuote && !inDoubleQuote) {
364
      if (!current.isEmpty()) {
365
        result.append(current);
366
        current.clear();
367
      }
368
      continue;
369
    }
370
    current.append(ch);
371
  }
372
  if (escaping) {
373
    current.append('\\');
374
  }
375
  if (!current.isEmpty()) {
376
    result.append(current);
377
  }
378
  return result;
379
}
380
#endif
381

382
} // namespace
383

384
/**
385
 * @brief Resolves the appropriate gpgconf command from a given GPG executable
386
 * path or command string.
387
 * @example
388
 * ResolvedGpgconfCommand result = Pass::resolveGpgconfCommand("wsl.exe
389
 * /usr/bin/gpg"); std::cout << result.first.toStdString() << std::endl; //
390
 * Expected output sample
391
 *
392
 * @param const QString &gpgPath - Path or command string pointing to the GPG
393
 * executable.
394
 * @return ResolvedGpgconfCommand - A pair containing the resolved gpgconf
395
 * command and its arguments.
396
 */
397
auto Pass::resolveGpgconfCommand(const QString &gpgPath)
8✔
398
    -> ResolvedGpgconfCommand {
399
  if (gpgPath.trimmed().isEmpty()) {
8✔
400
    return {"gpgconf", {}};
401
  }
402

403
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
404
  QStringList parts = QProcess::splitCommand(gpgPath);
7✔
405
#else
406
  QStringList parts = splitCommandCompat(gpgPath);
407
#endif
408

409
  if (parts.isEmpty()) {
7✔
410
    return {"gpgconf", {}};
411
  }
412

413
  const QString first = parts.first();
414
  if (first.compare("wsl", Qt::CaseInsensitive) == 0 ||
16✔
415
      first.compare("wsl.exe", Qt::CaseInsensitive) == 0) {
9✔
416
    if (parts.size() >= 2 && parts.at(1).startsWith("sh")) {
9✔
417
      return {"gpgconf", {}};
418
    }
419
    if (parts.size() >= 2 &&
4✔
420
        QFileInfo(parts.last()).fileName().startsWith("gpg")) {
10✔
421
      QString wslGpgconf = resolveWslGpgconfPath(parts.last());
3✔
422
      parts.removeLast();
3✔
423
      parts.append(wslGpgconf);
424
      return {parts.first(), parts.mid(1)};
425
    }
426
    return {"gpgconf", {}};
427
  }
428

429
  if (!first.contains('/') && !first.contains('\\')) {
2✔
430
    return {"gpgconf", {}};
431
  }
432

433
  QString gpgconfPath = findGpgconfInGpgDir(first);
1✔
434
  if (!gpgconfPath.isEmpty()) {
1✔
435
    return {gpgconfPath, {}};
×
436
  }
437

438
  return {"gpgconf", {}};
439
}
8✔
440

441
/**
442
 * @brief Pass::GenerateGPGKeys internal gpg keypair generator . .
443
 * @param batch GnuPG style configuration string
444
 */
445
void Pass::GenerateGPGKeys(QString batch) {
×
446
  // Kill any stale GPG agents that might be holding locks on the key database
447
  // This helps avoid "database locked" timeouts during key generation
448
  const QString gpgPath = m_settings.gpgExecutable;
449
  if (!gpgPath.isEmpty()) {
×
450
    ResolvedGpgconfCommand resolvedGpgconf = resolveGpgconfCommand(gpgPath);
×
451
    QStringList killArgs = resolvedGpgconf.arguments;
452
    killArgs << "--kill";
×
453
    killArgs << "gpg-agent";
×
454
    // Use same environment as key generation to target correct gpg-agent
455
    if (Executor::executeBlocking(env, resolvedGpgconf.program, killArgs) !=
×
456
        0) {
457
      qWarning() << "Failed to kill gpg-agent";
×
458
    }
459
  }
460

461
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
×
462
                 std::move(batch), true, true);
463
}
×
464

465
/**
466
 * @brief Pass::listKeys list users
467
 * @param keystrings
468
 * @param secret list private keys
469
 * @return QList<UserInfo> users
470
 */
471
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
×
472
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
×
473
  args.append(secret ? "--list-secret-keys" : "--list-keys");
×
474

475
  for (const QString &keystring : std::as_const(keystrings)) {
×
476
    if (!keystring.isEmpty()) {
×
477
      args.append(keystring);
478
    }
479
  }
480
  QString p_out;
×
NEW
481
  if (Executor::executeBlocking(m_settings.gpgExecutable, args, &p_out) != 0) {
×
UNCOV
482
    return {};
×
483
  }
484
  return parseGpgColonOutput(p_out, secret);
×
485
}
×
486

487
/**
488
 * @brief Pass::listKeys list users
489
 * @param keystring
490
 * @param secret list private keys
491
 * @return QList<UserInfo> users
492
 */
493
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
×
494
  return listKeys(QStringList(keystring), secret);
×
495
}
496

497
/**
498
 * @brief Maps GPG stderr (which may include --status-fd 2 tokens) to a
499
 * user-friendly encryption error string.
500
 *
501
 * Checked in order: machine-readable [GNUPG:] status tokens first (locale-
502
 * independent), then case-insensitive substring fallbacks for GPG builds that
503
 * don't emit status tokens.
504
 *
505
 * @param err Raw stderr from GPG
506
 * @return Translated human-readable error, or empty string if not recognised
507
 */
508
namespace {
509

510
/**
511
 * @brief Checks if @p str contains any of the @p patterns (case-sensitive).
512
 * @param str String to search in.
513
 * @param patterns Patterns to search for.
514
 * @return true if any pattern is found, false otherwise.
515
 */
516
auto containsAny(const QString &str, const QStringList &patterns) -> bool {
31✔
517
  for (const QString &p : patterns) {
82✔
518
    if (str.contains(p)) {
58✔
519
      return true;
520
    }
521
  }
522
  return false;
523
}
524

525
/**
526
 * @brief Checks if str contains any of the patterns (case-insensitive).
527
 * @param str String to search in (will be lowercased once).
528
 * @param patterns List of patterns to search for (must be lowercase; caller
529
 * should convert patterns to lowercase before calling).
530
 * @return true if any pattern is found.
531
 */
532
auto containsAnyCaseInsensitive(const QString &str, const QStringList &patterns)
13✔
533
    -> bool {
534
  const QString lower = str.toLower();
535
  for (const QString &p : patterns) {
32✔
536
    if (lower.contains(p)) {
23✔
537
      return true;
538
    }
539
  }
540
  return false;
541
}
542

543
} // namespace
544

545
auto gpgErrorMessage(const QString &err) -> QString {
13✔
546
  // Machine-readable status tokens added by --status-fd 2
547
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYEXPIRED"),
65✔
548
                        QStringLiteral("[GNUPG:] INV_RECP 5 ")}))
13✔
549
    return QCoreApplication::translate(
550
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
551
                "replace it.");
3✔
552
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYREVOKED"),
50✔
553
                        QStringLiteral("[GNUPG:] INV_RECP 4 ")}))
10✔
554
    return QCoreApplication::translate(
555
        "Pass", "Encryption failed: GPG key has been revoked.");
2✔
556
  if (containsAny(err, {QStringLiteral("[GNUPG:] NO_PUBKEY"),
40✔
557
                        QStringLiteral("[GNUPG:] INV_RECP")}))
8✔
558
    return QCoreApplication::translate(
559
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
560
                "Check that the key ID in .gpg-id is correct and imported.");
2✔
561
  if (err.contains(QStringLiteral("[GNUPG:] FAILURE")))
6✔
562
    return QCoreApplication::translate(
563
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1✔
564

565
  // Locale-dependent fallbacks
566
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has expired"),
20✔
567
                                       QLatin1String("key expired")}))
568
    return QCoreApplication::translate(
569
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
570
                "replace it.");
1✔
571
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has been revoked"),
16✔
572
                                       QLatin1String("revoked")}))
573
    return QCoreApplication::translate(
574
        "Pass", "Encryption failed: GPG key has been revoked.");
1✔
575
  if (containsAnyCaseInsensitive(err, {QLatin1String("no public key"),
15✔
576
                                       QLatin1String("unusable public key"),
577
                                       QLatin1String("no secret key")}))
578
    return QCoreApplication::translate(
579
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
580
                "Check that the key ID in .gpg-id is correct and imported.");
2✔
581
  if (containsAnyCaseInsensitive(err, {QLatin1String("encryption failed")}))
3✔
582
    return QCoreApplication::translate(
583
        "Pass", "Encryption failed. Check that your GPG key is valid.");
×
584

585
  return {};
586
}
×
587

588
namespace {
589
/**
590
 * @brief Determine whether a line from `pass grep` output is an entry header.
591
 *
592
 * Detects the ANSI blue escape (\x1B[94m) emitted by `pass grep`; as a
593
 * plain-text fallback, treats a non-indented line ending in ':' as a header.
594
 *
595
 * @param rawLine Original unmodified output line (with any ANSI codes).
596
 * @param trimmedLine The line after surrounding whitespace has been stripped.
597
 * @return true if the line is an entry header; otherwise false.
598
 */
599
auto isGrepHeaderLine(const QString &rawLine, const QString &trimmedLine)
45✔
600
    -> bool {
601
  return rawLine.startsWith(QStringLiteral("\x1B[94m")) ||
123✔
602
         (!rawLine.startsWith(' ') && !rawLine.startsWith('\t') &&
91✔
603
          trimmedLine.endsWith(':'));
119✔
604
}
605
} // namespace
606

607
/**
608
 * @brief Parses 'pass grep' raw output into (entry, matches) pairs.
609
 *
610
 * pass grep emits ANSI blue color (\x1B[94m) at the start of each entry
611
 * header line. This is checked before stripping ANSI so headers are detected
612
 * reliably regardless of locale.
613
 */
614
auto parseGrepOutput(const QString &rawOut)
12✔
615
    -> QList<QPair<QString, QStringList>> {
616
  static const QRegularExpression ansi(
617
      QStringLiteral(R"(\x1B\[[0-9;]*[a-zA-Z])"));
13✔
618
  QList<QPair<QString, QStringList>> results;
12✔
619
  QString currentEntry;
12✔
620
  QStringList currentMatches;
12✔
621
  for (const QString &rawLine : rawOut.split('\n')) {
69✔
622
    QString line = rawLine;
623
    line.remove('\r');
45✔
624
    line.remove(ansi);
45✔
625
    line = line.trimmed();
45✔
626
    const bool isHeader = isGrepHeaderLine(rawLine, line);
45✔
627
    if (isHeader) {
45✔
628
      if (!currentEntry.isEmpty() && !currentMatches.isEmpty())
14✔
629
        results.append({currentEntry, currentMatches});
3✔
630
      currentEntry = line.endsWith(':') ? line.chopped(1) : line;
14✔
631
      currentMatches.clear();
14✔
632
    } else if (!currentEntry.isEmpty()) {
31✔
633
      if (!line.isEmpty())
29✔
634
        currentMatches << line;
635
    }
636
  }
637
  if (!currentEntry.isEmpty() && !currentMatches.isEmpty())
12✔
638
    results.append({currentEntry, currentMatches});
11✔
639
  return results;
12✔
640
}
641

642
/**
643
 * @brief Pass::processFinished reemits specific signal based on what process
644
 * has finished
645
 * @param id    id of Pass process that was scheduled and finished
646
 * @param exitCode  return code of a process
647
 * @param out   output generated by process(if capturing was requested, empty
648
 *              otherwise)
649
 * @param err   error output generated by process(if capturing was requested,
650
 *              or error occurred)
651
 */
652
void Pass::finished(int id, int exitCode, const QString &out,
32✔
653
                    const QString &err) {
654
  auto pid = static_cast<PROCESS>(id);
32✔
655

656
  if (exitCode != 0) {
32✔
657
    handleProcessError(pid, exitCode, out, err);
2✔
658
    return;
2✔
659
  }
660

661
  emitProcessFinishedSignal(pid, out, err);
30✔
662
}
663

664
void Pass::handleProcessError(PROCESS pid, int exitCode, const QString &out,
2✔
665
                              const QString &err) {
666
  Q_UNUSED(out);
667

668
  if (pid == PASS_GREP) {
2✔
669
    handleGrepError(exitCode, err);
2✔
670
    return;
2✔
671
  }
672

673
  if (pid == PASS_INSERT) {
×
674
    const QString friendly = gpgErrorMessage(err);
×
675
    if (!friendly.isEmpty()) {
×
676
      emit processErrorExit(exitCode, formatInsertError(friendly, err));
×
677
      return;
678
    }
679
  }
680

681
  emit processErrorExit(exitCode, err);
×
682
}
683

684
void Pass::handleGrepError(int exitCode, const QString &err) {
2✔
685
  if (exitCode == 1) {
2✔
686
    emit finishedGrep({});
2✔
687
  } else {
688
    emit processErrorExit(exitCode, err);
1✔
689
    emit finishedGrep({});
2✔
690
  }
691
}
2✔
692

693
auto Pass::formatInsertError(const QString &friendly, const QString &err)
×
694
    -> QString {
695
  QStringList humanLines;
×
696
  for (const QString &line : err.split('\n')) {
×
697
    QString cleanedLine = line;
698
    cleanedLine.remove('\r');
×
699
    if (!cleanedLine.startsWith(QLatin1String("[GNUPG:]")))
×
700
      humanLines.append(cleanedLine);
701
  }
702
  const QString humanErr = humanLines.join('\n').trimmed();
×
703
  return humanErr.isEmpty() ? friendly : friendly + "\n\n" + humanErr;
×
704
}
705

706
/**
707
 * @brief Emit the appropriate finished signal for a completed subprocess.
708
 *
709
 * Emits a specific Qt signal corresponding to the given process identifier; for
710
 * grep results the stdout is parsed into a list of matches before emitting.
711
 *
712
 * @param pid The process identifier indicating which finished signal to emit.
713
 * @param out Standard output produced by the process.
714
 * @param err Standard error produced by the process.
715
 */
716
void Pass::emitProcessFinishedSignal(PROCESS pid, const QString &out,
30✔
717
                                     const QString &err) {
718
  /**
719
   * @brief Filter sensitive commands to prevent password leakage.
720
   *
721
   * Sensitive commands (PASS_SHOW, etc.) output plaintext passwords or
722
   * searchable content that should not be exposed to any UI listener.
723
   *
724
   * Using a default branch: if new PASS_* values are added, they
725
   * default to NOT leaking (safe by default). Making this
726
   * exhaustive would require updating here for every new
727
   * command and risk silent password leakage if forgotten.
728
   */
729
  switch (pid) {
30✔
730
  case PASS_SHOW:
731
  case PASS_OTP_GENERATE:
732
  case PASS_GREP:
733
  case PASS_INSERT:
734
    break;
735
  default:
×
736
    emit finishedAny(out, err);
×
737
    emit finishedAnyWithPid(out, err, pid);
×
738
    break;
×
739
  }
740

741
  switch (pid) {
30✔
742
  case GIT_INIT:
×
743
    emit finishedGitInit(out, err);
×
744
    break;
×
745
  case GIT_PULL:
×
746
    emit finishedGitPull(out, err);
×
747
    break;
×
748
  case GIT_PUSH:
×
749
    emit finishedGitPush(out, err);
×
750
    break;
×
751
  case PASS_SHOW:
10✔
752
    emit finishedShow(out);
10✔
753
    break;
10✔
754
  case PASS_OTP_GENERATE:
×
755
    emit finishedOtpGenerate(out);
×
756
    break;
×
757
  case PASS_INSERT:
19✔
758
    emit finishedInsert(out, err);
19✔
759
    break;
19✔
760
  case PASS_REMOVE:
×
761
    emit finishedRemove(out, err);
×
762
    break;
×
763
  case PASS_INIT:
×
764
    emit finishedInit(out, err);
×
765
    break;
×
766
  case PASS_MOVE:
×
767
    emit finishedMove(out, err);
×
768
    break;
×
769
  case PASS_COPY:
×
770
    emit finishedCopy(out, err);
×
771
    break;
×
772
  case GPG_GENKEYS:
×
773
    emit finishedGenerateGPGKeys(out, err);
×
774
    break;
×
775
  case PASS_GREP:
1✔
776
    emit finishedGrep(parseGrepOutput(out));
1✔
777
    break;
1✔
778
  default:
779
#ifdef QT_DEBUG
780
    dbg() << "Unhandled process type" << pid;
781
#endif
782
    break;
783
  }
784
}
30✔
785

786
/**
787
 * @brief Set or remove a single environment variable in the local env list.
788
 *
789
 * The provided key must include a trailing '=' (e.g. "FOO="). Existing entries
790
 * whose text begins with the given key are removed before the new value is
791
 * applied. If value is non-empty the pair "key+value" is appended; if value is
792
 * empty the variable is removed.
793
 *
794
 * The function asserts if key does not end with '='; if the assertion is not
795
 * active it will emit a warning and return without modifying env.
796
 *
797
 * @param key Environment variable name with trailing '=' (anchors the lookup).
798
 * @param value Value to set for the variable; an empty string unsets the
799
 * variable.
800
 */
801
void Pass::setEnvVar(const QString &key, const QString &value) {
146✔
802
  const bool hasEq = key.endsWith('=');
146✔
803
  Q_ASSERT_X(hasEq, "Pass::setEnvVar",
804
             "called with malformed key (missing '=')");
805
  if (!hasEq) {
146✔
806
    qWarning() << "Pass::setEnvVar called with malformed key (missing '='):"
×
807
               << key;
×
808
    return;
×
809
  }
810
  const QString varName = key.chopped(1);
811
  if (value.isEmpty())
146✔
812
    env.remove(varName);
30✔
813
  else
814
    env.insert(varName, value);
116✔
815
}
816

817
/**
818
 * @brief Update the process environment used for executing external commands.
819
 *
820
 * Updates environment entries for PASSWORD_STORE_SIGNING_KEY,
821
 * PASSWORD_STORE_DIR, PASSWORD_STORE_GENERATED_LENGTH, and
822
 * PASSWORD_STORE_CHARACTER_SET based on current settings, then applies the
823
 * environment to the internal executor.
824
 */
825
void Pass::updateEnv() {
35✔
826
  setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY="),
70✔
827
            m_settings.passSigningKey);
35✔
828
  setEnvVar(QStringLiteral("PASSWORD_STORE_DIR="), m_settings.passStore);
70✔
829

830
  const PasswordConfiguration &passConfig = m_settings.passwordConfiguration;
35✔
831
  setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH="),
70✔
832
            QString::number(passConfig.length));
35✔
833

834
  setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET="),
70✔
835
            effectiveCharset(passConfig));
35✔
836

837
  exec.setEnvironment(env);
35✔
838
}
35✔
839

840
/**
841
 * @brief Pass::getGpgIdPath return gpgid file path for some file (folder).
842
 * @param for_file which file (folder) would you like the gpgid file path for.
843
 * @return path to the gpgid file.
844
 */
845
auto Pass::getGpgIdPath(const QString &for_file) -> QString {
50✔
846
  QString passStore =
847
      QDir::fromNativeSeparators(QtPassSettings::getPassStore());
100✔
848
  QString normalizedFile = QDir::fromNativeSeparators(for_file);
50✔
849
  QString fullPath = normalizedFile.startsWith(passStore)
50✔
850
                         ? normalizedFile
50✔
851
                         : passStore + "/" + normalizedFile;
45✔
852
  QDir gpgIdDir(QFileInfo(fullPath).absoluteDir());
50✔
853
  // QDir::cleanPath() always normalises to forward slashes, so use '/'
854
  // here rather than QDir::separator() (which returns '\\' on Windows).
855
  QString cleanPassStore = QDir::cleanPath(passStore);
50✔
856
  bool found = false;
857
  while (gpgIdDir.exists()) {
71✔
858
    QString currentPath = QDir::cleanPath(gpgIdDir.absolutePath());
128✔
859
    if (currentPath != cleanPassStore &&
86✔
860
        !currentPath.startsWith(cleanPassStore + "/")) {
86✔
861
      break;
862
    }
863
    if (QFile(gpgIdDir.absoluteFilePath(".gpg-id")).exists()) {
126✔
864
      found = true;
865
      break;
866
    }
867
    if (!gpgIdDir.cdUp()) {
21✔
868
      break;
869
    }
870
  }
871
  QString gpgIdPath(
872
      found ? gpgIdDir.absoluteFilePath(".gpg-id")
50✔
873
            : QDir(QtPassSettings::getPassStore()).filePath(".gpg-id"));
116✔
874

875
  return gpgIdPath;
50✔
876
}
50✔
877

878
/**
879
 * @brief Pass::getRecipientList return list of gpg-id's to encrypt for
880
 * @param for_file which file (folder) would you like recipients for
881
 * @return recipients gpg-id contents
882
 */
883
auto Pass::getRecipientList(const QString &for_file) -> QStringList {
26✔
884
  QFile gpgId(getGpgIdPath(for_file));
26✔
885
  if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text)) {
26✔
886
    return {};
×
887
  }
888
  QStringList recipients;
26✔
889
  while (!gpgId.atEnd()) {
60✔
890
    QString recipient(gpgId.readLine());
68✔
891
    recipient = recipient.split("#")[0].trimmed();
68✔
892
    if (!recipient.isEmpty() && Util::isValidKeyId(recipient)) {
34✔
893
      recipients += recipient;
894
    }
895
  }
896
  return recipients;
897
}
26✔
898

899
/**
900
 * @brief Pass::getRecipientString formatted string for use with GPG
901
 * @param for_file which file (folder) would you like recipients for
902
 * @param separator formatting separator eg: " -r "
903
 * @param count
904
 * @return recipient string
905
 */
906
auto Pass::getRecipientString(const QString &for_file, const QString &separator,
2✔
907
                              int *count) -> QStringList {
908
  Q_UNUSED(separator)
909
  QStringList recipients = Pass::getRecipientList(for_file);
2✔
910
  if (count) {
2✔
911
    *count = static_cast<int>(recipients.size());
1✔
912
  }
913
  return recipients;
2✔
914
}
915

916
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
917
 */
918

919
/**
920
 * @brief Generates a random number bounded by the given value.
921
 * @param bound Upper bound (exclusive)
922
 * @return Random number in range [0, bound)
923
 */
924
auto Pass::boundedRandom(quint32 bound) -> quint32 {
7,592✔
925
  if (bound < 2) {
7,592✔
926
    return 0;
927
  }
928

929
  quint32 randval;
930
  // Rejection-sampling threshold to avoid modulo bias.
931
  // This follows the well-known "arc4random_uniform"-style approach:
932
  // reject values in the low range [0, min), where
933
  //   min = 2^32 % bound
934
  // so that the remaining range size is an exact multiple of `bound`.
935
  //
936
  // In quint32 arithmetic, (1 + ~bound) wraps to (2^32 - bound), therefore
937
  //   (1 + ~bound) % bound == 2^32 % bound.
938
  const quint32 rejectionThreshold = (1 + ~bound) % bound;
7,592✔
939

940
  do {
941
    randval = QRandomGenerator::system()->generate();
942
  } while (randval < rejectionThreshold);
7,592✔
943

944
  return randval % bound;
7,592✔
945
}
946

947
/**
948
 * @brief Generates a random password from the given charset.
949
 * @param charset Characters to use in the password
950
 * @param length Desired password length
951
 * @return Generated password string
952
 */
953
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,204✔
954
    -> QString {
955
  if (charset.isEmpty() || length == 0U) {
1,204✔
956
    return {};
957
  }
958
  QString out;
1,204✔
959
  for (unsigned int i = 0; i < length; ++i) {
8,796✔
960
    out.append(charset.at(static_cast<int>(
7,592✔
961
        boundedRandom(static_cast<quint32>(charset.length())))));
7,592✔
962
  }
963
  return out;
964
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc