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

IJHack / QtPass / 24616996157

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

Pull #1055

github

web-flow
Merge 8df346373 into d1a8c382f
Pull Request #1055: Refactor complex methods to reduce cyclomatic complexity

27 of 89 new or added lines in 2 files covered. (30.34%)

6 existing lines in 2 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
bool containsAny(const QString &str, const QStringList &patterns) {
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
bool containsAnyCaseInsensitive(const QString &str,
12✔
463
                                const QStringList &patterns) {
464
  const QString lower = str.toLower();
465
  for (const QString &p : patterns) {
30✔
466
    if (lower.contains(p.toLower())) {
22✔
467
      return true;
468
    }
469
  }
470
  return false;
471
}
472

473
} // namespace
474

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

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

515
  return {};
NEW
516
}
×
517

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

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

571
  if (exitCode != 0) {
3✔
572
    handleProcessError(pid, exitCode, out, err);
2✔
573
    return;
2✔
574
  }
575

576
  emitProcessFinishedSignal(pid, out, err);
1✔
577
}
578

579
void Pass::handleProcessError(PROCESS pid, int exitCode, const QString &out,
2✔
580
                              const QString &err) {
581
  if (pid == PASS_GREP) {
2✔
582
    handleGrepError(exitCode, err);
2✔
583
    return;
2✔
584
  }
585

NEW
586
  if (pid == PASS_INSERT) {
×
NEW
587
    const QString friendly = gpgErrorMessage(err);
×
NEW
588
    if (!friendly.isEmpty()) {
×
NEW
589
      emit processErrorExit(exitCode, formatInsertError(friendly, err));
×
590
      return;
591
    }
592
  }
593

NEW
594
  emit processErrorExit(exitCode, err);
×
595
}
596

597
void Pass::handleGrepError(int exitCode, const QString &err) {
2✔
598
  if (exitCode == 1) {
2✔
599
    emit finishedGrep({});
2✔
600
  } else {
601
    emit processErrorExit(exitCode, err);
1✔
602
    emit finishedGrep({});
2✔
603
  }
604
}
2✔
605

NEW
606
auto Pass::formatInsertError(const QString &friendly, const QString &err)
×
607
    -> QString {
608
  QStringList humanLines;
×
NEW
609
  for (QString line : err.split('\n')) {
×
NEW
610
    line.remove('\r');
×
NEW
611
    if (!line.startsWith(QLatin1String("[GNUPG:]")))
×
612
      humanLines.append(line);
613
  }
NEW
614
  const QString humanErr = humanLines.join('\n').trimmed();
×
NEW
615
  return humanErr.isEmpty() ? friendly : friendly + "\n\n" + humanErr;
×
616
}
617

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

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

680
void Pass::updateEnv() {
8✔
681
  setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY="),
16✔
682
            QtPassSettings::getPassSigningKey());
16✔
683
  setEnvVar(QStringLiteral("PASSWORD_STORE_DIR="),
16✔
684
            QtPassSettings::getPassStore());
16✔
685

686
  PasswordConfiguration passConfig = QtPassSettings::getPasswordConfiguration();
8✔
687
  setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH="),
16✔
688
            QString::number(passConfig.length));
8✔
689

690
  int sel = passConfig.selected;
8✔
691
  if (sel < 0 || sel >= PasswordConfiguration::CHARSETS_COUNT)
8✔
692
    sel = PasswordConfiguration::ALLCHARS;
693
  QString charset = passConfig.Characters[sel];
694
  if (charset.isEmpty())
8✔
695
    charset = passConfig.Characters[PasswordConfiguration::ALLCHARS];
1✔
696
  setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET="), charset);
16✔
697

698
  exec.setEnvironment(env);
8✔
699
}
8✔
700

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

728
  return gpgIdPath;
9✔
729
}
9✔
730

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

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

769
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
770
 */
771

772
/**
773
 * @brief Generates a random number bounded by the given value.
774
 * @param bound Upper bound (exclusive)
775
 * @return Random number in range [0, bound)
776
 */
777
auto Pass::boundedRandom(quint32 bound) -> quint32 {
1,224✔
778
  if (bound < 2) {
1,224✔
779
    return 0;
780
  }
781

782
  quint32 randval;
783
  // Rejection-sampling threshold to avoid modulo bias:
784
  // In quint32 arithmetic, (1 + ~bound) wraps to (2^32 - bound), so
785
  // (1 + ~bound) % bound == 2^32 % bound.
786
  // Values randval < max_mod_bound are rejected; accepted values produce a
787
  // uniform distribution when reduced with (randval % bound).
788
  const quint32 max_mod_bound = (1 + ~bound) % bound;
1,224✔
789

790
  do {
791
    randval = QRandomGenerator::system()->generate();
792
  } while (randval < max_mod_bound);
1,224✔
793

794
  return randval % bound;
1,224✔
795
}
796

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