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

IJHack / QtPass / 24592081376

18 Apr 2026 12:08AM UTC coverage: 21.266% (-0.6%) from 21.908%
24592081376

Pull #1037

github

web-flow
Merge 5afaee654 into 79d758a1a
Pull Request #1037: feat: implement pass grep content search (#109)

0 of 135 new or added lines in 5 files covered. (0.0%)

208 existing lines in 5 files now uncovered.

1199 of 5638 relevant lines covered (21.27%)

8.33 hits per line

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

50.0
/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()) {
16✔
37
  connect(&exec,
16✔
38
          static_cast<void (Executor::*)(int, int, const QString &,
39
                                         const QString &)>(&Executor::finished),
40
          this, &Pass::finished);
16✔
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);
16✔
48
  // Merge our vars into WSLENV rather than blindly appending a duplicate entry
49
  const QStringList wslenvVars = {
50
      QStringLiteral("PASSWORD_STORE_DIR/p"),
32✔
51
      QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH/w"),
16✔
52
      QStringLiteral("PASSWORD_STORE_CHARACTER_SET/w")};
80✔
53
  const QString wslenvPrefix = QStringLiteral("WSLENV=");
16✔
54
  auto it = std::find_if(env.begin(), env.end(), [&](const QString &s) {
32✔
55
    return s.startsWith(wslenvPrefix);
2,048✔
56
  });
57
  if (it == env.end()) {
16✔
58
    env.append(wslenvPrefix + wslenvVars.join(':'));
32✔
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
}
16✔
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
auto gpgErrorMessage(const QString &err) -> QString {
13✔
452
  // Machine-readable status tokens added by --status-fd 2
453
  if (err.contains(QStringLiteral("[GNUPG:] KEYEXPIRED")) ||
37✔
454
      err.contains(QStringLiteral("[GNUPG:] INV_RECP 5 ")))
24✔
455
    return QCoreApplication::translate("Pass",
456
                                       "Encryption failed: GPG key has expired."
457
                                       " Please renew or replace it.");
3✔
458
  if (err.contains(QStringLiteral("[GNUPG:] KEYREVOKED")) ||
29✔
459
      err.contains(QStringLiteral("[GNUPG:] INV_RECP 4 ")))
19✔
460
    return QCoreApplication::translate(
461
        "Pass", "Encryption failed: GPG key has been revoked.");
2✔
462
  if (err.contains(QStringLiteral("[GNUPG:] NO_PUBKEY")) ||
23✔
463
      err.contains(QStringLiteral("[GNUPG:] INV_RECP")))
15✔
464
    return QCoreApplication::translate(
465
        "Pass", "Encryption failed: recipient GPG key not found or invalid."
466
                " Check that the key ID in .gpg-id is correct and imported.");
2✔
467
  if (err.contains(QStringLiteral("[GNUPG:] FAILURE")))
6✔
468
    return QCoreApplication::translate(
469
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1✔
470

471
  // Locale-dependent fallbacks for GPG versions / configurations that don't
472
  // emit status tokens
473
  const QString lower = err.toLower();
474
  if (lower.contains(QLatin1String("key has expired")) ||
5✔
475
      lower.contains(QLatin1String("key expired")))
4✔
476
    return QCoreApplication::translate("Pass",
477
                                       "Encryption failed: GPG key has expired."
478
                                       " Please renew or replace it.");
1✔
479
  if (lower.contains(QLatin1String("key has been revoked")) ||
4✔
480
      lower.contains(QLatin1String("revoked")))
3✔
481
    return QCoreApplication::translate(
482
        "Pass", "Encryption failed: GPG key has been revoked.");
1✔
483
  if (lower.contains(QLatin1String("no public key")) ||
5✔
484
      lower.contains(QLatin1String("unusable public key")) ||
5✔
485
      lower.contains(QLatin1String("no secret key")))
1✔
486
    return QCoreApplication::translate(
487
        "Pass", "Encryption failed: recipient GPG key not found or invalid."
488
                " Check that the key ID in .gpg-id is correct and imported.");
2✔
489
  if (lower.contains(QLatin1String("encryption failed")))
1✔
490
    return QCoreApplication::translate(
491
        "Pass", "Encryption failed. Check that your GPG key is valid.");
×
492

493
  return {};
494
}
495

496
/**
497
 * @brief Parses 'pass grep' raw output into (entry, matches) pairs.
498
 *
499
 * pass grep emits ANSI blue color (\x1B[94m) at the start of each entry
500
 * header line. This is checked before stripping ANSI so headers are detected
501
 * reliably regardless of locale.
502
 */
NEW
503
static auto parseGrepOutput(const QString &rawOut)
×
504
    -> QList<QPair<QString, QStringList>> {
505
  static const QRegularExpression ansi(
NEW
506
      QStringLiteral(R"(\x1B\[[0-9;]*[a-zA-Z])"));
×
NEW
507
  QList<QPair<QString, QStringList>> results;
×
NEW
508
  QString currentEntry;
×
NEW
509
  QStringList currentMatches;
×
NEW
510
  for (const QString &rawLine : rawOut.split('\n')) {
×
NEW
511
    bool isHeader = rawLine.contains(QStringLiteral("\x1B[94m"));
×
512
    QString line = rawLine;
NEW
513
    line.remove('\r');
×
NEW
514
    line.remove(ansi);
×
NEW
515
    line = line.trimmed();
×
NEW
516
    if (isHeader) {
×
NEW
517
      if (!currentEntry.isEmpty() && !currentMatches.isEmpty())
×
NEW
518
        results.append({currentEntry, currentMatches});
×
NEW
519
      currentEntry = line.endsWith(':') ? line.chopped(1) : line;
×
NEW
520
      currentMatches.clear();
×
NEW
521
    } else if (!currentEntry.isEmpty()) {
×
NEW
522
      if (!line.isEmpty())
×
523
        currentMatches << line;
524
    }
525
  }
NEW
526
  if (!currentEntry.isEmpty() && !currentMatches.isEmpty())
×
NEW
527
    results.append({currentEntry, currentMatches});
×
NEW
528
  return results;
×
529
}
530

531
/**
532
 * @brief Pass::processFinished reemits specific signal based on what process
533
 * has finished
534
 * @param id    id of Pass process that was scheduled and finished
535
 * @param exitCode  return code of a process
536
 * @param out   output generated by process(if capturing was requested, empty
537
 *              otherwise)
538
 * @param err   error output generated by process(if capturing was requested,
539
 *              or error occurred)
540
 */
541
void Pass::finished(int id, int exitCode, const QString &out,
×
542
                    const QString &err) {
UNCOV
543
  auto pid = static_cast<PROCESS>(id);
×
544
  if (exitCode != 0) {
×
NEW
545
    if (pid == PASS_GREP) {
×
546
      // exit code 1 means no matches (standard grep behaviour); treat as empty
547
      // result set rather than an error
NEW
548
      if (exitCode == 1)
×
NEW
549
        emit finishedGrep({});
×
550
      else
NEW
551
        emit processErrorExit(exitCode, err);
×
NEW
552
      return;
×
553
    }
554
    if (pid == PASS_INSERT) {
×
555
      const QString friendly = gpgErrorMessage(err);
×
556
      if (!friendly.isEmpty()) {
×
557
        // Strip machine-readable [GNUPG:] status lines before showing raw
558
        // output; they are only useful for detection, not for display.
559
        QStringList humanLines;
×
560
        for (QString line : err.split('\n')) {
×
561
          line.remove('\r');
×
562
          if (!line.startsWith(QLatin1String("[GNUPG:]")))
×
563
            humanLines.append(line);
564
        }
565
        const QString humanErr = humanLines.join('\n').trimmed();
×
566
        emit processErrorExit(exitCode, humanErr.isEmpty()
×
567
                                            ? friendly
×
568
                                            : friendly + "\n\n" + humanErr);
×
569
        return;
570
      }
571
    }
572
    emit processErrorExit(exitCode, err);
×
573
    return;
×
574
  }
575
  switch (pid) {
×
576
  case GIT_INIT:
×
577
    emit finishedGitInit(out, err);
×
578
    break;
×
579
  case GIT_PULL:
×
580
    emit finishedGitPull(out, err);
×
581
    break;
×
582
  case GIT_PUSH:
×
583
    emit finishedGitPush(out, err);
×
584
    break;
×
585
  case PASS_SHOW:
×
586
    emit finishedShow(out);
×
587
    break;
×
588
  case PASS_OTP_GENERATE:
×
589
    emit finishedOtpGenerate(out);
×
590
    break;
×
591
  case PASS_INSERT:
×
592
    emit finishedInsert(out, err);
×
593
    break;
×
594
  case PASS_REMOVE:
×
595
    emit finishedRemove(out, err);
×
596
    break;
×
597
  case PASS_INIT:
×
598
    emit finishedInit(out, err);
×
599
    break;
×
600
  case PASS_MOVE:
×
601
    emit finishedMove(out, err);
×
602
    break;
×
603
  case PASS_COPY:
×
604
    emit finishedCopy(out, err);
×
605
    break;
×
606
  case GPG_GENKEYS:
×
607
    emit finishedGenerateGPGKeys(out, err);
×
608
    break;
×
NEW
609
  case PASS_GREP:
×
NEW
610
    emit finishedGrep(parseGrepOutput(out));
×
NEW
611
    break;
×
612
  default:
613
#ifdef QT_DEBUG
614
    dbg() << "Unhandled process type" << pid;
615
#endif
616
    break;
617
  }
618
}
619

620
/**
621
 * @brief Pass::updateEnv update the execution environment (used when
622
 * switching profiles)
623
 */
624
// key must include the trailing '=' (e.g. "FOO="); env.filter() does substring
625
// matching so the '=' anchors the lookup to avoid collisions with longer names.
626
void Pass::setEnvVar(const QString &key, const QString &value) {
38✔
627
  Q_ASSERT(key.endsWith('='));
628
  const QStringList existing = env.filter(key);
38✔
629
  for (const QString &entry : std::as_const(existing))
43✔
630
    env.removeAll(entry);
631
  if (!value.isEmpty())
38✔
632
    env.append(key + value);
56✔
633
}
38✔
634

635
void Pass::updateEnv() {
8✔
636
  setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY="),
16✔
637
            QtPassSettings::getPassSigningKey());
16✔
638
  setEnvVar(QStringLiteral("PASSWORD_STORE_DIR="),
16✔
639
            QtPassSettings::getPassStore());
16✔
640

641
  PasswordConfiguration passConfig = QtPassSettings::getPasswordConfiguration();
8✔
642
  setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH="),
16✔
643
            QString::number(passConfig.length));
8✔
644

645
  int sel = passConfig.selected;
8✔
646
  if (sel < 0 || sel >= PasswordConfiguration::CHARSETS_COUNT)
8✔
647
    sel = PasswordConfiguration::ALLCHARS;
648
  QString charset = passConfig.Characters[sel];
649
  if (charset.isEmpty())
8✔
650
    charset = passConfig.Characters[PasswordConfiguration::ALLCHARS];
1✔
651
  setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET="), charset);
16✔
652

653
  exec.setEnvironment(env);
8✔
654
}
8✔
655

656
/**
657
 * @brief Pass::getGpgIdPath return gpgid file path for some file (folder).
658
 * @param for_file which file (folder) would you like the gpgid file path for.
659
 * @return path to the gpgid file.
660
 */
661
auto Pass::getGpgIdPath(const QString &for_file) -> QString {
9✔
662
  QString passStore =
663
      QDir::fromNativeSeparators(QtPassSettings::getPassStore());
18✔
664
  QString normalizedFile = QDir::fromNativeSeparators(for_file);
9✔
665
  QString fullPath = normalizedFile.startsWith(passStore)
9✔
666
                         ? normalizedFile
9✔
667
                         : passStore + "/" + normalizedFile;
7✔
668
  QDir gpgIdDir(QFileInfo(fullPath).absoluteDir());
9✔
669
  bool found = false;
670
  while (gpgIdDir.exists() && gpgIdDir.absolutePath().startsWith(passStore)) {
11✔
671
    if (QFile(gpgIdDir.absoluteFilePath(".gpg-id")).exists()) {
2✔
672
      found = true;
673
      break;
674
    }
675
    if (!gpgIdDir.cdUp()) {
×
676
      break;
677
    }
678
  }
679
  QString gpgIdPath(
680
      found ? gpgIdDir.absoluteFilePath(".gpg-id")
9✔
681
            : QDir(QtPassSettings::getPassStore()).filePath(".gpg-id"));
33✔
682

683
  return gpgIdPath;
9✔
684
}
9✔
685

686
/**
687
 * @brief Pass::getRecipientList return list of gpg-id's to encrypt for
688
 * @param for_file which file (folder) would you like recipients for
689
 * @return recipients gpg-id contents
690
 */
691
auto Pass::getRecipientList(const QString &for_file) -> QStringList {
6✔
692
  QFile gpgId(getGpgIdPath(for_file));
6✔
693
  if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text)) {
6✔
694
    return {};
×
695
  }
696
  QStringList recipients;
6✔
697
  while (!gpgId.atEnd()) {
20✔
698
    QString recipient(gpgId.readLine());
28✔
699
    recipient = recipient.split("#")[0].trimmed();
28✔
700
    if (!recipient.isEmpty() && Util::isValidKeyId(recipient)) {
14✔
701
      recipients += recipient;
702
    }
703
  }
704
  return recipients;
705
}
6✔
706

707
/**
708
 * @brief Pass::getRecipientString formatted string for use with GPG
709
 * @param for_file which file (folder) would you like recipients for
710
 * @param separator formating separator eg: " -r "
711
 * @param count
712
 * @return recipient string
713
 */
714
auto Pass::getRecipientString(const QString &for_file, const QString &separator,
2✔
715
                              int *count) -> QStringList {
716
  Q_UNUSED(separator)
717
  QStringList recipients = Pass::getRecipientList(for_file);
2✔
718
  if (count) {
2✔
719
    *count = recipients.size();
1✔
720
  }
721
  return recipients;
2✔
722
}
723

724
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
725
 */
726

727
/**
728
 * @brief Generates a random number bounded by the given value.
729
 * @param bound Upper bound (exclusive)
730
 * @return Random number in range [0, bound)
731
 */
732
auto Pass::boundedRandom(quint32 bound) -> quint32 {
1,224✔
733
  if (bound < 2) {
1,224✔
734
    return 0;
735
  }
736

737
  quint32 randval;
738
  // Rejection-sampling threshold to avoid modulo bias:
739
  // In quint32 arithmetic, (1 + ~bound) wraps to (2^32 - bound), so
740
  // (1 + ~bound) % bound == 2^32 % bound.
741
  // Values randval < max_mod_bound are rejected; accepted values produce a
742
  // uniform distribution when reduced with (randval % bound).
743
  const quint32 max_mod_bound = (1 + ~bound) % bound;
1,224✔
744

745
  do {
746
    randval = QRandomGenerator::system()->generate();
747
  } while (randval < max_mod_bound);
1,224✔
748

749
  return randval % bound;
1,224✔
750
}
751

752
/**
753
 * @brief Generates a random password from the given charset.
754
 * @param charset Characters to use in the password
755
 * @param length Desired password length
756
 * @return Generated password string
757
 */
758
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,006✔
759
    -> QString {
760
  if (charset.isEmpty() || length == 0U) {
1,006✔
761
    return {};
762
  }
763
  QString out;
1,005✔
764
  for (unsigned int i = 0; i < length; ++i) {
2,229✔
765
    out.append(charset.at(static_cast<int>(
1,224✔
766
        boundedRandom(static_cast<quint32>(charset.length())))));
1,224✔
767
  }
768
  return out;
769
}
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