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

IJHack / QtPass / 24639890620

19 Apr 2026 09:46PM UTC coverage: 27.362%. First build
24639890620

Pull #1087

github

web-flow
Merge 2eaa34ed6 into ed8be909f
Pull Request #1087: docs: standardise Doxygen style across headers and main.cpp

15 of 25 new or added lines in 3 files covered. (60.0%)

1596 of 5833 relevant lines covered (27.36%)

16.44 hits per line

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

68.08
/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 <QDebug>
10
#include <QDir>
11
#include <QFileInfo>
12
#include <QProcess>
13
#include <QRandomGenerator>
14
#include <QRegularExpression>
15
#include <algorithm>
16
#include <utility>
17

18
#ifdef QT_DEBUG
19
#include "debughelper.h"
20
#endif
21

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

35
namespace {
36
auto fallbackCharset(const QString &input, const QString &fallback) -> QString {
37
  return input.isEmpty() ? fallback : input;
1,021✔
38
}
39

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

50
/**
51
 * @brief Pass::Pass wrapper for using either pass or the pass imitation
52
 */
53
Pass::Pass() : wrapperRunning(false), env(QProcess::systemEnvironment()) {
29✔
54
  connect(&exec,
29✔
55
          static_cast<void (Executor::*)(int, int, const QString &,
56
                                         const QString &)>(&Executor::finished),
57
          this, &Pass::finished);
29✔
58

59
  // This was previously using direct QProcess signals.
60
  // The code now uses Executor instead of raw QProcess for better control.
61
  // connect(&process, SIGNAL(error(QProcess::ProcessError)), this,
62
  //        SIGNAL(error(QProcess::ProcessError)));
63

64
  connect(&exec, &Executor::starting, this, &Pass::startingExecuteWrapper);
29✔
65
  // Merge our vars into WSLENV rather than blindly appending a duplicate entry
66
  const QStringList wslenvVars = {
67
      QStringLiteral("PASSWORD_STORE_DIR/p"),
58✔
68
      QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH/w"),
29✔
69
      QStringLiteral("PASSWORD_STORE_CHARACTER_SET/w")};
145✔
70
  const QString wslenvPrefix = QStringLiteral("WSLENV=");
29✔
71
  auto it =
72
      std::find_if(env.begin(), env.end(), [&wslenvPrefix](const QString &s) {
58✔
73
        return s.startsWith(wslenvPrefix);
3,720✔
74
      });
75
  if (it == env.end()) {
29✔
76
    env.append(wslenvPrefix + wslenvVars.join(':'));
58✔
77
  } else {
78
    QStringList parts =
79
        it->mid(wslenvPrefix.size()).split(':', Qt::SkipEmptyParts);
×
80
    for (const QString &v : wslenvVars) {
×
81
      if (!parts.contains(v))
×
82
        parts.append(v);
83
    }
84
    *it = wslenvPrefix + parts.join(':');
×
85
  }
86
}
29✔
87

88
/**
89
 * @brief Executes a wrapper command.
90
 * @param id Process ID
91
 * @param app Application to execute
92
 * @param args Arguments
93
 * @param readStdout Whether to read stdout
94
 * @param readStderr Whether to read stderr
95
 */
96
void Pass::executeWrapper(PROCESS id, const QString &app,
×
97
                          const QStringList &args, bool readStdout,
98
                          bool readStderr) {
99
  executeWrapper(id, app, args, QString(), readStdout, readStderr);
×
100
}
×
101

102
void Pass::executeWrapper(PROCESS id, const QString &app,
17✔
103
                          const QStringList &args, QString input,
104
                          bool readStdout, bool readStderr) {
105
#ifdef QT_DEBUG
106
  dbg() << app << args;
107
#endif
108
  exec.execute(id, QtPassSettings::getPassStore(), app, args, std::move(input),
34✔
109
               readStdout, readStderr);
110
}
17✔
111

112
/**
113
 * @brief Initializes the pass wrapper environment.
114
 */
115
void Pass::init() {
9✔
116
#ifdef __APPLE__
117
  // If it exists, add the gpgtools to PATH
118
  if (QFile("/usr/local/MacGPG2/bin").exists())
119
    env.replaceInStrings("PATH=", "PATH=/usr/local/MacGPG2/bin:");
120
  // Add missing /usr/local/bin
121
  if (env.filter("/usr/local/bin").isEmpty())
122
    env.replaceInStrings("PATH=", "PATH=/usr/local/bin:");
123
#endif
124

125
  if (!QtPassSettings::getGpgHome().isEmpty()) {
18✔
126
    QDir absHome(QtPassSettings::getGpgHome());
16✔
127
    absHome.makeAbsolute();
8✔
128
    env << "GNUPGHOME=" + absHome.path();
8✔
129
  }
8✔
130
}
9✔
131

132
/**
133
 * @brief Pass::Generate use either pwgen or internal password
134
 * generator
135
 * @param length of the desired password
136
 * @param charset to use for generation
137
 * @return the password
138
 */
139
auto Pass::generatePassword(unsigned int length, const QString &charset)
1,006✔
140
    -> QString {
141
  if (length == 0) {
1,006✔
142
    emit critical(tr("Invalid password length"),
2✔
143
                  tr("Can't generate password with zero length."));
1✔
144
    return {};
145
  }
146
  QString passwd;
1,005✔
147
  if (QtPassSettings::isUsePwgen()) {
1,005✔
148
    // --secure goes first as it overrides --no-* otherwise
149
    QStringList args;
×
150
    args.append("-1");
×
151
    if (!QtPassSettings::isLessRandom()) {
×
152
      args.append("--secure");
×
153
    }
154
    args.append(QtPassSettings::isAvoidCapitals() ? "--no-capitalize"
×
155
                                                  : "--capitalize");
156
    args.append(QtPassSettings::isAvoidNumbers() ? "--no-numerals"
×
157
                                                 : "--numerals");
158
    if (QtPassSettings::isUseSymbols()) {
×
159
      args.append("--symbols");
×
160
    }
161
    args.append(QString::number(length));
×
162
    // executeBlocking returns 0 on success, non-zero on failure
163
    if (Executor::executeBlocking(QtPassSettings::getPwgenExecutable(), args,
×
164
                                  &passwd) == 0) {
165
      static const QRegularExpression literalNewLines{"[\\n\\r]"};
×
166
      passwd.remove(literalNewLines);
×
167
    } else {
168
      passwd.clear();
×
169
#ifdef QT_DEBUG
170
      qDebug() << __FILE__ << ":" << __LINE__ << "\t"
171
               << "pwgen fail";
172
#endif
173
      // Error is already handled by clearing passwd; no need for critical
174
      // signal here
175
    }
176
  } else {
177
    // Validate charset - if CUSTOM is selected but chars are empty,
178
    // fall back to ALLCHARS to prevent weak passwords (issue #780)
179
    const QString cs = fallbackCharset(
180
        charset, QtPassSettings::getPasswordConfiguration()
2,010✔
181
                     .Characters[PasswordConfiguration::ALLCHARS]);
182
    if (cs.length() > 0) {
1,005✔
183
      passwd = generateRandomPassword(cs, length);
2,010✔
184
    } else {
185
      emit critical(
×
186
          tr("No characters chosen"),
×
187
          tr("Can't generate password, there are no characters to choose from "
×
188
             "set in the configuration!"));
189
    }
190
  }
191
  return passwd;
192
}
193

194
/**
195
 * @brief Pass::gpgSupportsEd25519 check if GPG supports ed25519 (ECC)
196
 * GPG 2.1+ supports ed25519 which is much faster for key generation
197
 * @return true if ed25519 is supported
198
 */
199
bool Pass::gpgSupportsEd25519() {
2✔
200
  QString out, err;
2✔
201
  if (Executor::executeBlocking(QtPassSettings::getGpgExecutable(),
8✔
202
                                {"--version"}, &out, &err) != 0) {
203
    return false;
204
  }
205
  QRegularExpression versionRegex(R"(gpg \(GnuPG\) (\d+)\.(\d+))");
×
206
  QRegularExpressionMatch match = versionRegex.match(out);
×
207
  if (!match.hasMatch()) {
×
208
    return false;
209
  }
210
  int major = match.captured(1).toInt();
×
211
  int minor = match.captured(2).toInt();
×
212
  return major > 2 || (major == 2 && minor >= 1);
×
213
}
2✔
214

215
/**
216
 * @brief Pass::getDefaultKeyTemplate return default key generation template
217
 * Uses ed25519 if supported, otherwise falls back to RSA
218
 * @return GPG batch template string
219
 */
220
QString Pass::getDefaultKeyTemplate() {
1✔
221
  if (gpgSupportsEd25519()) {
1✔
222
    return QStringLiteral("%echo Generating a default key\n"
×
223
                          "Key-Type: EdDSA\n"
224
                          "Key-Curve: Ed25519\n"
225
                          "Subkey-Type: ECDH\n"
226
                          "Subkey-Curve: Curve25519\n"
227
                          "Name-Real: \n"
228
                          "Name-Comment: QtPass\n"
229
                          "Name-Email: \n"
230
                          "Expire-Date: 0\n"
231
                          "%no-protection\n"
232
                          "%commit\n"
233
                          "%echo done");
234
  }
235
  return QStringLiteral("%echo Generating a default key\n"
1✔
236
                        "Key-Type: RSA\n"
237
                        "Subkey-Type: RSA\n"
238
                        "Name-Real: \n"
239
                        "Name-Comment: QtPass\n"
240
                        "Name-Email: \n"
241
                        "Expire-Date: 0\n"
242
                        "%no-protection\n"
243
                        "%commit\n"
244
                        "%echo done");
245
}
246

247
namespace {
248
auto resolveWslGpgconfPath(const QString &lastPart) -> QString {
3✔
249
  int lastSep = lastPart.lastIndexOf('/');
3✔
250
  if (lastSep < 0) {
3✔
251
    lastSep = lastPart.lastIndexOf('\\');
2✔
252
  }
253
  if (lastSep >= 0) {
2✔
254
    return lastPart.left(lastSep + 1) + "gpgconf";
2✔
255
  }
256
  return QStringLiteral("gpgconf");
2✔
257
}
258

259
/**
260
 * @brief Finds the path to the gpgconf executable in the same directory as the
261
 * given GPG path.
262
 * @example
263
 * QString result = findGpgconfInGpgDir(gpgPath);
264
 * std::cout << result.toStdString() << std::endl; // Expected output: path to
265
 * gpgconf or empty string
266
 *
267
 * @param gpgPath - Absolute path to a GPG executable or related file used to
268
 * locate gpgconf.
269
 * @return QString - The full path to gpgconf if found and executable; otherwise
270
 * an empty QString.
271
 */
272
QString findGpgconfInGpgDir(const QString &gpgPath) {
1✔
273
  QFileInfo gpgInfo(gpgPath);
1✔
274
  if (!gpgInfo.isAbsolute()) {
1✔
275
    return QString();
276
  }
277

278
  QDir dir(gpgInfo.absolutePath());
1✔
279

280
#ifdef Q_OS_WIN
281
  QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
282
  if (candidateExe.isExecutable()) {
283
    return candidateExe.filePath();
284
  }
285
#endif
286

287
  QFileInfo candidate(dir.filePath("gpgconf"));
1✔
288
  if (candidate.isExecutable()) {
1✔
289
    return candidate.filePath();
×
290
  }
291
  return QString();
292
}
1✔
293

294
// Compatibility shim for Qt < 5.15 where QProcess::splitCommand is not
295
// available. Keep this fallback while supporting pre-5.15 builds; remove once
296
// the project's minimum supported Qt version is raised to 5.15 or newer.
297
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
298
/**
299
 * @brief Splits a command string into arguments while respecting quotes and
300
 * escape characters.
301
 * @example
302
 * QStringList result = splitCommandCompat("cmd \"arg one\" 'arg two'
303
 * escaped\\ space");
304
 * // Expected output: ["cmd", "arg one", "arg two", "escaped space"]
305
 *
306
 * @param command - The input command string to split into individual arguments.
307
 * @return QStringList - A list of parsed command arguments.
308
 */
309
QStringList splitCommandCompat(const QString &command) {
310
  QStringList result;
311
  QString current;
312
  bool inSingleQuote = false;
313
  bool inDoubleQuote = false;
314
  bool escaping = false;
315
  for (QChar ch : command) {
316
    if (escaping) {
317
      current.append(ch);
318
      escaping = false;
319
      continue;
320
    }
321
    if (ch == '\\') {
322
      escaping = true;
323
      continue;
324
    }
325
    if (ch == '\'' && !inDoubleQuote) {
326
      inSingleQuote = !inSingleQuote;
327
      continue;
328
    }
329
    if (ch == '"' && !inSingleQuote) {
330
      inDoubleQuote = !inDoubleQuote;
331
      continue;
332
    }
333
    if (ch.isSpace() && !inSingleQuote && !inDoubleQuote) {
334
      if (!current.isEmpty()) {
335
        result.append(current);
336
        current.clear();
337
      }
338
      continue;
339
    }
340
    current.append(ch);
341
  }
342
  if (escaping) {
343
    current.append('\\');
344
  }
345
  if (!current.isEmpty()) {
346
    result.append(current);
347
  }
348
  return result;
349
}
350
#endif
351

352
} // namespace
353

354
/**
355
 * @brief Resolves the appropriate gpgconf command from a given GPG executable
356
 * path or command string.
357
 * @example
358
 * ResolvedGpgconfCommand result = Pass::resolveGpgconfCommand("wsl.exe
359
 * /usr/bin/gpg"); std::cout << result.first.toStdString() << std::endl; //
360
 * Expected output sample
361
 *
362
 * @param const QString &gpgPath - Path or command string pointing to the GPG
363
 * executable.
364
 * @return ResolvedGpgconfCommand - A pair containing the resolved gpgconf
365
 * command and its arguments.
366
 */
367
auto Pass::resolveGpgconfCommand(const QString &gpgPath)
8✔
368
    -> ResolvedGpgconfCommand {
369
  if (gpgPath.trimmed().isEmpty()) {
8✔
370
    return {"gpgconf", {}};
371
  }
372

373
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
374
  QStringList parts = QProcess::splitCommand(gpgPath);
7✔
375
#else
376
  QStringList parts = splitCommandCompat(gpgPath);
377
#endif
378

379
  if (parts.isEmpty()) {
7✔
380
    return {"gpgconf", {}};
381
  }
382

383
  const QString first = parts.first();
384
  if (first.compare("wsl", Qt::CaseInsensitive) == 0 ||
16✔
385
      first.compare("wsl.exe", Qt::CaseInsensitive) == 0) {
9✔
386
    if (parts.size() >= 2 && parts.at(1).startsWith("sh")) {
9✔
387
      return {"gpgconf", {}};
388
    }
389
    if (parts.size() >= 2 &&
4✔
390
        QFileInfo(parts.last()).fileName().startsWith("gpg")) {
10✔
391
      QString wslGpgconf = resolveWslGpgconfPath(parts.last());
3✔
392
      parts.removeLast();
3✔
393
      parts.append(wslGpgconf);
394
      return {parts.first(), parts.mid(1)};
395
    }
396
    return {"gpgconf", {}};
397
  }
398

399
  if (!first.contains('/') && !first.contains('\\')) {
2✔
400
    return {"gpgconf", {}};
401
  }
402

403
  QString gpgconfPath = findGpgconfInGpgDir(first);
1✔
404
  if (!gpgconfPath.isEmpty()) {
1✔
405
    return {gpgconfPath, {}};
×
406
  }
407

408
  return {"gpgconf", {}};
409
}
8✔
410

411
/**
412
 * @brief Pass::GenerateGPGKeys internal gpg keypair generator . .
413
 * @param batch GnuPG style configuration string
414
 */
415
void Pass::GenerateGPGKeys(QString batch) {
×
416
  // Kill any stale GPG agents that might be holding locks on the key database
417
  // This helps avoid "database locked" timeouts during key generation
418
  QString gpgPath = QtPassSettings::getGpgExecutable();
×
419
  if (!gpgPath.isEmpty()) {
×
420
    ResolvedGpgconfCommand resolvedGpgconf = resolveGpgconfCommand(gpgPath);
×
421
    QStringList killArgs = resolvedGpgconf.arguments;
422
    killArgs << "--kill";
×
423
    killArgs << "gpg-agent";
×
424
    // Use same environment as key generation to target correct gpg-agent
425
    Executor::executeBlocking(env, resolvedGpgconf.program, killArgs);
×
426
  }
427

428
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
×
429
                 std::move(batch));
430
}
×
431

432
/**
433
 * @brief Pass::listKeys list users
434
 * @param keystrings
435
 * @param secret list private keys
436
 * @return QList<UserInfo> users
437
 */
438
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
×
439
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
×
440
  args.append(secret ? "--list-secret-keys" : "--list-keys");
×
441

442
  for (const QString &keystring : AS_CONST(keystrings)) {
×
443
    if (!keystring.isEmpty()) {
×
444
      args.append(keystring);
445
    }
446
  }
447
  QString p_out;
×
448
  if (Executor::executeBlocking(QtPassSettings::getGpgExecutable(), args,
×
449
                                &p_out) != 0) {
450
    return QList<UserInfo>();
×
451
  }
452
  return parseGpgColonOutput(p_out, secret);
×
453
}
×
454

455
/**
456
 * @brief Pass::listKeys list users
457
 * @param keystring
458
 * @param secret list private keys
459
 * @return QList<UserInfo> users
460
 */
461
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
×
462
  return listKeys(QStringList(keystring), secret);
×
463
}
464

465
/**
466
 * @brief Maps GPG stderr (which may include --status-fd 2 tokens) to a
467
 * user-friendly encryption error string.
468
 *
469
 * Checked in order: machine-readable [GNUPG:] status tokens first (locale-
470
 * independent), then case-insensitive substring fallbacks for GPG builds that
471
 * don't emit status tokens.
472
 *
473
 * @param err Raw stderr from GPG
474
 * @return Translated human-readable error, or empty string if not recognised
475
 */
476
namespace {
477

478
auto containsAny(const QString &str, const QStringList &patterns) -> bool {
31✔
479
  for (const QString &p : patterns) {
82✔
480
    if (str.contains(p)) {
58✔
481
      return true;
482
    }
483
  }
484
  return false;
485
}
486

487
/**
488
 * @brief Checks if str contains any of the patterns (case-insensitive).
489
 * @param str String to search in (will be lowercased once).
490
 * @param patterns List of patterns to search for (must be lowercase; caller
491
 * should convert patterns to lowercase before calling).
492
 * @return true if any pattern is found.
493
 */
494
auto containsAnyCaseInsensitive(const QString &str, const QStringList &patterns)
13✔
495
    -> bool {
496
  const QString lower = str.toLower();
497
  for (const QString &p : patterns) {
32✔
498
    if (lower.contains(p)) {
23✔
499
      return true;
500
    }
501
  }
502
  return false;
503
}
504

505
} // namespace
506

507
auto gpgErrorMessage(const QString &err) -> QString {
13✔
508
  // Machine-readable status tokens added by --status-fd 2
509
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYEXPIRED"),
65✔
510
                        QStringLiteral("[GNUPG:] INV_RECP 5 ")}))
13✔
511
    return QCoreApplication::translate(
512
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
513
                "replace it.");
3✔
514
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYREVOKED"),
50✔
515
                        QStringLiteral("[GNUPG:] INV_RECP 4 ")}))
10✔
516
    return QCoreApplication::translate(
517
        "Pass", "Encryption failed: GPG key has been revoked.");
2✔
518
  if (containsAny(err, {QStringLiteral("[GNUPG:] NO_PUBKEY"),
40✔
519
                        QStringLiteral("[GNUPG:] INV_RECP")}))
8✔
520
    return QCoreApplication::translate(
521
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
522
                "Check that the key ID in .gpg-id is correct and imported.");
2✔
523
  if (err.contains(QStringLiteral("[GNUPG:] FAILURE")))
6✔
524
    return QCoreApplication::translate(
525
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1✔
526

527
  // Locale-dependent fallbacks
528
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has expired"),
20✔
529
                                       QLatin1String("key expired")}))
530
    return QCoreApplication::translate(
531
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
532
                "replace it.");
1✔
533
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has been revoked"),
16✔
534
                                       QLatin1String("revoked")}))
535
    return QCoreApplication::translate(
536
        "Pass", "Encryption failed: GPG key has been revoked.");
1✔
537
  if (containsAnyCaseInsensitive(err, {QLatin1String("no public key"),
15✔
538
                                       QLatin1String("unusable public key"),
539
                                       QLatin1String("no secret key")}))
540
    return QCoreApplication::translate(
541
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
542
                "Check that the key ID in .gpg-id is correct and imported.");
2✔
543
  if (containsAnyCaseInsensitive(err, {QLatin1String("encryption failed")}))
3✔
544
    return QCoreApplication::translate(
545
        "Pass", "Encryption failed. Check that your GPG key is valid.");
×
546

547
  return {};
548
}
×
549

550
namespace {
551
auto isGrepHeaderLine(const QString &rawLine, const QString &trimmedLine)
45✔
552
    -> bool {
553
  // ANSI-colored header starts with the blue escape; plain-text fallback:
554
  // a non-indented line ending with ':' (pass grep format without color)
555
  return rawLine.startsWith(QStringLiteral("\x1B[94m")) ||
123✔
556
         (!rawLine.startsWith(' ') && !rawLine.startsWith('\t') &&
91✔
557
          trimmedLine.endsWith(':'));
119✔
558
}
559
} // namespace
560

561
/**
562
 * @brief Parses 'pass grep' raw output into (entry, matches) pairs.
563
 *
564
 * pass grep emits ANSI blue color (\x1B[94m) at the start of each entry
565
 * header line. This is checked before stripping ANSI so headers are detected
566
 * reliably regardless of locale.
567
 */
568
auto parseGrepOutput(const QString &rawOut)
12✔
569
    -> QList<QPair<QString, QStringList>> {
570
  static const QRegularExpression ansi(
571
      QStringLiteral(R"(\x1B\[[0-9;]*[a-zA-Z])"));
13✔
572
  QList<QPair<QString, QStringList>> results;
12✔
573
  QString currentEntry;
12✔
574
  QStringList currentMatches;
12✔
575
  for (const QString &rawLine : rawOut.split('\n')) {
69✔
576
    QString line = rawLine;
577
    line.remove('\r');
45✔
578
    line.remove(ansi);
45✔
579
    line = line.trimmed();
45✔
580
    const bool isHeader = isGrepHeaderLine(rawLine, line);
45✔
581
    if (isHeader) {
45✔
582
      if (!currentEntry.isEmpty() && !currentMatches.isEmpty())
14✔
583
        results.append({currentEntry, currentMatches});
3✔
584
      currentEntry = line.endsWith(':') ? line.chopped(1) : line;
14✔
585
      currentMatches.clear();
14✔
586
    } else if (!currentEntry.isEmpty()) {
31✔
587
      if (!line.isEmpty())
29✔
588
        currentMatches << line;
589
    }
590
  }
591
  if (!currentEntry.isEmpty() && !currentMatches.isEmpty())
12✔
592
    results.append({currentEntry, currentMatches});
11✔
593
  return results;
12✔
594
}
595

596
/**
597
 * @brief Pass::processFinished reemits specific signal based on what process
598
 * has finished
599
 * @param id    id of Pass process that was scheduled and finished
600
 * @param exitCode  return code of a process
601
 * @param out   output generated by process(if capturing was requested, empty
602
 *              otherwise)
603
 * @param err   error output generated by process(if capturing was requested,
604
 *              or error occurred)
605
 */
606
void Pass::finished(int id, int exitCode, const QString &out,
18✔
607
                    const QString &err) {
608
  auto pid = static_cast<PROCESS>(id);
18✔
609

610
  if (exitCode != 0) {
18✔
611
    handleProcessError(pid, exitCode, out, err);
2✔
612
    return;
2✔
613
  }
614

615
  emitProcessFinishedSignal(pid, out, err);
16✔
616
}
617

618
void Pass::handleProcessError(PROCESS pid, int exitCode, const QString &out,
2✔
619
                              const QString &err) {
620
  if (pid == PASS_GREP) {
2✔
621
    handleGrepError(exitCode, err);
2✔
622
    return;
2✔
623
  }
624

625
  if (pid == PASS_INSERT) {
×
626
    const QString friendly = gpgErrorMessage(err);
×
627
    if (!friendly.isEmpty()) {
×
628
      emit processErrorExit(exitCode, formatInsertError(friendly, err));
×
629
      return;
630
    }
631
  }
632

633
  emit processErrorExit(exitCode, err);
×
634
}
635

636
void Pass::handleGrepError(int exitCode, const QString &err) {
2✔
637
  if (exitCode == 1) {
2✔
638
    emit finishedGrep({});
2✔
639
  } else {
640
    emit processErrorExit(exitCode, err);
1✔
641
    emit finishedGrep({});
2✔
642
  }
643
}
2✔
644

645
auto Pass::formatInsertError(const QString &friendly, const QString &err)
×
646
    -> QString {
647
  QStringList humanLines;
×
648
  for (const QString &line : err.split('\n')) {
×
649
    QString cleanedLine = line;
650
    cleanedLine.remove('\r');
×
651
    if (!cleanedLine.startsWith(QLatin1String("[GNUPG:]")))
×
652
      humanLines.append(cleanedLine);
653
  }
654
  const QString humanErr = humanLines.join('\n').trimmed();
×
655
  return humanErr.isEmpty() ? friendly : friendly + "\n\n" + humanErr;
×
656
}
657

658
void Pass::emitProcessFinishedSignal(PROCESS pid, const QString &out,
16✔
659
                                     const QString &err) {
660
  switch (pid) {
16✔
NEW
661
  case GIT_INIT:
×
NEW
662
    emit finishedGitInit(out, err);
×
NEW
663
    break;
×
NEW
664
  case GIT_PULL:
×
NEW
665
    emit finishedGitPull(out, err);
×
NEW
666
    break;
×
NEW
667
  case GIT_PUSH:
×
668
    emit finishedGitPush(out, err);
×
669
    break;
×
670
  case PASS_SHOW:
5✔
671
    emit finishedShow(out);
5✔
672
    break;
5✔
673
  case PASS_OTP_GENERATE:
×
674
    emit finishedOtpGenerate(out);
×
675
    break;
×
676
  case PASS_INSERT:
10✔
677
    emit finishedInsert(out, err);
10✔
678
    break;
10✔
679
  case PASS_REMOVE:
×
680
    emit finishedRemove(out, err);
×
681
    break;
×
682
  case PASS_INIT:
×
683
    emit finishedInit(out, err);
×
684
    break;
×
685
  case PASS_MOVE:
×
686
    emit finishedMove(out, err);
×
687
    break;
×
688
  case PASS_COPY:
×
689
    emit finishedCopy(out, err);
×
690
    break;
×
691
  case GPG_GENKEYS:
×
692
    emit finishedGenerateGPGKeys(out, err);
×
693
    break;
×
694
  case PASS_GREP:
1✔
695
    emit finishedGrep(parseGrepOutput(out));
1✔
696
    break;
1✔
697
  default:
698
#ifdef QT_DEBUG
699
    dbg() << "Unhandled process type" << pid;
700
#endif
701
    break;
702
  }
703
}
16✔
704

705
/**
706
 * @brief Pass::setEnvVar set or remove a single environment variable.
707
 * @param key Variable name including trailing '=' (e.g. "FOO=").
708
 * @param value Value to set; pass an empty string to remove the variable.
709
 */
710
// key must include the trailing '=' (e.g. "FOO="); env.filter() does substring
711
// matching so the '=' anchors the lookup to avoid collisions with longer names.
712
void Pass::setEnvVar(const QString &key, const QString &value) {
70✔
713
  const bool hasEq = key.endsWith('=');
70✔
714
  Q_ASSERT_X(hasEq, "Pass::setEnvVar",
715
             "called with malformed key (missing '=')");
716
  if (!hasEq) {
70✔
NEW
717
    qWarning() << "Pass::setEnvVar called with malformed key (missing '='):"
×
NEW
718
               << key;
×
719
    return;
×
720
  }
721
  const QStringList existing = env.filter(key);
70✔
722
  for (const QString &entry : existing)
75✔
723
    env.removeAll(entry);
724
  if (!value.isEmpty())
70✔
725
    env.append(key + value);
104✔
726
}
727

728
/**
729
 * @brief Pass::updateEnv update the execution environment (used when
730
 * switching profiles)
731
 */
732
void Pass::updateEnv() {
16✔
733
  setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY="),
32✔
734
            QtPassSettings::getPassSigningKey());
32✔
735
  setEnvVar(QStringLiteral("PASSWORD_STORE_DIR="),
32✔
736
            QtPassSettings::getPassStore());
32✔
737

738
  PasswordConfiguration passConfig = QtPassSettings::getPasswordConfiguration();
16✔
739
  setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH="),
32✔
740
            QString::number(passConfig.length));
16✔
741

742
  setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET="),
32✔
743
            effectiveCharset(passConfig));
16✔
744

745
  exec.setEnvironment(env);
16✔
746
}
16✔
747

748
/**
749
 * @brief Pass::getGpgIdPath return gpgid file path for some file (folder).
750
 * @param for_file which file (folder) would you like the gpgid file path for.
751
 * @return path to the gpgid file.
752
 */
753
auto Pass::getGpgIdPath(const QString &for_file) -> QString {
32✔
754
  QString passStore =
755
      QDir::fromNativeSeparators(QtPassSettings::getPassStore());
64✔
756
  QString normalizedFile = QDir::fromNativeSeparators(for_file);
32✔
757
  QString fullPath = normalizedFile.startsWith(passStore)
32✔
758
                         ? normalizedFile
32✔
759
                         : passStore + "/" + normalizedFile;
27✔
760
  QDir gpgIdDir(QFileInfo(fullPath).absoluteDir());
32✔
761
  bool found = false;
762
  while (gpgIdDir.exists() && gpgIdDir.absolutePath().startsWith(passStore)) {
81✔
763
    if (QFile(gpgIdDir.absoluteFilePath(".gpg-id")).exists()) {
26✔
764
      found = true;
765
      break;
766
    }
767
    if (!gpgIdDir.cdUp()) {
12✔
768
      break;
769
    }
770
  }
771
  QString gpgIdPath(
772
      found ? gpgIdDir.absoluteFilePath(".gpg-id")
32✔
773
            : QDir(QtPassSettings::getPassStore()).filePath(".gpg-id"));
125✔
774

775
  return gpgIdPath;
32✔
776
}
32✔
777

778
/**
779
 * @brief Pass::getRecipientList return list of gpg-id's to encrypt for
780
 * @param for_file which file (folder) would you like recipients for
781
 * @return recipients gpg-id contents
782
 */
783
auto Pass::getRecipientList(const QString &for_file) -> QStringList {
17✔
784
  QFile gpgId(getGpgIdPath(for_file));
17✔
785
  if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text)) {
17✔
786
    return {};
×
787
  }
788
  QStringList recipients;
17✔
789
  while (!gpgId.atEnd()) {
42✔
790
    QString recipient(gpgId.readLine());
50✔
791
    recipient = recipient.split("#")[0].trimmed();
50✔
792
    if (!recipient.isEmpty() && Util::isValidKeyId(recipient)) {
25✔
793
      recipients += recipient;
794
    }
795
  }
796
  return recipients;
797
}
17✔
798

799
/**
800
 * @brief Pass::getRecipientString formatted string for use with GPG
801
 * @param for_file which file (folder) would you like recipients for
802
 * @param separator formating separator eg: " -r "
803
 * @param count
804
 * @return recipient string
805
 */
806
auto Pass::getRecipientString(const QString &for_file, const QString &separator,
2✔
807
                              int *count) -> QStringList {
808
  Q_UNUSED(separator)
809
  QStringList recipients = Pass::getRecipientList(for_file);
2✔
810
  if (count) {
2✔
811
    *count = recipients.size();
1✔
812
  }
813
  return recipients;
2✔
814
}
815

816
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
817
 */
818

819
/**
820
 * @brief Generates a random number bounded by the given value.
821
 * @param bound Upper bound (exclusive)
822
 * @return Random number in range [0, bound)
823
 */
824
auto Pass::boundedRandom(quint32 bound) -> quint32 {
1,224✔
825
  if (bound < 2) {
1,224✔
826
    return 0;
827
  }
828

829
  quint32 randval;
830
  // Rejection-sampling threshold to avoid modulo bias.
831
  // This follows the well-known "arc4random_uniform"-style approach:
832
  // reject values in the low range [0, min), where
833
  //   min = 2^32 % bound
834
  // so that the remaining range size is an exact multiple of `bound`.
835
  //
836
  // In quint32 arithmetic, (1 + ~bound) wraps to (2^32 - bound), therefore
837
  //   (1 + ~bound) % bound == 2^32 % bound.
838
  const quint32 rejectionThreshold = (1 + ~bound) % bound;
1,224✔
839

840
  do {
841
    randval = QRandomGenerator::system()->generate();
842
  } while (randval < rejectionThreshold);
1,224✔
843

844
  return randval % bound;
1,224✔
845
}
846

847
/**
848
 * @brief Generates a random password from the given charset.
849
 * @param charset Characters to use in the password
850
 * @param length Desired password length
851
 * @return Generated password string
852
 */
853
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,005✔
854
    -> QString {
855
  if (charset.isEmpty() || length == 0U) {
1,005✔
856
    return {};
857
  }
858
  QString out;
1,005✔
859
  for (unsigned int i = 0; i < length; ++i) {
2,229✔
860
    out.append(charset.at(static_cast<int>(
1,224✔
861
        boundedRandom(static_cast<quint32>(charset.length())))));
1,224✔
862
  }
863
  return out;
864
}
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