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

IJHack / QtPass / 27662039065

17 Jun 2026 02:37AM UTC coverage: 57.501% (+0.02%) from 57.477%
27662039065

Pull #1551

github

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

52 of 92 new or added lines in 6 files covered. (56.52%)

13 existing lines in 6 files now uncovered.

3990 of 6939 relevant lines covered (57.5%)

23.81 hits per line

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

69.62
/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, &passwd) ==
×
184
        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, m_settings.passwordConfiguration
201
                     .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 =
221
      gpgExecutable.isEmpty() ? QStringLiteral("gpg") : gpgExecutable;
12✔
222
  QString out, err;
12✔
223
  if (Executor::executeBlocking(exe, {"--version"}, &out, &err) != 0) {
36✔
224
    return false;
225
  }
226
  QRegularExpression versionRegex(R"(gpg \(GnuPG\) (\d+)\.(\d+))");
4✔
227
  QRegularExpressionMatch match = versionRegex.match(out);
2✔
228
  if (!match.hasMatch()) {
2✔
229
    return false;
230
  }
231
  int major = match.captured(1).toInt();
2✔
232
  int minor = match.captured(2).toInt();
2✔
233
  return major > 2 || (major == 2 && minor >= 1);
2✔
234
}
14✔
235

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

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

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

309
  QDir dir(gpgInfo.absolutePath());
1✔
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"));
1✔
319
  if (candidate.isExecutable()) {
1✔
320
    return candidate.filePath();
×
321
  }
322
  return {};
323
}
1✔
324

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

383
} // namespace
384

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

544
} // namespace
545

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

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

586
  return {};
587
}
×
588

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

876
  return gpgIdPath;
50✔
877
}
50✔
878

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

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

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

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

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

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

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

948
/**
949
 * @brief Generates a random password from the given charset.
950
 * @param charset Characters to use in the password
951
 * @param length Desired password length
952
 * @return Generated password string
953
 */
954
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,204✔
955
    -> QString {
956
  if (charset.isEmpty() || length == 0U) {
1,204✔
957
    return {};
958
  }
959
  QString out;
1,204✔
960
  for (unsigned int i = 0; i < length; ++i) {
8,796✔
961
    out.append(charset.at(static_cast<int>(
7,592✔
962
        boundedRandom(static_cast<quint32>(charset.length())))));
7,592✔
963
  }
964
  return out;
965
}
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