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

IJHack / QtPass / 24102839925

07 Apr 2026 08:28PM UTC coverage: 21.044% (+0.8%) from 20.217%
24102839925

push

github

web-flow
Merge pull request #904 from IJHack/refactor/listkeys-parsing

refactor: reduce complexity in Pass::listKeys()

48 of 51 new or added lines in 2 files covered. (94.12%)

1 existing line in 1 file now uncovered.

1109 of 5270 relevant lines covered (21.04%)

7.8 hits per line

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

45.54
/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 <QDir>
9
#include <QFileInfo>
10
#include <QProcess>
11
#include <QRandomGenerator>
12
#include <QRegularExpression>
13
#include <utility>
14

15
#ifdef QT_DEBUG
16
#include "debughelper.h"
17
#endif
18

19
using Enums::GIT_INIT;
20
using Enums::GIT_PULL;
21
using Enums::GIT_PUSH;
22
using Enums::GPG_GENKEYS;
23
using Enums::PASS_COPY;
24
using Enums::PASS_INIT;
25
using Enums::PASS_INSERT;
26
using Enums::PASS_MOVE;
27
using Enums::PASS_OTP_GENERATE;
28
using Enums::PASS_REMOVE;
29
using Enums::PASS_SHOW;
30

31
/**
32
 * @brief Pass::Pass wrapper for using either pass or the pass imitation
33
 */
34
Pass::Pass() : wrapperRunning(false), env(QProcess::systemEnvironment()) {
11✔
35
  connect(&exec,
11✔
36
          static_cast<void (Executor::*)(int, int, const QString &,
37
                                         const QString &)>(&Executor::finished),
38
          this, &Pass::finished);
11✔
39

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

45
  connect(&exec, &Executor::starting, this, &Pass::startingExecuteWrapper);
11✔
46
  env.append("WSLENV=PASSWORD_STORE_DIR/p");
11✔
47
}
11✔
48

49
/**
50
 * @brief Executes a wrapper command.
51
 * @param id Process ID
52
 * @param app Application to execute
53
 * @param args Arguments
54
 * @param readStdout Whether to read stdout
55
 * @param readStderr Whether to read stderr
56
 */
57
void Pass::executeWrapper(PROCESS id, const QString &app,
×
58
                          const QStringList &args, bool readStdout,
59
                          bool readStderr) {
60
  executeWrapper(id, app, args, QString(), readStdout, readStderr);
×
61
}
×
62

63
void Pass::executeWrapper(PROCESS id, const QString &app,
×
64
                          const QStringList &args, QString input,
65
                          bool readStdout, bool readStderr) {
66
#ifdef QT_DEBUG
67
  dbg() << app << args;
68
#endif
69
  exec.execute(id, QtPassSettings::getPassStore(), app, args, std::move(input),
×
70
               readStdout, readStderr);
71
}
×
72

73
/**
74
 * @brief Initializes the pass wrapper environment.
75
 */
76
void Pass::init() {
1✔
77
#ifdef __APPLE__
78
  // If it exists, add the gpgtools to PATH
79
  if (QFile("/usr/local/MacGPG2/bin").exists())
80
    env.replaceInStrings("PATH=", "PATH=/usr/local/MacGPG2/bin:");
81
  // Add missing /usr/local/bin
82
  if (env.filter("/usr/local/bin").isEmpty())
83
    env.replaceInStrings("PATH=", "PATH=/usr/local/bin:");
84
#endif
85

86
  if (!QtPassSettings::getGpgHome().isEmpty()) {
2✔
87
    QDir absHome(QtPassSettings::getGpgHome());
×
88
    absHome.makeAbsolute();
×
89
    env << "GNUPGHOME=" + absHome.path();
×
90
  }
×
91
}
1✔
92

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

152
/**
153
 * @brief Pass::gpgSupportsEd25519 check if GPG supports ed25519 (ECC)
154
 * GPG 2.1+ supports ed25519 which is much faster for key generation
155
 * @return true if ed25519 is supported
156
 */
157
bool Pass::gpgSupportsEd25519() {
3✔
158
  QString out, err;
3✔
159
  if (Executor::executeBlocking(QtPassSettings::getGpgExecutable(),
12✔
160
                                {"--version"}, &out, &err) != 0) {
161
    return false;
162
  }
163
  QRegularExpression versionRegex(R"(gpg \(GnuPG\) (\d+)\.(\d+))");
×
164
  QRegularExpressionMatch match = versionRegex.match(out);
×
165
  if (!match.hasMatch()) {
×
166
    return false;
167
  }
168
  int major = match.captured(1).toInt();
×
169
  int minor = match.captured(2).toInt();
×
170
  return major > 2 || (major == 2 && minor >= 1);
×
171
}
3✔
172

173
/**
174
 * @brief Pass::getDefaultKeyTemplate return default key generation template
175
 * Uses ed25519 if supported, otherwise falls back to RSA
176
 * @return GPG batch template string
177
 */
178
QString Pass::getDefaultKeyTemplate() {
1✔
179
  if (gpgSupportsEd25519()) {
1✔
180
    return QStringLiteral("%echo Generating a default key\n"
×
181
                          "Key-Type: EdDSA\n"
182
                          "Key-Curve: Ed25519\n"
183
                          "Subkey-Type: ECDH\n"
184
                          "Subkey-Curve: Curve25519\n"
185
                          "Name-Real: \n"
186
                          "Name-Comment: QtPass\n"
187
                          "Name-Email: \n"
188
                          "Expire-Date: 0\n"
189
                          "%no-protection\n"
190
                          "%commit\n"
191
                          "%echo done");
192
  }
193
  return QStringLiteral("%echo Generating a default key\n"
1✔
194
                        "Key-Type: RSA\n"
195
                        "Subkey-Type: RSA\n"
196
                        "Name-Real: \n"
197
                        "Name-Comment: QtPass\n"
198
                        "Name-Email: \n"
199
                        "Expire-Date: 0\n"
200
                        "%no-protection\n"
201
                        "%commit\n"
202
                        "%echo done");
203
}
204

205
namespace {
206
auto resolveWslGpgconfPath(const QString &lastPart) -> QString {
3✔
207
  int lastSep = lastPart.lastIndexOf('/');
3✔
208
  if (lastSep < 0) {
3✔
209
    lastSep = lastPart.lastIndexOf('\\');
2✔
210
  }
211
  if (lastSep >= 0) {
2✔
212
    return lastPart.left(lastSep + 1) + "gpgconf";
2✔
213
  }
214
  return QStringLiteral("gpgconf");
2✔
215
}
216

217
QString findGpgconfInGpgDir(const QString &gpgPath) {
1✔
218
  QFileInfo gpgInfo(gpgPath);
1✔
219
  if (!gpgInfo.isAbsolute()) {
1✔
220
    return QString();
221
  }
222

223
  QDir dir(gpgInfo.absolutePath());
1✔
224

225
#ifdef Q_OS_WIN
226
  QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
227
  if (candidateExe.isExecutable()) {
228
    return candidateExe.filePath();
229
  }
230
#endif
231

232
  QFileInfo candidate(dir.filePath("gpgconf"));
1✔
233
  if (candidate.isExecutable()) {
1✔
234
    return candidate.filePath();
1✔
235
  }
236
  return QString();
237
}
1✔
238
} // namespace
239

240
auto Pass::resolveGpgconfCommand(const QString &gpgPath)
8✔
241
    -> ResolvedGpgconfCommand {
242
  if (gpgPath.trimmed().isEmpty()) {
8✔
243
    return {"gpgconf", {}};
244
  }
245

246
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
247
  QStringList parts = QProcess::splitCommand(gpgPath);
7✔
248
#else
249
  QStringList parts = QStringList{gpgPath};
250
#endif
251

252
  if (parts.isEmpty()) {
7✔
253
    return {"gpgconf", {}};
254
  }
255

256
  const QString first = parts.first();
257
  if (first == "wsl" || first == "wsl.exe") {
9✔
258
    if (parts.size() >= 2 && parts.at(1).startsWith("sh")) {
9✔
259
      return {"gpgconf", {}};
260
    }
261
    if (parts.size() >= 2 &&
4✔
262
        QFileInfo(parts.last()).fileName().startsWith("gpg")) {
10✔
263
      QString wslGpgconf = resolveWslGpgconfPath(parts.last());
3✔
264
      parts.removeLast();
3✔
265
      parts.append(wslGpgconf);
266
      return {parts.first(), parts.mid(1)};
267
    }
268
    return {"gpgconf", {}};
269
  }
270

271
  if (!gpgPath.contains('/') && !gpgPath.contains('\\')) {
2✔
272
    return {"gpgconf", {}};
273
  }
274

275
  QString gpgconfPath = findGpgconfInGpgDir(gpgPath);
1✔
276
  if (!gpgconfPath.isEmpty()) {
1✔
277
    return {gpgconfPath, {}};
1✔
278
  }
279

280
  return {"gpgconf", {}};
281
}
8✔
282

283
/**
284
 * @brief Pass::GenerateGPGKeys internal gpg keypair generator . .
285
 * @param batch GnuPG style configuration string
286
 */
287
void Pass::GenerateGPGKeys(QString batch) {
×
288
  // Kill any stale GPG agents that might be holding locks on the key database
289
  // This helps avoid "database locked" timeouts during key generation
290
  QString gpgPath = QtPassSettings::getGpgExecutable();
×
291
  if (!gpgPath.isEmpty()) {
×
292
    ResolvedGpgconfCommand gpgconf = resolveGpgconfCommand(gpgPath);
×
293
    QStringList killArgs = gpgconf.arguments;
294
    killArgs << "--kill";
×
295
    killArgs << "gpg-agent";
×
296
    // Use same environment as key generation to target correct gpg-agent
297
    Executor::executeBlocking(env, gpgconf.program, killArgs);
×
298
  }
299

300
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
×
301
                 std::move(batch));
302
}
×
303

304
/**
305
 * @brief Pass::listKeys list users
306
 * @param keystrings
307
 * @param secret list private keys
308
 * @return QList<UserInfo> users
309
 */
310
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
×
311
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
×
312
  args.append(secret ? "--list-secret-keys" : "--list-keys");
×
313

314
  for (const QString &keystring : AS_CONST(keystrings)) {
×
315
    if (!keystring.isEmpty()) {
×
316
      args.append(keystring);
317
    }
318
  }
319
  QString p_out;
×
320
  if (Executor::executeBlocking(QtPassSettings::getGpgExecutable(), args,
×
321
                                &p_out) != 0) {
NEW
322
    return QList<UserInfo>();
×
323
  }
NEW
324
  return parseGpgColonOutput(p_out, secret);
×
UNCOV
325
}
×
326

327
/**
328
 * @brief Pass::listKeys list users
329
 * @param keystring
330
 * @param secret list private keys
331
 * @return QList<UserInfo> users
332
 */
333
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
×
334
  return listKeys(QStringList(keystring), secret);
×
335
}
336

337
/**
338
 * @brief Pass::processFinished reemits specific signal based on what process
339
 * has finished
340
 * @param id    id of Pass process that was scheduled and finished
341
 * @param exitCode  return code of a process
342
 * @param out   output generated by process(if capturing was requested, empty
343
 *              otherwise)
344
 * @param err   error output generated by process(if capturing was requested,
345
 *              or error occurred)
346
 */
347
void Pass::finished(int id, int exitCode, const QString &out,
×
348
                    const QString &err) {
349
  auto pid = static_cast<PROCESS>(id);
350
  if (exitCode != 0) {
×
351
    emit processErrorExit(exitCode, err);
×
352
    return;
×
353
  }
354
  switch (pid) {
×
355
  case GIT_INIT:
×
356
    emit finishedGitInit(out, err);
×
357
    break;
×
358
  case GIT_PULL:
×
359
    emit finishedGitPull(out, err);
×
360
    break;
×
361
  case GIT_PUSH:
×
362
    emit finishedGitPush(out, err);
×
363
    break;
×
364
  case PASS_SHOW:
×
365
    emit finishedShow(out);
×
366
    break;
×
367
  case PASS_OTP_GENERATE:
×
368
    emit finishedOtpGenerate(out);
×
369
    break;
×
370
  case PASS_INSERT:
×
371
    emit finishedInsert(out, err);
×
372
    break;
×
373
  case PASS_REMOVE:
×
374
    emit finishedRemove(out, err);
×
375
    break;
×
376
  case PASS_INIT:
×
377
    emit finishedInit(out, err);
×
378
    break;
×
379
  case PASS_MOVE:
×
380
    emit finishedMove(out, err);
×
381
    break;
×
382
  case PASS_COPY:
×
383
    emit finishedCopy(out, err);
×
384
    break;
×
385
  case GPG_GENKEYS:
×
386
    emit finishedGenerateGPGKeys(out, err);
×
387
    break;
×
388
  default:
389
#ifdef QT_DEBUG
390
    dbg() << "Unhandled process type" << pid;
391
#endif
392
    break;
393
  }
394
}
395

396
/**
397
 * @brief Pass::updateEnv update the execution environment (used when
398
 * switching profiles)
399
 */
400
void Pass::updateEnv() {
×
401
  // put PASSWORD_STORE_SIGNING_KEY in env
402
  QStringList envSigningKey = env.filter("PASSWORD_STORE_SIGNING_KEY=");
×
403
  QString currentSigningKey = QtPassSettings::getPassSigningKey();
×
404
  if (envSigningKey.isEmpty()) {
×
405
    if (!currentSigningKey.isEmpty()) {
×
406
      // dbg()<< "Added
407
      // PASSWORD_STORE_SIGNING_KEY with" + currentSigningKey;
408
      env.append("PASSWORD_STORE_SIGNING_KEY=" + currentSigningKey);
×
409
    }
410
  } else {
411
    if (currentSigningKey.isEmpty()) {
×
412
      // dbg() << "Removed
413
      // PASSWORD_STORE_SIGNING_KEY";
414
      env.removeAll(envSigningKey.first());
415
    } else {
416
      // dbg()<< "Update
417
      // PASSWORD_STORE_SIGNING_KEY with " + currentSigningKey;
418
      env.replaceInStrings(envSigningKey.first(),
×
419
                           "PASSWORD_STORE_SIGNING_KEY=" + currentSigningKey);
×
420
    }
421
  }
422
  // put PASSWORD_STORE_DIR in env
423
  QStringList store = env.filter("PASSWORD_STORE_DIR=");
×
424
  if (store.isEmpty()) {
×
425
    // dbg()<< "Added
426
    // PASSWORD_STORE_DIR";
427
    env.append("PASSWORD_STORE_DIR=" + QtPassSettings::getPassStore());
×
428
  } else {
429
    // dbg()<< "Update
430
    // PASSWORD_STORE_DIR with " + passStore;
431
    env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" +
×
432
                                            QtPassSettings::getPassStore());
×
433
  }
434
  exec.setEnvironment(env);
×
435
}
×
436

437
/**
438
 * @brief Pass::getGpgIdPath return gpgid file path for some file (folder).
439
 * @param for_file which file (folder) would you like the gpgid file path for.
440
 * @return path to the gpgid file.
441
 */
442
auto Pass::getGpgIdPath(const QString &for_file) -> QString {
8✔
443
  QString passStore =
444
      QDir::fromNativeSeparators(QtPassSettings::getPassStore());
16✔
445
  QString normalizedFile = QDir::fromNativeSeparators(for_file);
8✔
446
  QString fullPath = normalizedFile.startsWith(passStore)
8✔
447
                         ? normalizedFile
8✔
448
                         : passStore + "/" + normalizedFile;
6✔
449
  QDir gpgIdDir(QFileInfo(fullPath).absoluteDir());
8✔
450
  bool found = false;
451
  while (gpgIdDir.exists() && gpgIdDir.absolutePath().startsWith(passStore)) {
10✔
452
    if (QFile(gpgIdDir.absoluteFilePath(".gpg-id")).exists()) {
2✔
453
      found = true;
454
      break;
455
    }
456
    if (!gpgIdDir.cdUp()) {
×
457
      break;
458
    }
459
  }
460
  QString gpgIdPath(found ? gpgIdDir.absoluteFilePath(".gpg-id")
8✔
461
                          : QtPassSettings::getPassStore() + ".gpg-id");
22✔
462

463
  return gpgIdPath;
8✔
464
}
8✔
465

466
/**
467
 * @brief Pass::getRecipientList return list of gpg-id's to encrypt for
468
 * @param for_file which file (folder) would you like recipients for
469
 * @return recipients gpg-id contents
470
 */
471
auto Pass::getRecipientList(const QString &for_file) -> QStringList {
5✔
472
  QFile gpgId(getGpgIdPath(for_file));
5✔
473
  if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text)) {
5✔
474
    return {};
×
475
  }
476
  QStringList recipients;
5✔
477
  while (!gpgId.atEnd()) {
14✔
478
    QString recipient(gpgId.readLine());
18✔
479
    recipient = recipient.split("#")[0].trimmed();
18✔
480
    if (!recipient.isEmpty()) {
9✔
481
      recipients += recipient;
482
    }
483
  }
484
  return recipients;
485
}
5✔
486

487
/**
488
 * @brief Pass::getRecipientString formatted string for use with GPG
489
 * @param for_file which file (folder) would you like recipients for
490
 * @param separator formating separator eg: " -r "
491
 * @param count
492
 * @return recipient string
493
 */
494
auto Pass::getRecipientString(const QString &for_file, const QString &separator,
2✔
495
                              int *count) -> QStringList {
496
  Q_UNUSED(separator)
497
  QStringList recipients = Pass::getRecipientList(for_file);
2✔
498
  if (count) {
2✔
499
    *count = recipients.size();
1✔
500
  }
501
  return recipients;
2✔
502
}
503

504
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
505
 */
506

507
/**
508
 * @brief Generates a random number bounded by the given value.
509
 * @param bound Upper bound (exclusive)
510
 * @return Random number in range [0, bound)
511
 */
512
auto Pass::boundedRandom(quint32 bound) -> quint32 {
1,160✔
513
  if (bound < 2) {
1,160✔
514
    return 0;
515
  }
516

517
  quint32 randval;
518
  // Reject values below max_mod_bound (computed as 1 + ~bound == 2^32 -
519
  // bound) to avoid modulo bias and ensure uniform randval % bound.
520
  const quint32 max_mod_bound = (1 + ~bound) % bound;
1,160✔
521

522
  do {
523
    randval = QRandomGenerator::system()->generate();
524
  } while (randval < max_mod_bound);
1,160✔
525

526
  return randval % bound;
1,160✔
527
}
528

529
/**
530
 * @brief Generates a random password from the given charset.
531
 * @param charset Characters to use in the password
532
 * @param length Desired password length
533
 * @return Generated password string
534
 */
535
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,004✔
536
    -> QString {
537
  if (charset.isEmpty() || length == 0U) {
1,004✔
538
    return {};
539
  }
540
  QString out;
1,003✔
541
  for (unsigned int i = 0; i < length; ++i) {
2,163✔
542
    out.append(charset.at(static_cast<int>(
1,160✔
543
        boundedRandom(static_cast<quint32>(charset.length())))));
1,160✔
544
  }
545
  return out;
546
}
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