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

IJHack / QtPass / 24617323889

19 Apr 2026 12:33AM UTC coverage: 22.692% (+0.09%) from 22.607%
24617323889

push

github

web-flow
Merge pull request #1055 from IJHack/fix/refactor-complex-methods

Refactor complex methods to reduce cyclomatic complexity

33 of 84 new or added lines in 2 files covered. (39.29%)

13 existing lines in 3 files now uncovered.

1315 of 5795 relevant lines covered (22.69%)

8.54 hits per line

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

63.18
/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 "helpers.h"
6
#include "qtpasssettings.h"
7
#include "util.h"
8
#include <QCoreApplication>
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
/**
34
 * @brief Pass::Pass wrapper for using either pass or the pass imitation
35
 */
36
Pass::Pass() : wrapperRunning(false), env(QProcess::systemEnvironment()) {
21✔
37
  connect(&exec,
21✔
38
          static_cast<void (Executor::*)(int, int, const QString &,
39
                                         const QString &)>(&Executor::finished),
40
          this, &Pass::finished);
21✔
41

42
  // This was previously using direct QProcess signals.
43
  // The code now uses Executor instead of raw QProcess for better control.
44
  // connect(&process, SIGNAL(error(QProcess::ProcessError)), this,
45
  //        SIGNAL(error(QProcess::ProcessError)));
46

47
  connect(&exec, &Executor::starting, this, &Pass::startingExecuteWrapper);
21✔
48
  // Merge our vars into WSLENV rather than blindly appending a duplicate entry
49
  const QStringList wslenvVars = {
50
      QStringLiteral("PASSWORD_STORE_DIR/p"),
42✔
51
      QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH/w"),
21✔
52
      QStringLiteral("PASSWORD_STORE_CHARACTER_SET/w")};
105✔
53
  const QString wslenvPrefix = QStringLiteral("WSLENV=");
21✔
54
  auto it = std::find_if(env.begin(), env.end(), [&](const QString &s) {
42✔
55
    return s.startsWith(wslenvPrefix);
2,688✔
56
  });
57
  if (it == env.end()) {
21✔
58
    env.append(wslenvPrefix + wslenvVars.join(':'));
42✔
59
  } else {
60
    QStringList parts =
61
        it->mid(wslenvPrefix.size()).split(':', Qt::SkipEmptyParts);
×
62
    for (const QString &v : wslenvVars) {
×
63
      if (!parts.contains(v))
×
64
        parts.append(v);
65
    }
66
    *it = wslenvPrefix + parts.join(':');
×
67
  }
68
}
21✔
69

70
/**
71
 * @brief Executes a wrapper command.
72
 * @param id Process ID
73
 * @param app Application to execute
74
 * @param args Arguments
75
 * @param readStdout Whether to read stdout
76
 * @param readStderr Whether to read stderr
77
 */
78
void Pass::executeWrapper(PROCESS id, const QString &app,
×
79
                          const QStringList &args, bool readStdout,
80
                          bool readStderr) {
81
  executeWrapper(id, app, args, QString(), readStdout, readStderr);
×
82
}
×
83

84
void Pass::executeWrapper(PROCESS id, const QString &app,
×
85
                          const QStringList &args, QString input,
86
                          bool readStdout, bool readStderr) {
87
#ifdef QT_DEBUG
88
  dbg() << app << args;
89
#endif
90
  exec.execute(id, QtPassSettings::getPassStore(), app, args, std::move(input),
×
91
               readStdout, readStderr);
92
}
×
93

94
/**
95
 * @brief Initializes the pass wrapper environment.
96
 */
97
void Pass::init() {
1✔
98
#ifdef __APPLE__
99
  // If it exists, add the gpgtools to PATH
100
  if (QFile("/usr/local/MacGPG2/bin").exists())
101
    env.replaceInStrings("PATH=", "PATH=/usr/local/MacGPG2/bin:");
102
  // Add missing /usr/local/bin
103
  if (env.filter("/usr/local/bin").isEmpty())
104
    env.replaceInStrings("PATH=", "PATH=/usr/local/bin:");
105
#endif
106

107
  if (!QtPassSettings::getGpgHome().isEmpty()) {
2✔
108
    QDir absHome(QtPassSettings::getGpgHome());
×
109
    absHome.makeAbsolute();
×
110
    env << "GNUPGHOME=" + absHome.path();
×
111
  }
×
112
}
1✔
113

114
/**
115
 * @brief Pass::Generate use either pwgen or internal password
116
 * generator
117
 * @param length of the desired password
118
 * @param charset to use for generation
119
 * @return the password
120
 */
121
auto Pass::generatePassword(unsigned int length, const QString &charset)
1,006✔
122
    -> QString {
123
  QString passwd;
1,006✔
124
  if (QtPassSettings::isUsePwgen()) {
1,006✔
125
    // --secure goes first as it overrides --no-* otherwise
126
    QStringList args;
×
127
    args.append("-1");
×
128
    if (!QtPassSettings::isLessRandom()) {
×
129
      args.append("--secure");
×
130
    }
131
    args.append(QtPassSettings::isAvoidCapitals() ? "--no-capitalize"
×
132
                                                  : "--capitalize");
133
    args.append(QtPassSettings::isAvoidNumbers() ? "--no-numerals"
×
134
                                                 : "--numerals");
135
    if (QtPassSettings::isUseSymbols()) {
×
136
      args.append("--symbols");
×
137
    }
138
    args.append(QString::number(length));
×
139
    // executeBlocking returns 0 on success, non-zero on failure
140
    if (Executor::executeBlocking(QtPassSettings::getPwgenExecutable(), args,
×
141
                                  &passwd) == 0) {
142
      static const QRegularExpression literalNewLines{"[\\n\\r]"};
×
143
      passwd.remove(literalNewLines);
×
144
    } else {
145
      passwd.clear();
×
146
#ifdef QT_DEBUG
147
      qDebug() << __FILE__ << ":" << __LINE__ << "\t"
148
               << "pwgen fail";
149
#endif
150
      // Error is already handled by clearing passwd; no need for critical
151
      // signal here
152
    }
153
  } else {
154
    // Validate charset - if CUSTOM is selected but chars are empty,
155
    // fall back to ALLCHARS to prevent weak passwords (issue #780)
156
    QString effectiveCharset = charset;
157
    if (effectiveCharset.isEmpty()) {
1,006✔
158
      effectiveCharset = QtPassSettings::getPasswordConfiguration()
2✔
159
                             .Characters[PasswordConfiguration::ALLCHARS];
160
    }
161
    if (effectiveCharset.length() > 0) {
1,006✔
162
      passwd = generateRandomPassword(effectiveCharset, length);
2,012✔
163
    } else {
164
      emit critical(
×
165
          tr("No characters chosen"),
×
166
          tr("Can't generate password, there are no characters to choose from "
×
167
             "set in the configuration!"));
168
    }
169
  }
170
  return passwd;
1,006✔
171
}
172

173
/**
174
 * @brief Pass::gpgSupportsEd25519 check if GPG supports ed25519 (ECC)
175
 * GPG 2.1+ supports ed25519 which is much faster for key generation
176
 * @return true if ed25519 is supported
177
 */
178
bool Pass::gpgSupportsEd25519() {
2✔
179
  QString out, err;
2✔
180
  if (Executor::executeBlocking(QtPassSettings::getGpgExecutable(),
8✔
181
                                {"--version"}, &out, &err) != 0) {
182
    return false;
183
  }
184
  QRegularExpression versionRegex(R"(gpg \(GnuPG\) (\d+)\.(\d+))");
×
185
  QRegularExpressionMatch match = versionRegex.match(out);
×
186
  if (!match.hasMatch()) {
×
187
    return false;
188
  }
189
  int major = match.captured(1).toInt();
×
190
  int minor = match.captured(2).toInt();
×
191
  return major > 2 || (major == 2 && minor >= 1);
×
192
}
2✔
193

194
/**
195
 * @brief Pass::getDefaultKeyTemplate return default key generation template
196
 * Uses ed25519 if supported, otherwise falls back to RSA
197
 * @return GPG batch template string
198
 */
199
QString Pass::getDefaultKeyTemplate() {
1✔
200
  if (gpgSupportsEd25519()) {
1✔
201
    return QStringLiteral("%echo Generating a default key\n"
×
202
                          "Key-Type: EdDSA\n"
203
                          "Key-Curve: Ed25519\n"
204
                          "Subkey-Type: ECDH\n"
205
                          "Subkey-Curve: Curve25519\n"
206
                          "Name-Real: \n"
207
                          "Name-Comment: QtPass\n"
208
                          "Name-Email: \n"
209
                          "Expire-Date: 0\n"
210
                          "%no-protection\n"
211
                          "%commit\n"
212
                          "%echo done");
213
  }
214
  return QStringLiteral("%echo Generating a default key\n"
1✔
215
                        "Key-Type: RSA\n"
216
                        "Subkey-Type: RSA\n"
217
                        "Name-Real: \n"
218
                        "Name-Comment: QtPass\n"
219
                        "Name-Email: \n"
220
                        "Expire-Date: 0\n"
221
                        "%no-protection\n"
222
                        "%commit\n"
223
                        "%echo done");
224
}
225

226
namespace {
227
auto resolveWslGpgconfPath(const QString &lastPart) -> QString {
3✔
228
  int lastSep = lastPart.lastIndexOf('/');
3✔
229
  if (lastSep < 0) {
3✔
230
    lastSep = lastPart.lastIndexOf('\\');
2✔
231
  }
232
  if (lastSep >= 0) {
2✔
233
    return lastPart.left(lastSep + 1) + "gpgconf";
2✔
234
  }
235
  return QStringLiteral("gpgconf");
2✔
236
}
237

238
/**
239
 * @brief Finds the path to the gpgconf executable in the same directory as the
240
 * given GPG path.
241
 * @example
242
 * QString result = findGpgconfInGpgDir(gpgPath);
243
 * std::cout << result.toStdString() << std::endl; // Expected output: path to
244
 * gpgconf or empty string
245
 *
246
 * @param gpgPath - Absolute path to a GPG executable or related file used to
247
 * locate gpgconf.
248
 * @return QString - The full path to gpgconf if found and executable; otherwise
249
 * an empty QString.
250
 */
251
QString findGpgconfInGpgDir(const QString &gpgPath) {
1✔
252
  QFileInfo gpgInfo(gpgPath);
1✔
253
  if (!gpgInfo.isAbsolute()) {
1✔
254
    return QString();
255
  }
256

257
  QDir dir(gpgInfo.absolutePath());
1✔
258

259
#ifdef Q_OS_WIN
260
  QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
261
  if (candidateExe.isExecutable()) {
262
    return candidateExe.filePath();
263
  }
264
#endif
265

266
  QFileInfo candidate(dir.filePath("gpgconf"));
1✔
267
  if (candidate.isExecutable()) {
1✔
268
    return candidate.filePath();
×
269
  }
270
  return QString();
271
}
1✔
272

273
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
274
/**
275
 * @brief Splits a command string into arguments while respecting quotes and
276
 * escape characters.
277
 * @example
278
 * QStringList result = splitCommandCompat("cmd \"arg one\" 'arg two'
279
 * escaped\\ space");
280
 * // Expected output: ["cmd", "arg one", "arg two", "escaped space"]
281
 *
282
 * @param command - The input command string to split into individual arguments.
283
 * @return QStringList - A list of parsed command arguments.
284
 */
285
QStringList splitCommandCompat(const QString &command) {
286
  QStringList result;
287
  QString current;
288
  bool inSingleQuote = false;
289
  bool inDoubleQuote = false;
290
  bool escaping = false;
291
  for (QChar ch : command) {
292
    if (escaping) {
293
      current.append(ch);
294
      escaping = false;
295
      continue;
296
    }
297
    if (ch == '\\') {
298
      escaping = true;
299
      continue;
300
    }
301
    if (ch == '\'' && !inDoubleQuote) {
302
      inSingleQuote = !inSingleQuote;
303
      continue;
304
    }
305
    if (ch == '"' && !inSingleQuote) {
306
      inDoubleQuote = !inDoubleQuote;
307
      continue;
308
    }
309
    if (ch.isSpace() && !inSingleQuote && !inDoubleQuote) {
310
      if (!current.isEmpty()) {
311
        result.append(current);
312
        current.clear();
313
      }
314
      continue;
315
    }
316
    current.append(ch);
317
  }
318
  if (escaping) {
319
    current.append('\\');
320
  }
321
  if (!current.isEmpty()) {
322
    result.append(current);
323
  }
324
  return result;
325
}
326
#endif
327

328
} // namespace
329

330
/**
331
 * @brief Resolves the appropriate gpgconf command from a given GPG executable
332
 * path or command string.
333
 * @example
334
 * ResolvedGpgconfCommand result = Pass::resolveGpgconfCommand("wsl.exe
335
 * /usr/bin/gpg"); std::cout << result.first.toStdString() << std::endl; //
336
 * Expected output sample
337
 *
338
 * @param const QString &gpgPath - Path or command string pointing to the GPG
339
 * executable.
340
 * @return ResolvedGpgconfCommand - A pair containing the resolved gpgconf
341
 * command and its arguments.
342
 */
343
auto Pass::resolveGpgconfCommand(const QString &gpgPath)
8✔
344
    -> ResolvedGpgconfCommand {
345
  if (gpgPath.trimmed().isEmpty()) {
8✔
346
    return {"gpgconf", {}};
347
  }
348

349
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
350
  QStringList parts = QProcess::splitCommand(gpgPath);
7✔
351
#else
352
  QStringList parts = splitCommandCompat(gpgPath);
353
#endif
354

355
  if (parts.isEmpty()) {
7✔
356
    return {"gpgconf", {}};
357
  }
358

359
  const QString first = parts.first();
360
  if (first == "wsl" || first == "wsl.exe") {
9✔
361
    if (parts.size() >= 2 && parts.at(1).startsWith("sh")) {
9✔
362
      return {"gpgconf", {}};
363
    }
364
    if (parts.size() >= 2 &&
4✔
365
        QFileInfo(parts.last()).fileName().startsWith("gpg")) {
10✔
366
      QString wslGpgconf = resolveWslGpgconfPath(parts.last());
3✔
367
      parts.removeLast();
3✔
368
      parts.append(wslGpgconf);
369
      return {parts.first(), parts.mid(1)};
370
    }
371
    return {"gpgconf", {}};
372
  }
373

374
  if (!first.contains('/') && !first.contains('\\')) {
2✔
375
    return {"gpgconf", {}};
376
  }
377

378
  QString gpgconfPath = findGpgconfInGpgDir(gpgPath);
1✔
379
  if (!gpgconfPath.isEmpty()) {
1✔
380
    return {gpgconfPath, {}};
×
381
  }
382

383
  return {"gpgconf", {}};
384
}
8✔
385

386
/**
387
 * @brief Pass::GenerateGPGKeys internal gpg keypair generator . .
388
 * @param batch GnuPG style configuration string
389
 */
390
void Pass::GenerateGPGKeys(QString batch) {
×
391
  // Kill any stale GPG agents that might be holding locks on the key database
392
  // This helps avoid "database locked" timeouts during key generation
393
  QString gpgPath = QtPassSettings::getGpgExecutable();
×
394
  if (!gpgPath.isEmpty()) {
×
395
    ResolvedGpgconfCommand gpgconf = resolveGpgconfCommand(gpgPath);
×
396
    QStringList killArgs = gpgconf.arguments;
397
    killArgs << "--kill";
×
398
    killArgs << "gpg-agent";
×
399
    // Use same environment as key generation to target correct gpg-agent
400
    Executor::executeBlocking(env, gpgconf.program, killArgs);
×
401
  }
402

403
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
×
404
                 std::move(batch));
405
}
×
406

407
/**
408
 * @brief Pass::listKeys list users
409
 * @param keystrings
410
 * @param secret list private keys
411
 * @return QList<UserInfo> users
412
 */
413
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
×
414
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
×
415
  args.append(secret ? "--list-secret-keys" : "--list-keys");
×
416

417
  for (const QString &keystring : AS_CONST(keystrings)) {
×
418
    if (!keystring.isEmpty()) {
×
419
      args.append(keystring);
420
    }
421
  }
422
  QString p_out;
×
423
  if (Executor::executeBlocking(QtPassSettings::getGpgExecutable(), args,
×
424
                                &p_out) != 0) {
425
    return QList<UserInfo>();
×
426
  }
427
  return parseGpgColonOutput(p_out, secret);
×
428
}
×
429

430
/**
431
 * @brief Pass::listKeys list users
432
 * @param keystring
433
 * @param secret list private keys
434
 * @return QList<UserInfo> users
435
 */
436
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
×
437
  return listKeys(QStringList(keystring), secret);
×
438
}
439

440
/**
441
 * @brief Maps GPG stderr (which may include --status-fd 2 tokens) to a
442
 * user-friendly encryption error string.
443
 *
444
 * Checked in order: machine-readable [GNUPG:] status tokens first (locale-
445
 * independent), then case-insensitive substring fallbacks for GPG builds that
446
 * don't emit status tokens.
447
 *
448
 * @param err Raw stderr from GPG
449
 * @return Translated human-readable error, or empty string if not recognised
450
 */
451
namespace {
452

453
auto containsAny(const QString &str, const QStringList &patterns) -> bool {
31✔
454
  for (const QString &p : patterns) {
82✔
455
    if (str.contains(p)) {
58✔
456
      return true;
457
    }
458
  }
459
  return false;
460
}
461

462
/**
463
 * @brief Checks if str contains any of the patterns (case-insensitive).
464
 * @param str String to search in (will be lowercased once).
465
 * @param patterns List of patterns to search for (must be lowercase; caller
466
 * should convert patterns to lowercase before calling).
467
 * @return true if any pattern is found.
468
 */
469
auto containsAnyCaseInsensitive(const QString &str, const QStringList &patterns)
13✔
470
    -> bool {
471
  const QString lower = str.toLower();
472
  for (const QString &p : patterns) {
32✔
473
    if (lower.contains(p)) {
23✔
474
      return true;
475
    }
476
  }
477
  return false;
478
}
479

480
} // namespace
481

482
auto gpgErrorMessage(const QString &err) -> QString {
13✔
483
  // Machine-readable status tokens added by --status-fd 2
484
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYEXPIRED"),
65✔
485
                        QStringLiteral("[GNUPG:] INV_RECP 5 ")}))
13✔
486
    return QCoreApplication::translate(
487
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
488
                "replace it.");
3✔
489
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYREVOKED"),
50✔
490
                        QStringLiteral("[GNUPG:] INV_RECP 4 ")}))
10✔
491
    return QCoreApplication::translate(
492
        "Pass", "Encryption failed: GPG key has been revoked.");
2✔
493
  if (containsAny(err, {QStringLiteral("[GNUPG:] NO_PUBKEY"),
40✔
494
                        QStringLiteral("[GNUPG:] INV_RECP")}))
8✔
495
    return QCoreApplication::translate(
496
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
497
                "Check that the key ID in .gpg-id is correct and imported.");
2✔
498
  if (err.contains(QStringLiteral("[GNUPG:] FAILURE")))
6✔
499
    return QCoreApplication::translate(
500
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1✔
501

502
  // Locale-dependent fallbacks
503
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has expired"),
20✔
504
                                       QLatin1String("key expired")}))
505
    return QCoreApplication::translate(
506
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
507
                "replace it.");
1✔
508
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has been revoked"),
16✔
509
                                       QLatin1String("revoked")}))
510
    return QCoreApplication::translate(
511
        "Pass", "Encryption failed: GPG key has been revoked.");
1✔
512
  if (containsAnyCaseInsensitive(err, {QLatin1String("no public key"),
15✔
513
                                       QLatin1String("unusable public key"),
514
                                       QLatin1String("no secret key")}))
515
    return QCoreApplication::translate(
516
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
517
                "Check that the key ID in .gpg-id is correct and imported.");
2✔
518
  if (containsAnyCaseInsensitive(err, {QLatin1String("encryption failed")}))
3✔
519
    return QCoreApplication::translate(
520
        "Pass", "Encryption failed. Check that your GPG key is valid.");
×
521

522
  return {};
UNCOV
523
}
×
524

525
/**
526
 * @brief Parses 'pass grep' raw output into (entry, matches) pairs.
527
 *
528
 * pass grep emits ANSI blue color (\x1B[94m) at the start of each entry
529
 * header line. This is checked before stripping ANSI so headers are detected
530
 * reliably regardless of locale.
531
 */
532
auto parseGrepOutput(const QString &rawOut)
12✔
533
    -> QList<QPair<QString, QStringList>> {
534
  static const QRegularExpression ansi(
535
      QStringLiteral(R"(\x1B\[[0-9;]*[a-zA-Z])"));
13✔
536
  QList<QPair<QString, QStringList>> results;
12✔
537
  QString currentEntry;
12✔
538
  QStringList currentMatches;
12✔
539
  for (const QString &rawLine : rawOut.split('\n')) {
69✔
540
    QString line = rawLine;
541
    line.remove('\r');
45✔
542
    line.remove(ansi);
45✔
543
    line = line.trimmed();
45✔
544
    // ANSI-colored header starts with the blue escape; plain-text fallback:
545
    // a non-indented line ending with ':' (pass grep format without color)
546
    bool isHeader = rawLine.startsWith(QStringLiteral("\x1B[94m")) ||
123✔
547
                    (!rawLine.startsWith(' ') && !rawLine.startsWith('\t') &&
91✔
548
                     line.endsWith(':') && !line.isEmpty());
76✔
549
    if (isHeader) {
45✔
550
      if (!currentEntry.isEmpty() && !currentMatches.isEmpty())
14✔
551
        results.append({currentEntry, currentMatches});
3✔
552
      currentEntry = line.endsWith(':') ? line.chopped(1) : line;
14✔
553
      currentMatches.clear();
14✔
554
    } else if (!currentEntry.isEmpty()) {
31✔
555
      if (!line.isEmpty())
29✔
556
        currentMatches << line;
557
    }
558
  }
559
  if (!currentEntry.isEmpty() && !currentMatches.isEmpty())
12✔
560
    results.append({currentEntry, currentMatches});
11✔
561
  return results;
12✔
562
}
563

564
/**
565
 * @brief Pass::processFinished reemits specific signal based on what process
566
 * has finished
567
 * @param id    id of Pass process that was scheduled and finished
568
 * @param exitCode  return code of a process
569
 * @param out   output generated by process(if capturing was requested, empty
570
 *              otherwise)
571
 * @param err   error output generated by process(if capturing was requested,
572
 *              or error occurred)
573
 */
574
void Pass::finished(int id, int exitCode, const QString &out,
3✔
575
                    const QString &err) {
576
  auto pid = static_cast<PROCESS>(id);
3✔
577

578
  if (exitCode != 0) {
3✔
579
    handleProcessError(pid, exitCode, out, err);
2✔
580
    return;
2✔
581
  }
582

583
  emitProcessFinishedSignal(pid, out, err);
1✔
584
}
585

586
void Pass::handleProcessError(PROCESS pid, int exitCode, const QString &out,
2✔
587
                              const QString &err) {
588
  if (pid == PASS_GREP) {
2✔
589
    handleGrepError(exitCode, err);
2✔
590
    return;
2✔
591
  }
592

NEW
593
  if (pid == PASS_INSERT) {
×
NEW
594
    const QString friendly = gpgErrorMessage(err);
×
NEW
595
    if (!friendly.isEmpty()) {
×
NEW
596
      emit processErrorExit(exitCode, formatInsertError(friendly, err));
×
597
      return;
598
    }
599
  }
600

NEW
601
  emit processErrorExit(exitCode, err);
×
602
}
603

604
void Pass::handleGrepError(int exitCode, const QString &err) {
2✔
605
  if (exitCode == 1) {
2✔
606
    emit finishedGrep({});
2✔
607
  } else {
608
    emit processErrorExit(exitCode, err);
1✔
609
    emit finishedGrep({});
2✔
610
  }
611
}
2✔
612

NEW
613
auto Pass::formatInsertError(const QString &friendly, const QString &err)
×
614
    -> QString {
NEW
615
  QStringList humanLines;
×
NEW
616
  for (QString line : err.split('\n')) {
×
NEW
617
    line.remove('\r');
×
NEW
618
    if (!line.startsWith(QLatin1String("[GNUPG:]")))
×
619
      humanLines.append(line);
620
  }
NEW
621
  const QString humanErr = humanLines.join('\n').trimmed();
×
NEW
622
  return humanErr.isEmpty() ? friendly : friendly + "\n\n" + humanErr;
×
623
}
624

625
void Pass::emitProcessFinishedSignal(PROCESS pid, const QString &out,
1✔
626
                                     const QString &err) {
627
  switch (pid) {
1✔
628
  case GIT_INIT:
×
629
    emit finishedGitInit(out, err);
×
630
    break;
×
631
  case GIT_PULL:
×
632
    emit finishedGitPull(out, err);
×
633
    break;
×
634
  case GIT_PUSH:
×
635
    emit finishedGitPush(out, err);
×
636
    break;
×
637
  case PASS_SHOW:
×
638
    emit finishedShow(out);
×
639
    break;
×
640
  case PASS_OTP_GENERATE:
×
641
    emit finishedOtpGenerate(out);
×
642
    break;
×
643
  case PASS_INSERT:
×
644
    emit finishedInsert(out, err);
×
645
    break;
×
646
  case PASS_REMOVE:
×
647
    emit finishedRemove(out, err);
×
648
    break;
×
649
  case PASS_INIT:
×
650
    emit finishedInit(out, err);
×
651
    break;
×
652
  case PASS_MOVE:
×
653
    emit finishedMove(out, err);
×
654
    break;
×
655
  case PASS_COPY:
×
656
    emit finishedCopy(out, err);
×
657
    break;
×
658
  case GPG_GENKEYS:
×
659
    emit finishedGenerateGPGKeys(out, err);
×
660
    break;
×
661
  case PASS_GREP:
1✔
662
    emit finishedGrep(parseGrepOutput(out));
1✔
663
    break;
1✔
664
  default:
665
#ifdef QT_DEBUG
666
    dbg() << "Unhandled process type" << pid;
667
#endif
668
    break;
669
  }
670
}
1✔
671

672
/**
673
 * @brief Pass::updateEnv update the execution environment (used when
674
 * switching profiles)
675
 */
676
// key must include the trailing '=' (e.g. "FOO="); env.filter() does substring
677
// matching so the '=' anchors the lookup to avoid collisions with longer names.
678
void Pass::setEnvVar(const QString &key, const QString &value) {
38✔
679
  Q_ASSERT(key.endsWith('='));
680
  const QStringList existing = env.filter(key);
38✔
681
  for (const QString &entry : std::as_const(existing))
43✔
682
    env.removeAll(entry);
683
  if (!value.isEmpty())
38✔
684
    env.append(key + value);
56✔
685
}
38✔
686

687
void Pass::updateEnv() {
8✔
688
  setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY="),
16✔
689
            QtPassSettings::getPassSigningKey());
16✔
690
  setEnvVar(QStringLiteral("PASSWORD_STORE_DIR="),
16✔
691
            QtPassSettings::getPassStore());
16✔
692

693
  PasswordConfiguration passConfig = QtPassSettings::getPasswordConfiguration();
8✔
694
  setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH="),
16✔
695
            QString::number(passConfig.length));
8✔
696

697
  int sel = passConfig.selected;
8✔
698
  if (sel < 0 || sel >= PasswordConfiguration::CHARSETS_COUNT)
8✔
699
    sel = PasswordConfiguration::ALLCHARS;
700
  QString charset = passConfig.Characters[sel];
701
  if (charset.isEmpty())
8✔
702
    charset = passConfig.Characters[PasswordConfiguration::ALLCHARS];
1✔
703
  setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET="), charset);
16✔
704

705
  exec.setEnvironment(env);
8✔
706
}
8✔
707

708
/**
709
 * @brief Pass::getGpgIdPath return gpgid file path for some file (folder).
710
 * @param for_file which file (folder) would you like the gpgid file path for.
711
 * @return path to the gpgid file.
712
 */
713
auto Pass::getGpgIdPath(const QString &for_file) -> QString {
9✔
714
  QString passStore =
715
      QDir::fromNativeSeparators(QtPassSettings::getPassStore());
18✔
716
  QString normalizedFile = QDir::fromNativeSeparators(for_file);
9✔
717
  QString fullPath = normalizedFile.startsWith(passStore)
9✔
718
                         ? normalizedFile
9✔
719
                         : passStore + "/" + normalizedFile;
7✔
720
  QDir gpgIdDir(QFileInfo(fullPath).absoluteDir());
9✔
721
  bool found = false;
722
  while (gpgIdDir.exists() && gpgIdDir.absolutePath().startsWith(passStore)) {
11✔
723
    if (QFile(gpgIdDir.absoluteFilePath(".gpg-id")).exists()) {
2✔
724
      found = true;
725
      break;
726
    }
727
    if (!gpgIdDir.cdUp()) {
×
728
      break;
729
    }
730
  }
731
  QString gpgIdPath(
732
      found ? gpgIdDir.absoluteFilePath(".gpg-id")
9✔
733
            : QDir(QtPassSettings::getPassStore()).filePath(".gpg-id"));
33✔
734

735
  return gpgIdPath;
9✔
736
}
9✔
737

738
/**
739
 * @brief Pass::getRecipientList return list of gpg-id's to encrypt for
740
 * @param for_file which file (folder) would you like recipients for
741
 * @return recipients gpg-id contents
742
 */
743
auto Pass::getRecipientList(const QString &for_file) -> QStringList {
6✔
744
  QFile gpgId(getGpgIdPath(for_file));
6✔
745
  if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text)) {
6✔
746
    return {};
×
747
  }
748
  QStringList recipients;
6✔
749
  while (!gpgId.atEnd()) {
20✔
750
    QString recipient(gpgId.readLine());
28✔
751
    recipient = recipient.split("#")[0].trimmed();
28✔
752
    if (!recipient.isEmpty() && Util::isValidKeyId(recipient)) {
14✔
753
      recipients += recipient;
754
    }
755
  }
756
  return recipients;
757
}
6✔
758

759
/**
760
 * @brief Pass::getRecipientString formatted string for use with GPG
761
 * @param for_file which file (folder) would you like recipients for
762
 * @param separator formating separator eg: " -r "
763
 * @param count
764
 * @return recipient string
765
 */
766
auto Pass::getRecipientString(const QString &for_file, const QString &separator,
2✔
767
                              int *count) -> QStringList {
768
  Q_UNUSED(separator)
769
  QStringList recipients = Pass::getRecipientList(for_file);
2✔
770
  if (count) {
2✔
771
    *count = recipients.size();
1✔
772
  }
773
  return recipients;
2✔
774
}
775

776
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
777
 */
778

779
/**
780
 * @brief Generates a random number bounded by the given value.
781
 * @param bound Upper bound (exclusive)
782
 * @return Random number in range [0, bound)
783
 */
784
auto Pass::boundedRandom(quint32 bound) -> quint32 {
1,224✔
785
  if (bound < 2) {
1,224✔
786
    return 0;
787
  }
788

789
  quint32 randval;
790
  // Rejection-sampling threshold to avoid modulo bias:
791
  // In quint32 arithmetic, (1 + ~bound) wraps to (2^32 - bound), so
792
  // (1 + ~bound) % bound == 2^32 % bound.
793
  // Values randval < max_mod_bound are rejected; accepted values produce a
794
  // uniform distribution when reduced with (randval % bound).
795
  const quint32 max_mod_bound = (1 + ~bound) % bound;
1,224✔
796

797
  do {
798
    randval = QRandomGenerator::system()->generate();
799
  } while (randval < max_mod_bound);
1,224✔
800

801
  return randval % bound;
1,224✔
802
}
803

804
/**
805
 * @brief Generates a random password from the given charset.
806
 * @param charset Characters to use in the password
807
 * @param length Desired password length
808
 * @return Generated password string
809
 */
810
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,006✔
811
    -> QString {
812
  if (charset.isEmpty() || length == 0U) {
1,006✔
813
    return {};
814
  }
815
  QString out;
1,005✔
816
  for (unsigned int i = 0; i < length; ++i) {
2,229✔
817
    out.append(charset.at(static_cast<int>(
1,224✔
818
        boundedRandom(static_cast<quint32>(charset.length())))));
1,224✔
819
  }
820
  return out;
821
}
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