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

IJHack / QtPass / 24574931090

17 Apr 2026 04:11PM UTC coverage: 21.249% (-0.08%) from 21.329%
24574931090

Pull #1032

github

web-flow
Merge 153c521b1 into 89ef5cc93
Pull Request #1032: fix: set PASSWORD_STORE_* env vars and grey out pass-managed controls

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

227 existing lines in 2 files now uncovered.

1143 of 5379 relevant lines covered (21.25%)

8.05 hits per line

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

42.25
/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()) {
9✔
35
  connect(&exec,
9✔
36
          static_cast<void (Executor::*)(int, int, const QString &,
37
                                         const QString &)>(&Executor::finished),
38
          this, &Pass::finished);
9✔
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);
9✔
46
  env.append("WSLENV=PASSWORD_STORE_DIR/p");
9✔
47
}
9✔
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
 */
UNCOV
57
void Pass::executeWrapper(PROCESS id, const QString &app,
×
58
                          const QStringList &args, bool readStdout,
59
                          bool readStderr) {
UNCOV
60
  executeWrapper(id, app, args, QString(), readStdout, readStderr);
×
61
}
×
62

UNCOV
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
UNCOV
69
  exec.execute(id, QtPassSettings::getPassStore(), app, args, std::move(input),
×
70
               readStdout, readStderr);
UNCOV
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✔
UNCOV
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,006✔
101
    -> QString {
102
  QString passwd;
1,006✔
103
  if (QtPassSettings::isUsePwgen()) {
1,006✔
104
    // --secure goes first as it overrides --no-* otherwise
UNCOV
105
    QStringList args;
×
106
    args.append("-1");
×
107
    if (!QtPassSettings::isLessRandom()) {
×
108
      args.append("--secure");
×
109
    }
UNCOV
110
    args.append(QtPassSettings::isAvoidCapitals() ? "--no-capitalize"
×
111
                                                  : "--capitalize");
UNCOV
112
    args.append(QtPassSettings::isAvoidNumbers() ? "--no-numerals"
×
113
                                                 : "--numerals");
UNCOV
114
    if (QtPassSettings::isUseSymbols()) {
×
115
      args.append("--symbols");
×
116
    }
UNCOV
117
    args.append(QString::number(length));
×
118
    // executeBlocking returns 0 on success, non-zero on failure
UNCOV
119
    if (Executor::executeBlocking(QtPassSettings::getPwgenExecutable(), args,
×
120
                                  &passwd) == 0) {
UNCOV
121
      static const QRegularExpression literalNewLines{"[\\n\\r]"};
×
122
      passwd.remove(literalNewLines);
×
123
    } else {
UNCOV
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,006✔
137
      effectiveCharset = QtPassSettings::getPasswordConfiguration()
2✔
138
                             .Characters[PasswordConfiguration::ALLCHARS];
139
    }
140
    if (effectiveCharset.length() > 0) {
1,006✔
141
      passwd = generateRandomPassword(effectiveCharset, length);
2,012✔
142
    } else {
UNCOV
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,006✔
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() {
2✔
158
  QString out, err;
2✔
159
  if (Executor::executeBlocking(QtPassSettings::getGpgExecutable(),
8✔
160
                                {"--version"}, &out, &err) != 0) {
161
    return false;
162
  }
UNCOV
163
  QRegularExpression versionRegex(R"(gpg \(GnuPG\) (\d+)\.(\d+))");
×
164
  QRegularExpressionMatch match = versionRegex.match(out);
×
165
  if (!match.hasMatch()) {
×
166
    return false;
167
  }
UNCOV
168
  int major = match.captured(1).toInt();
×
169
  int minor = match.captured(2).toInt();
×
170
  return major > 2 || (major == 2 && minor >= 1);
×
171
}
2✔
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✔
UNCOV
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
/**
218
 * @brief Finds the path to the gpgconf executable in the same directory as the
219
 * given GPG path.
220
 * @example
221
 * QString result = findGpgconfInGpgDir(gpgPath);
222
 * std::cout << result.toStdString() << std::endl; // Expected output: path to
223
 * gpgconf or empty string
224
 *
225
 * @param gpgPath - Absolute path to a GPG executable or related file used to
226
 * locate gpgconf.
227
 * @return QString - The full path to gpgconf if found and executable; otherwise
228
 * an empty QString.
229
 */
230
QString findGpgconfInGpgDir(const QString &gpgPath) {
1✔
231
  QFileInfo gpgInfo(gpgPath);
1✔
232
  if (!gpgInfo.isAbsolute()) {
1✔
233
    return QString();
234
  }
235

236
  QDir dir(gpgInfo.absolutePath());
1✔
237

238
#ifdef Q_OS_WIN
239
  QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
240
  if (candidateExe.isExecutable()) {
241
    return candidateExe.filePath();
242
  }
243
#endif
244

245
  QFileInfo candidate(dir.filePath("gpgconf"));
1✔
246
  if (candidate.isExecutable()) {
1✔
UNCOV
247
    return candidate.filePath();
×
248
  }
249
  return QString();
250
}
1✔
251

252
#if QT_VERSION < QT_VERSION_CHECK(5, 15, 0)
253
/**
254
 * @brief Splits a command string into arguments while respecting quotes and
255
 * escape characters.
256
 * @example
257
 * QStringList result = splitCommandCompat("cmd \"arg one\" 'arg two'
258
 * escaped\\ space");
259
 * // Expected output: ["cmd", "arg one", "arg two", "escaped space"]
260
 *
261
 * @param command - The input command string to split into individual arguments.
262
 * @return QStringList - A list of parsed command arguments.
263
 */
264
QStringList splitCommandCompat(const QString &command) {
265
  QStringList result;
266
  QString current;
267
  bool inSingleQuote = false;
268
  bool inDoubleQuote = false;
269
  bool escaping = false;
270
  for (QChar ch : command) {
271
    if (escaping) {
272
      current.append(ch);
273
      escaping = false;
274
      continue;
275
    }
276
    if (ch == '\\') {
277
      escaping = true;
278
      continue;
279
    }
280
    if (ch == '\'' && !inDoubleQuote) {
281
      inSingleQuote = !inSingleQuote;
282
      continue;
283
    }
284
    if (ch == '"' && !inSingleQuote) {
285
      inDoubleQuote = !inDoubleQuote;
286
      continue;
287
    }
288
    if (ch.isSpace() && !inSingleQuote && !inDoubleQuote) {
289
      if (!current.isEmpty()) {
290
        result.append(current);
291
        current.clear();
292
      }
293
      continue;
294
    }
295
    current.append(ch);
296
  }
297
  if (escaping) {
298
    current.append('\\');
299
  }
300
  if (!current.isEmpty()) {
301
    result.append(current);
302
  }
303
  return result;
304
}
305
#endif
306

307
} // namespace
308

309
/**
310
 * @brief Resolves the appropriate gpgconf command from a given GPG executable
311
 * path or command string.
312
 * @example
313
 * ResolvedGpgconfCommand result = Pass::resolveGpgconfCommand("wsl.exe
314
 * /usr/bin/gpg"); std::cout << result.first.toStdString() << std::endl; //
315
 * Expected output sample
316
 *
317
 * @param const QString &gpgPath - Path or command string pointing to the GPG
318
 * executable.
319
 * @return ResolvedGpgconfCommand - A pair containing the resolved gpgconf
320
 * command and its arguments.
321
 */
322
auto Pass::resolveGpgconfCommand(const QString &gpgPath)
8✔
323
    -> ResolvedGpgconfCommand {
324
  if (gpgPath.trimmed().isEmpty()) {
8✔
325
    return {"gpgconf", {}};
326
  }
327

328
#if QT_VERSION >= QT_VERSION_CHECK(5, 15, 0)
329
  QStringList parts = QProcess::splitCommand(gpgPath);
7✔
330
#else
331
  QStringList parts = splitCommandCompat(gpgPath);
332
#endif
333

334
  if (parts.isEmpty()) {
7✔
335
    return {"gpgconf", {}};
336
  }
337

338
  const QString first = parts.first();
339
  if (first == "wsl" || first == "wsl.exe") {
9✔
340
    if (parts.size() >= 2 && parts.at(1).startsWith("sh")) {
9✔
341
      return {"gpgconf", {}};
342
    }
343
    if (parts.size() >= 2 &&
4✔
344
        QFileInfo(parts.last()).fileName().startsWith("gpg")) {
10✔
345
      QString wslGpgconf = resolveWslGpgconfPath(parts.last());
3✔
346
      parts.removeLast();
3✔
347
      parts.append(wslGpgconf);
348
      return {parts.first(), parts.mid(1)};
349
    }
350
    return {"gpgconf", {}};
351
  }
352

353
  if (!first.contains('/') && !first.contains('\\')) {
2✔
354
    return {"gpgconf", {}};
355
  }
356

357
  QString gpgconfPath = findGpgconfInGpgDir(gpgPath);
1✔
358
  if (!gpgconfPath.isEmpty()) {
1✔
UNCOV
359
    return {gpgconfPath, {}};
×
360
  }
361

362
  return {"gpgconf", {}};
363
}
8✔
364

365
/**
366
 * @brief Pass::GenerateGPGKeys internal gpg keypair generator . .
367
 * @param batch GnuPG style configuration string
368
 */
UNCOV
369
void Pass::GenerateGPGKeys(QString batch) {
×
370
  // Kill any stale GPG agents that might be holding locks on the key database
371
  // This helps avoid "database locked" timeouts during key generation
UNCOV
372
  QString gpgPath = QtPassSettings::getGpgExecutable();
×
373
  if (!gpgPath.isEmpty()) {
×
374
    ResolvedGpgconfCommand gpgconf = resolveGpgconfCommand(gpgPath);
×
375
    QStringList killArgs = gpgconf.arguments;
UNCOV
376
    killArgs << "--kill";
×
377
    killArgs << "gpg-agent";
×
378
    // Use same environment as key generation to target correct gpg-agent
UNCOV
379
    Executor::executeBlocking(env, gpgconf.program, killArgs);
×
380
  }
381

UNCOV
382
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
×
383
                 std::move(batch));
UNCOV
384
}
×
385

386
/**
387
 * @brief Pass::listKeys list users
388
 * @param keystrings
389
 * @param secret list private keys
390
 * @return QList<UserInfo> users
391
 */
UNCOV
392
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
×
393
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
×
394
  args.append(secret ? "--list-secret-keys" : "--list-keys");
×
395

UNCOV
396
  for (const QString &keystring : AS_CONST(keystrings)) {
×
397
    if (!keystring.isEmpty()) {
×
398
      args.append(keystring);
399
    }
400
  }
UNCOV
401
  QString p_out;
×
402
  if (Executor::executeBlocking(QtPassSettings::getGpgExecutable(), args,
×
403
                                &p_out) != 0) {
UNCOV
404
    return QList<UserInfo>();
×
405
  }
UNCOV
406
  return parseGpgColonOutput(p_out, secret);
×
407
}
×
408

409
/**
410
 * @brief Pass::listKeys list users
411
 * @param keystring
412
 * @param secret list private keys
413
 * @return QList<UserInfo> users
414
 */
UNCOV
415
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
×
416
  return listKeys(QStringList(keystring), secret);
×
417
}
418

419
/**
420
 * @brief Pass::processFinished reemits specific signal based on what process
421
 * has finished
422
 * @param id    id of Pass process that was scheduled and finished
423
 * @param exitCode  return code of a process
424
 * @param out   output generated by process(if capturing was requested, empty
425
 *              otherwise)
426
 * @param err   error output generated by process(if capturing was requested,
427
 *              or error occurred)
428
 */
UNCOV
429
void Pass::finished(int id, int exitCode, const QString &out,
×
430
                    const QString &err) {
431
  auto pid = static_cast<PROCESS>(id);
UNCOV
432
  if (exitCode != 0) {
×
433
    emit processErrorExit(exitCode, err);
×
434
    return;
×
435
  }
UNCOV
436
  switch (pid) {
×
437
  case GIT_INIT:
×
438
    emit finishedGitInit(out, err);
×
439
    break;
×
440
  case GIT_PULL:
×
441
    emit finishedGitPull(out, err);
×
442
    break;
×
443
  case GIT_PUSH:
×
444
    emit finishedGitPush(out, err);
×
445
    break;
×
446
  case PASS_SHOW:
×
447
    emit finishedShow(out);
×
448
    break;
×
449
  case PASS_OTP_GENERATE:
×
450
    emit finishedOtpGenerate(out);
×
451
    break;
×
452
  case PASS_INSERT:
×
453
    emit finishedInsert(out, err);
×
454
    break;
×
455
  case PASS_REMOVE:
×
456
    emit finishedRemove(out, err);
×
457
    break;
×
458
  case PASS_INIT:
×
459
    emit finishedInit(out, err);
×
460
    break;
×
461
  case PASS_MOVE:
×
462
    emit finishedMove(out, err);
×
463
    break;
×
464
  case PASS_COPY:
×
465
    emit finishedCopy(out, err);
×
466
    break;
×
467
  case GPG_GENKEYS:
×
468
    emit finishedGenerateGPGKeys(out, err);
×
469
    break;
×
470
  default:
471
#ifdef QT_DEBUG
472
    dbg() << "Unhandled process type" << pid;
473
#endif
474
    break;
475
  }
476
}
477

478
/**
479
 * @brief Pass::updateEnv update the execution environment (used when
480
 * switching profiles)
481
 */
UNCOV
482
void Pass::updateEnv() {
×
483
  // put PASSWORD_STORE_SIGNING_KEY in env
UNCOV
484
  QStringList envSigningKey = env.filter("PASSWORD_STORE_SIGNING_KEY=");
×
485
  QString currentSigningKey = QtPassSettings::getPassSigningKey();
×
486
  if (envSigningKey.isEmpty()) {
×
487
    if (!currentSigningKey.isEmpty()) {
×
488
      // dbg()<< "Added
489
      // PASSWORD_STORE_SIGNING_KEY with" + currentSigningKey;
UNCOV
490
      env.append("PASSWORD_STORE_SIGNING_KEY=" + currentSigningKey);
×
491
    }
492
  } else {
UNCOV
493
    if (currentSigningKey.isEmpty()) {
×
494
      env.removeAll(envSigningKey.first());
495
    } else {
496
      // dbg()<< "Update
497
      // PASSWORD_STORE_SIGNING_KEY with " + currentSigningKey;
UNCOV
498
      env.replaceInStrings(envSigningKey.first(),
×
499
                           "PASSWORD_STORE_SIGNING_KEY=" + currentSigningKey);
×
500
    }
501
  }
502
  // put PASSWORD_STORE_DIR in env
UNCOV
503
  QStringList store = env.filter("PASSWORD_STORE_DIR=");
×
504
  if (store.isEmpty()) {
×
505
    env.append("PASSWORD_STORE_DIR=" + QtPassSettings::getPassStore());
×
506
  } else {
507
    // dbg()<< "Update
508
    // PASSWORD_STORE_DIR with " + passStore;
UNCOV
509
    env.replaceInStrings(store.first(), "PASSWORD_STORE_DIR=" +
×
510
                                            QtPassSettings::getPassStore());
×
511
  }
512
  // put PASSWORD_STORE_GENERATED_LENGTH in env
NEW
513
  PasswordConfiguration passConfig = QtPassSettings::getPasswordConfiguration();
×
NEW
514
  QString lenKey = QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH=");
×
NEW
515
  QString lenVal = lenKey + QString::number(passConfig.length);
×
516
  QStringList envLen = env.filter(lenKey);
NEW
517
  if (envLen.isEmpty()) {
×
518
    env.append(lenVal);
519
  } else {
NEW
520
    env.replaceInStrings(envLen.first(), lenVal);
×
521
  }
522
  // put PASSWORD_STORE_CHARACTER_SET in env
NEW
523
  QString charset = passConfig.Characters[passConfig.selected];
×
NEW
524
  if (!charset.isEmpty()) {
×
NEW
525
    QString charKey = QStringLiteral("PASSWORD_STORE_CHARACTER_SET=");
×
NEW
526
    QString charVal = charKey + charset;
×
527
    QStringList envChar = env.filter(charKey);
NEW
528
    if (envChar.isEmpty()) {
×
529
      env.append(charVal);
530
    } else {
NEW
531
      env.replaceInStrings(envChar.first(), charVal);
×
532
    }
533
  }
NEW
534
  exec.setEnvironment(env);
×
NEW
535
}
×
536

537
/**
538
 * @brief Pass::getGpgIdPath return gpgid file path for some file (folder).
539
 * @param for_file which file (folder) would you like the gpgid file path for.
540
 * @return path to the gpgid file.
541
 */
542
auto Pass::getGpgIdPath(const QString &for_file) -> QString {
9✔
543
  QString passStore =
544
      QDir::fromNativeSeparators(QtPassSettings::getPassStore());
18✔
545
  QString normalizedFile = QDir::fromNativeSeparators(for_file);
9✔
546
  QString fullPath = normalizedFile.startsWith(passStore)
9✔
547
                         ? normalizedFile
9✔
548
                         : passStore + "/" + normalizedFile;
7✔
549
  QDir gpgIdDir(QFileInfo(fullPath).absoluteDir());
9✔
550
  bool found = false;
551
  while (gpgIdDir.exists() && gpgIdDir.absolutePath().startsWith(passStore)) {
11✔
552
    if (QFile(gpgIdDir.absoluteFilePath(".gpg-id")).exists()) {
2✔
553
      found = true;
554
      break;
555
    }
UNCOV
556
    if (!gpgIdDir.cdUp()) {
×
557
      break;
558
    }
559
  }
560
  QString gpgIdPath(
561
      found ? gpgIdDir.absoluteFilePath(".gpg-id")
9✔
562
            : QDir(QtPassSettings::getPassStore()).filePath(".gpg-id"));
33✔
563

564
  return gpgIdPath;
9✔
565
}
9✔
566

567
/**
568
 * @brief Pass::getRecipientList return list of gpg-id's to encrypt for
569
 * @param for_file which file (folder) would you like recipients for
570
 * @return recipients gpg-id contents
571
 */
572
auto Pass::getRecipientList(const QString &for_file) -> QStringList {
6✔
573
  QFile gpgId(getGpgIdPath(for_file));
6✔
574
  if (!gpgId.open(QIODevice::ReadOnly | QIODevice::Text)) {
6✔
UNCOV
575
    return {};
×
576
  }
577
  QStringList recipients;
6✔
578
  while (!gpgId.atEnd()) {
20✔
579
    QString recipient(gpgId.readLine());
28✔
580
    recipient = recipient.split("#")[0].trimmed();
28✔
581
    if (!recipient.isEmpty() && Util::isValidKeyId(recipient)) {
14✔
582
      recipients += recipient;
583
    }
584
  }
585
  return recipients;
586
}
6✔
587

588
/**
589
 * @brief Pass::getRecipientString formatted string for use with GPG
590
 * @param for_file which file (folder) would you like recipients for
591
 * @param separator formating separator eg: " -r "
592
 * @param count
593
 * @return recipient string
594
 */
595
auto Pass::getRecipientString(const QString &for_file, const QString &separator,
2✔
596
                              int *count) -> QStringList {
597
  Q_UNUSED(separator)
598
  QStringList recipients = Pass::getRecipientList(for_file);
2✔
599
  if (count) {
2✔
600
    *count = recipients.size();
1✔
601
  }
602
  return recipients;
2✔
603
}
604

605
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
606
 */
607

608
/**
609
 * @brief Generates a random number bounded by the given value.
610
 * @param bound Upper bound (exclusive)
611
 * @return Random number in range [0, bound)
612
 */
613
auto Pass::boundedRandom(quint32 bound) -> quint32 {
1,224✔
614
  if (bound < 2) {
1,224✔
615
    return 0;
616
  }
617

618
  quint32 randval;
619
  // Rejection-sampling threshold to avoid modulo bias:
620
  // In quint32 arithmetic, (1 + ~bound) wraps to (2^32 - bound), so
621
  // (1 + ~bound) % bound == 2^32 % bound.
622
  // Values randval < max_mod_bound are rejected; accepted values produce a
623
  // uniform distribution when reduced with (randval % bound).
624
  const quint32 max_mod_bound = (1 + ~bound) % bound;
1,224✔
625

626
  do {
627
    randval = QRandomGenerator::system()->generate();
628
  } while (randval < max_mod_bound);
1,224✔
629

630
  return randval % bound;
1,224✔
631
}
632

633
/**
634
 * @brief Generates a random password from the given charset.
635
 * @param charset Characters to use in the password
636
 * @param length Desired password length
637
 * @return Generated password string
638
 */
639
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,006✔
640
    -> QString {
641
  if (charset.isEmpty() || length == 0U) {
1,006✔
642
    return {};
643
  }
644
  QString out;
1,005✔
645
  for (unsigned int i = 0; i < length; ++i) {
2,229✔
646
    out.append(charset.at(static_cast<int>(
1,224✔
647
        boundedRandom(static_cast<quint32>(charset.length())))));
1,224✔
648
  }
649
  return out;
650
}
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