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

IJHack / QtPass / 46578328516

01 Dec 2026 04:47AM UTC coverage: 94.508% (-0.004%) from 94.512%
46578328516

Pull #2430

github

web-flow
Merge 9e7afff0b into 9ec41c840
Pull Request #2430: Split pinStoreGitAttributes, copyText and trackCopied

23 of 35 new or added lines in 2 files covered. (65.71%)

1 existing line in 1 file now uncovered.

11427 of 12091 relevant lines covered (94.51%)

23908.56 hits per line

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

96.17
/src/pass.cpp
1
// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
/**
4
 * @file
5
 * @brief Implements what both backends share: the environment the store's
6
 * processes run in, the refusals for links and paths outside the store, `.gpg-
7
 * id` lookup, and Pass::finished(), which routes each finished process to its
8
 * signal.
9
 */
10
#include "pass.h"
11

12
#include "entryrecord.h"
13
#include "gpgidgeneration.h"
14
#include "gpgidsigner.h"
15
#include "gpgkeystate.h"
16
#include "pathvalidator.h"
17
#include "processinfo.h"
18
#include "util.h"
19
#include <QCoreApplication>
20
#include <QDebug>
21
#include <QDir>
22
#include <QFile>
23
#include <QFileInfo>
24
#include <QHash>
25
#include <QLocale>
26
#include <QProcess>
27
#include <QRandomGenerator>
28
#include <QRegularExpression>
29
#include <QSaveFile>
30
#include <QScopeGuard>
31
#include <QTemporaryDir>
32
#include <QTextStream>
33
#include <algorithm>
34
#include <array>
35
#include <optional>
36
#include <utility>
37

38
#include "qtpasslogging.h"
39

40
using Enums::GIT_INIT;
41
using Enums::GIT_PULL;
42
using Enums::GIT_PUSH;
43
using Enums::GPG_GENKEYS;
44
using Enums::PASS_COPY;
45
using Enums::PASS_INIT;
46
using Enums::PASS_INSERT;
47
using Enums::PASS_MOVE;
48
using Enums::PASS_REMOVE;
49
using Enums::PASS_SHOW;
50

51
namespace {
52
auto fallbackCharset(const QString &input, const QString &fallback) -> QString {
53
  return input.isEmpty() ? fallback : input;
1,706 ✔
54
}
55

56
auto effectiveCharset(const PasswordConfiguration &passConfig) -> QString {
499 ✔
57
  int sel = passConfig.selected;
499 ✔
58
  if (sel < 0 || sel >= PasswordConfiguration::CHARSETS_COUNT)
499 ✔
59
    sel = PasswordConfiguration::ALLCHARS;
60
  return fallbackCharset(
61
      passConfig.Characters[sel],
499 ✔
62
      passConfig.Characters[PasswordConfiguration::ALLCHARS]);
499 ✔
63
}
64

65
/**
66
 * @brief Add @p names to WSLENV in @p env, keeping its entries and adding no
67
 * duplicate.
68
 * @param env The environment to amend.
69
 * @param names WSLENV entries, each a variable name with its flags.
70
 */
71
void mergeIntoWslenv(QProcessEnvironment &env, const QStringList &names) {
986 ✔
72
  QStringList parts = env.value(QStringLiteral("WSLENV"))
1,972 ✔
73
                          .split(QLatin1Char(':'), Qt::SkipEmptyParts);
986 ✔
74
  for (const QString &name : names) {
5,892 ✔
75
    if (!parts.contains(name)) {
4,906 ✔
76
      parts.append(name);
77
    }
78
  }
79
  env.insert(QStringLiteral("WSLENV"), parts.join(QLatin1Char(':')));
1,972 ✔
80
}
986 ✔
81
} // namespace
82

83
Pass::Pass() : env(QProcessEnvironment::systemEnvironment()) {
487 ✔
84
  connect(&exec, &Executor::finished, this, &Pass::finished);
487 ✔
85
  connect(&exec, &Executor::error, this, &Pass::finished);
487 ✔
86

87
  connect(&exec, &Executor::starting, this, &Pass::startingExecuteWrapper);
487 ✔
88
  connect(&exec, &Executor::drained, this, [this] {
487 ✔
89
    // Idle means the queue is empty and nothing runs, so no insert is in
90
    // flight: force the pending count to zero. A report that never arrived
91
    // (the "No such transaction" path in ImitatePass::finished(), or any
92
    // later change that drops an insert without reporting) would otherwise
93
    // leave the count one too high for the rest of the session, and every
94
    // later dialog would take its own report for an earlier one and wait for
95
    // ever. Idle cannot fall between a dialog's insertsPending() read and its
96
    // own report, since that insert keeps the executor busy.
97
    m_insertsPending = 0;
139 ✔
98
    m_insertedEntries.clear();
139 ✔
99
    emit idle();
139 ✔
100
  });
139 ✔
101
  // Each queued process starts in the environment as the store is then:
102
  // the Git pin is judged at that moment (dequeuing() comes just before the
103
  // start, on this thread).
104
  connect(&exec, &Executor::dequeuing, this, [this](int, bool completes) {
487 ✔
105
    if (completes) {
384 ✔
106
      exec.setEnvironment(withCurrentGitPin(env));
376 ✔
107
    }
108
  });
384 ✔
109
  // Merge our vars into WSLENV rather than blindly appending a duplicate
110
  // entry. WSLENV flags: /p translates the path, /u forwards from Windows
111
  // into WSL only; /w would be the other direction, from WSL out, and leaves
112
  // pass inside WSL without the value. Everything updateEnv() sets for pass
113
  // has to cross, the signing key above all: without it pass does not check
114
  // the .gpg-id signature.
115
  const QStringList wslenvVars = {
116
      QStringLiteral("PASSWORD_STORE_DIR/p"),
974 ✔
117
      QStringLiteral("PASSWORD_STORE_SIGNING_KEY/u"),
487 ✔
118
      QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH/u"),
487 ✔
119
      QStringLiteral("PASSWORD_STORE_CHARACTER_SET/u"),
487 ✔
120
      QStringLiteral("PASSWORD_STORE_GPG_OPTS/u"),
487 ✔
121
      QStringLiteral("GIT_CEILING_DIRECTORIES/p"),
487 ✔
122
      QStringLiteral("GIT_LITERAL_PATHSPECS/u")};
3,896 ✔
123
  mergeIntoWslenv(env, wslenvVars);
487 ✔
124
}
487 ✔
125

126
void Pass::executeWrapper(PROCESS id, const QString &app,
2 ✔
127
                          const QStringList &args, bool readStdout,
128
                          bool readStderr) {
129
  executeWrapper(id, app, args, QString(), readStdout, readStderr);
2 ✔
130
}
2 ✔
131

132
void Pass::executeWrapper(PROCESS id, const QString &app,
384 ✔
133
                          const QStringList &args, QString input,
134
                          bool readStdout, bool readStderr) {
135
  beforeExecute(id);
384 ✔
136
  qCDebug(lcQtPass) << app << loggableArgs(args);
384 ✔
137
  exec.execute(id, m_settings.passStore, app, args, std::move(input),
384 ✔
138
               readStdout, readStderr);
139
}
384 ✔
140

141
auto Pass::loggableArgs(const QStringList &args) -> QStringList {
4 ✔
142
  // Secrets travel on stdin (Insert's content, KeygenDialog's batch file),
143
  // never in argv; this keeps the log honest should that ever change.
144
  static const QStringList secretOptions{
145
      QStringLiteral("--passphrase"), QStringLiteral("--override-session-key")};
49 ✔
146
  QStringList out;
4 ✔
147
  bool hide = false;
148
  for (const QString &arg : args) {
12 ✔
149
    if (hide) {
8 ✔
150
      out << QStringLiteral("<redacted>");
1 ✔
151
      hide = false;
152
      continue;
1 ✔
153
    }
154
    if (arg.startsWith(QStringLiteral("otpauth://"))) {
14 ✔
155
      out << QStringLiteral("<redacted>");
1 ✔
156
      continue;
1 ✔
157
    }
158
    if (arg.startsWith(QStringLiteral("--passphrase=")) ||
12 ✔
159
        arg.startsWith(QStringLiteral("--override-session-key="))) {
11 ✔
160
      out << arg.left(arg.indexOf(u'=') + 1) + QStringLiteral("<redacted>");
2 ✔
161
      continue;
1 ✔
162
    }
163
    hide = secretOptions.contains(arg);
164
    out << arg;
165
  }
166
  return out;
4 ✔
167
}
168

169
void Pass::beforeExecute(PROCESS /*id*/) {}
87 ✔
170

171
void Pass::init(const AppSettings &settings) {
971 ✔
172
  m_settings = settings;
971 ✔
173
  // A key exported for pass counts when none is set here: pass checks the
174
  // list against it, and so do QtPass's own checks. Dropping it turned every
175
  // check off.
176
  m_settings.passSigningKey =
177
      GpgIdSigner::settingOrExported(m_settings.passSigningKey);
971 ✔
178
#ifdef __APPLE__
179
  // If it exists, prepend gpgtools to PATH
180
  if (QFile(QStringLiteral("/usr/local/MacGPG2/bin")).exists())
181
    env.insert(QStringLiteral("PATH"),
182
               QStringLiteral("/usr/local/MacGPG2/bin:") +
183
                   env.value(QStringLiteral("PATH")));
184
  // Add missing /usr/local/bin (exact component match, no leading colon)
185
  const QString currentPath = env.value(QStringLiteral("PATH"));
186
  if (!currentPath.split(':', Qt::SkipEmptyParts)
187
           .contains(QStringLiteral("/usr/local/bin"))) {
188
    env.insert(QStringLiteral("PATH"),
189
               currentPath.isEmpty()
190
                   ? QStringLiteral("/usr/local/bin")
191
                   : QStringLiteral("/usr/local/bin:") + currentPath);
192
  }
193
#endif
194

195
  // The configured gpgHome wins over GNUPGHOME only when it exists: a stale
196
  // one (#1711) fails every gpg call with "No secret key". Clearing the
197
  // setting restores the inherited value rather than keeping the old path.
198
  const QString inheritedHome = QProcessEnvironment::systemEnvironment().value(
1,942 ✔
199
      QStringLiteral("GNUPGHOME"));
1,942 ✔
200
  const auto useInheritedHome = [this, &inheritedHome]() {
908 ✔
201
    if (inheritedHome.isEmpty()) {
908 ✔
202
      env.remove(QStringLiteral("GNUPGHOME"));
1,244 ✔
203
    } else {
204
      env.insert(QStringLiteral("GNUPGHOME"), inheritedHome);
572 ✔
205
    }
206
  };
1,879 ✔
207
  if (m_settings.gpgHome.isEmpty()) {
971 ✔
208
    useInheritedHome();
906 ✔
209
  } else {
210
    QDir absHome(m_settings.gpgHome);
65 ✔
211
    absHome.makeAbsolute();
65 ✔
212
    if (absHome.exists()) {
65 ✔
213
      env.insert(QStringLiteral("GNUPGHOME"), absHome.path());
126 ✔
214
    } else {
215
      if (inheritedHome.isEmpty()) {
2 ✔
216
        qCWarning(lcQtPass) << "gpgHome" << absHome.path()
2 ✔
217
                            << "does not exist; using the default GnuPG home";
1 ✔
218
        emit statusMsg(tr("Configured GPG home %1 does not exist, using the "
1 ✔
219
                          "default keyring")
220
                           .arg(absHome.path()),
2 ✔
221
                       5000);
222
      } else {
223
        qCWarning(lcQtPass)
2 ✔
224
            << "gpgHome" << absHome.path() << "does not exist; using GNUPGHOME"
2 ✔
225
            << inheritedHome << "from the environment";
1 ✔
226
        emit statusMsg(tr("Configured GPG home %1 does not exist, using "
1 ✔
227
                          "GNUPGHOME %2 from the environment")
228
                           .arg(absHome.path(), inheritedHome),
2 ✔
229
                       5000);
230
      }
231
      useInheritedHome();
2 ✔
232
    }
233
  }
65 ✔
234
  // With signed lists, the entries a store holds when this device first
235
  // opens it count as saved here (trust on first use), before anything a
236
  // pusher writes can land: not at the edit check, which would record a
237
  // renamed folder as saved. Unsigned stores never walk.
238
  if (!m_settings.passSigningKey.isEmpty()) {
971 ✔
239
    EntryRecord::seedStore(m_settings.passStore);
44 ✔
240
  }
241
}
971 ✔
242

243
auto Pass::generatePassword(unsigned int length, const QString &charset)
1,211 ✔
244
    -> QString {
245
  if (length == 0) {
1,211 ✔
246
    emit critical(tr("Invalid password length"),
2 ✔
247
                  tr("Can't generate password with zero length."));
1 ✔
248
    return {};
1 ✔
249
  }
250
  QString passwd;
1,210 ✔
251
  if (m_settings.usePwgen) {
1,210 ✔
252
    // --secure goes first as it overrides --no-* otherwise
253
    QStringList args;
3 ✔
254
    args.append("-1");
3 ✔
255
    if (!m_settings.lessRandom) {
3 ✔
256
      args.append("--secure");
4 ✔
257
    }
258
    args.append(m_settings.avoidCapitals ? "--no-capitalize" : "--capitalize");
5 ✔
259
    args.append(m_settings.avoidNumbers ? "--no-numerals" : "--numerals");
5 ✔
260
    if (m_settings.useSymbols) {
3 ✔
261
      args.append("--symbols");
2 ✔
262
    }
263
    args.append(QString::number(length));
3 ✔
264
    if (Executor::executeBlocking(m_settings.pwgenExecutable, args, &passwd) ==
3 ✔
265
        0) {
266
      static const QRegularExpression literalNewLines{"[\\n\\r]"};
3 ✔
267
      passwd.remove(literalNewLines);
2 ✔
268
    } else {
269
      passwd.clear();
1 ✔
270
      qCDebug(lcQtPass) << "pwgen fail";
1 ✔
271
      // Report it, as the other generation failures do: otherwise Generate
272
      // does nothing silently and OK then saves an empty (or, on Edit, the
273
      // old) password.
274
      emit critical(
1 ✔
275
          tr("Password generation failed"),
1 ✔
276
          tr("Could not run pwgen (\"%1\"). Check the pwgen program in the "
1 ✔
277
             "settings, or turn \"Use pwgen\" off.")
278
              .arg(m_settings.pwgenExecutable));
2 ✔
279
    }
280
  } else {
281
    // An empty CUSTOM charset falls back to ALLCHARS, not a weak password
282
    // (#780).
283
    const QString cs = fallbackCharset(
284
        charset, m_settings.passwordConfiguration
285
                     .Characters[PasswordConfiguration::ALLCHARS]);
1,207 ✔
286
    if (cs.length() > 0) {
1,207 ✔
287
      passwd = generateRandomPassword(cs, length);
2,412 ✔
288
    } else {
289
      emit critical(
1 ✔
290
          tr("No characters chosen"),
1 ✔
291
          tr("Can't generate password, there are no characters to choose from "
1 ✔
292
             "set in the configuration!"));
293
    }
294
  }
295
  return passwd;
296
}
297

298
bool Pass::gpgSupportsEd25519(const QString &gpgExecutable) {
41 ✔
299
  const QString exe =
300
      gpgExecutable.isEmpty() ? QStringLiteral("gpg") : gpgExecutable;
41 ✔
301
  QString out, err;
41 ✔
302
  if (Executor::executeBlocking(exe, {"--version"}, &out, &err) != 0) {
164 ✔
303
    return false;
304
  }
305
  QRegularExpression versionRegex(R"(gpg \(GnuPG\) (\d+)\.(\d+))");
39 ✔
306
  QRegularExpressionMatch match = versionRegex.match(out);
39 ✔
307
  if (!match.hasMatch()) {
39 ✔
308
    return false;
309
  }
310
  int major = match.captured(1).toInt();
38 ✔
311
  int minor = match.captured(2).toInt();
38 ✔
312
  return major > 2 || (major == 2 && minor >= 1);
38 ✔
313
}
39 ✔
314

315
// ed25519 (GnuPG 2.1+) generates much faster than RSA.
316
QString Pass::getDefaultKeyTemplate(const QString &gpgExecutable) {
37 ✔
317
  if (gpgSupportsEd25519(gpgExecutable)) {
37 ✔
318
    return QStringLiteral("%echo Generating a default key\n"
34 ✔
319
                          "Key-Type: EdDSA\n"
320
                          "Key-Curve: Ed25519\n"
321
                          "Subkey-Type: ECDH\n"
322
                          "Subkey-Curve: Curve25519\n"
323
                          "Name-Real: \n"
324
                          "Name-Comment: QtPass\n"
325
                          "Name-Email: \n"
326
                          "Expire-Date: 0\n"
327
                          "%no-protection\n"
328
                          "%commit\n"
329
                          "%echo done");
330
  }
331
  return QStringLiteral("%echo Generating a default key\n"
3 ✔
332
                        "Key-Type: RSA\n"
333
                        "Subkey-Type: RSA\n"
334
                        "Name-Real: \n"
335
                        "Name-Comment: QtPass\n"
336
                        "Name-Email: \n"
337
                        "Expire-Date: 0\n"
338
                        "%no-protection\n"
339
                        "%commit\n"
340
                        "%echo done");
341
}
342

343
namespace {
344
auto resolveWslGpgconfPath(const QString &lastPart) -> QString {
8 ✔
345
  qsizetype lastSep = lastPart.lastIndexOf('/');
8 ✔
346
  if (lastSep < 0) {
8 ✔
347
    lastSep = lastPart.lastIndexOf('\\');
5 ✔
348
  }
349
  if (lastSep >= 0) {
5 ✔
350
    return lastPart.left(lastSep + 1) + "gpgconf";
6 ✔
351
  }
352
  return QStringLiteral("gpgconf");
5 ✔
353
}
354

355
QString findGpgconfInGpgDir(const QString &gpgPath) {
8 ✔
356
  QFileInfo gpgInfo(gpgPath);
8 ✔
357
  if (!gpgInfo.isAbsolute()) {
8 ✔
358
    return {};
1 ✔
359
  }
360

361
  QDir dir(gpgInfo.absolutePath());
7 ✔
362

363
#ifdef Q_OS_WIN
364
  QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
365
  if (candidateExe.isExecutable()) {
366
    return candidateExe.filePath();
367
  }
368
#endif
369

370
  QFileInfo candidate(dir.filePath("gpgconf"));
7 ✔
371
  if (candidate.isExecutable()) {
7 ✔
372
    return candidate.filePath();
5 ✔
373
  }
374
  return {};
2 ✔
375
}
8 ✔
376

377
} // namespace
378

379
auto Pass::resolveGpgconfCommand(const QString &gpgPath)
22 ✔
380
    -> ResolvedGpgconfCommand {
381
  if (gpgPath.trimmed().isEmpty()) {
22 ✔
382
    return {"gpgconf", {}};
383
  }
384

385
  // WSL: gpgconf next to the configured gpg, same distribution, via --exec
386
  // not the shell. An unparsed form (`wsl sh -c ...`, bare `wsl`) falls back
387
  // to gpgconf on the Windows PATH.
388
  if (const auto wsl = Executor::parseWslCommand(gpgPath)) {
21 ✔
389
    if (!QFileInfo(wsl->command).fileName().startsWith("gpg")) {
18 ✔
390
      return {"gpgconf", {}};
391
    }
392
    const auto gpgconf = wsl->with(resolveWslGpgconfPath(wsl->command));
16 ✔
393
    return {gpgconf.launcher, gpgconf.argv({})};
×
394
  }
8 ✔
395

396
  const QStringList parts = QProcess::splitCommand(gpgPath);
12 ✔
397
  if (parts.isEmpty()) {
12 ✔
398
    return {"gpgconf", {}};
399
  }
400
  const QString first = parts.first();
401
  if (QFileInfo(first).fileName().compare("wsl", Qt::CaseInsensitive) == 0 ||
33 ✔
402
      QFileInfo(first).fileName().compare("wsl.exe", Qt::CaseInsensitive) ==
30 ✔
403
          0) {
404
    return {"gpgconf", {}};
405
  }
406

407
  if (!first.contains('/') && !first.contains('\\')) {
9 ✔
408
    return {"gpgconf", {}};
409
  }
410

411
  QString gpgconfPath = findGpgconfInGpgDir(first);
8 ✔
412
  if (!gpgconfPath.isEmpty()) {
8 ✔
413
    return {gpgconfPath, {}};
5 ✔
414
  }
415

416
  return {"gpgconf", {}};
417
}
22 ✔
418

419
void Pass::GenerateGPGKeys(QString batch) {
12 ✔
420
  const QString gpgPath = m_settings.gpgExecutable;
421
  if (gpgPath.isEmpty()) {
12 ✔
422
    // The executor would fail an empty executable with a generic process
423
    // error; the keygen dialog waits for generateGPGKeysFailed and a reason
424
    // it can show. Queued so we do not re-enter KeygenDialog::done(), which
425
    // drives key generation synchronously.
426
    QMetaObject::invokeMethod(
10 ✔
427
        this,
428
        [this]() {
10 ✔
429
          emit generateGPGKeysFailed(tr("No GPG executable configured"));
5 ✔
430
          emit processErrorExit(1, tr("No GPG executable configured"));
5 ✔
431
        },
5 ✔
432
        Qt::QueuedConnection);
433
    return;
434
  }
435

436
  // A stale gpg-agent holding the key database lock causes "database locked"
437
  // timeouts during key generation.
438
  ResolvedGpgconfCommand resolvedGpgconf = resolveGpgconfCommand(gpgPath);
2 ✔
439
  QStringList killArgs = resolvedGpgconf.arguments;
440
  killArgs << "--kill";
2 ✔
441
  killArgs << "gpg-agent";
2 ✔
442
  // Use same environment as key generation to target correct gpg-agent
443
  if (Executor::executeBlocking(env, resolvedGpgconf.program, killArgs) != 0) {
2 ✔
444
    qCWarning(lcQtPass) << "Failed to kill gpg-agent";
2 ✔
445
  }
446

447
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
16 ✔
448
                 std::move(batch), true, true);
449
}
450

451
namespace {
452
/**
453
 * @brief The key ID or fingerprint @p line names, as gpg reads it: 8, 16,
454
 *        40 or 64 hex digits, with an optional 0x and trailing "!", or a
455
 *        fingerprint grouped with spaces as `gpg --fingerprint` prints it.
456
 * @param line A recipient line.
457
 * @return The digits in upper case, without 0x, "!" or spaces; empty for
458
 *         any other line.
459
 */
460
auto keyOfLine(const QString &line) -> QString {
6,718 ✔
461
  QString key = line.trimmed();
462
  if (key.endsWith(QLatin1Char('!'))) {
6,718 ✔
463
    key.chop(1);
1 ✔
464
  }
465
  if (key.startsWith(QLatin1String("0x"), Qt::CaseInsensitive)) {
6,718 ✔
466
    key.remove(0, 2);
7 ✔
467
  }
468
  static const QRegularExpression grouped(
469
      QStringLiteral("^[0-9A-Fa-f]{4}(?:\\s+[0-9A-Fa-f]{4})+$"));
6,732 ✔
470
  if (grouped.match(key).hasMatch()) {
6,718 ✔
471
    static const QRegularExpression space(QStringLiteral("\\s"));
6 ✔
472
    key.remove(space);
2 ✔
473
    if (key.size() != 40 && key.size() != 64) {
2 ✔
474
      return {};
×
475
    }
476
  }
477
  static const QRegularExpression hex(QStringLiteral(
7 ✔
478
      "^(?:[0-9A-Fa-f]{8}|[0-9A-Fa-f]{16}|[0-9A-Fa-f]{40}|[0-9A-Fa-f]{64})$"));
6,732 ✔
479
  return hex.match(key).hasMatch() ? key.toUpper() : QString();
7,348 ✔
480
}
481

482
/**
483
 * @brief One key block of a colon listing: its primary fingerprint and
484
 *        name, and the key IDs and fingerprints of the key and its subkeys.
485
 */
486
struct KeyBlock {
487
  QString primary;    ///< Primary fingerprint, upper case.
488
  QString name;       ///< First user ID.
489
  QStringList keyIds; ///< Key IDs of the key and its subkeys.
490
  QStringList fprs;   ///< Fingerprints of the key and its subkeys.
491
};
492

493
/**
494
 * @brief Split a `--with-colons --with-fingerprint
495
 *        --with-subkey-fingerprint` listing into key blocks, once.
496
 * @param listing The listing.
497
 * @return The blocks, in listing order.
498
 */
499
auto keyBlocks(const QString &listing) -> QList<KeyBlock> {
271 ✔
500
  QList<KeyBlock> blocks;
271 ✔
501
  bool expectPrimary = false;
502
  for (const QString &line :
503
       listing.split(Util::newLinesRegex(), Qt::SkipEmptyParts)) {
1,913 ✔
504
    const QStringList f = line.split(QLatin1Char(':'));
1,642 ✔
505
    const QString type = f.value(0);
1,642 ✔
506
    if (type == QLatin1String("pub")) {
1,642 ✔
507
      blocks.append(KeyBlock{});
756 ✔
508
      blocks.last().keyIds << f.value(4).toUpper();
756 ✔
509
      expectPrimary = true;
510
    } else if (blocks.isEmpty()) {
1,264 ✔
511
      continue;
512
    } else if (type == QLatin1String("sub")) {
1,142 ✔
513
      blocks.last().keyIds << f.value(4).toUpper();
498 ✔
514
      expectPrimary = false;
515
    } else if (type == QLatin1String("fpr")) {
893 ✔
516
      const QString fpr = f.value(9).toUpper();
1,142 ✔
517
      blocks.last().fprs << fpr;
571 ✔
518
      if (expectPrimary) {
571 ✔
519
        blocks.last().primary = fpr;
322 ✔
520
        expectPrimary = false;
521
      }
522
    } else if (type == QLatin1String("uid") && blocks.last().name.isEmpty()) {
644 ✔
523
      blocks.last().name = Util::displayable(f.value(9), false);
638 ✔
524
    }
525
  }
526
  return blocks;
271 ✔
527
}
528

529
/**
530
 * @brief How a holder is named: its first user ID and key ID (a v4
531
 *        fingerprint's tail, a v5/v6 one's head).
532
 * @param block The holder.
533
 * @return The name.
534
 */
535
auto holderName(const KeyBlock &block) -> QString {
193 ✔
536
  const QString id = block.primary.size() == 64 ? block.primary.left(16)
193 ✔
537
                                                : block.primary.right(16);
193 ✔
538
  return block.name.isEmpty() ? id
193 ✔
539
                              : QStringLiteral("%1 (%2)").arg(block.name, id);
383 ✔
540
}
541
} // namespace
542

543
auto Pass::fullKeyListing(QString *listing) -> int {
40 ✔
544
  // In the store's environment: the keyring encryption uses.
545
  QProcess process;
40 ✔
546
  process.setProcessEnvironment(storeEnvironment());
40 ✔
547
  return Executor::executeBlocking(
320 ✔
548
      process, m_settings.gpgExecutable,
40 ✔
549
      {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
40 ✔
550
       QStringLiteral("--with-colons"), QStringLiteral("--with-fingerprint"),
40 ✔
551
       QStringLiteral("--with-subkey-fingerprint"),
40 ✔
552
       QStringLiteral("--list-keys")},
40 ✔
553
      QString(), listing);
80 ✔
554
}
40 ✔
555

556
auto Pass::exportPublicKeys(const QString &gpg, const QStringList &keys,
2 ✔
557
                            QString *out, QString *err) -> int {
558
  QProcess process;
2 ✔
559
  process.setProcessEnvironment(storeEnvironment());
2 ✔
560
  return Executor::executeBlocking(
2 ✔
561
      process, gpg,
562
      QStringList{QStringLiteral("--armor"), QStringLiteral("--export")} + keys,
8 ✔
563
      QString(), out, err);
4 ✔
564
}
2 ✔
565

566
auto Pass::refuseKeyLinesHeldTwice(const QStringList &lines) -> bool {
313 ✔
567
  const std::optional<QHash<QString, QStringList>> held =
568
      keyLinesHeldTwice(lines);
313 ✔
569
  if (held && held->isEmpty()) {
313 ✔
570
    return false;
571
  }
572
  emit critical(held ? tr("A recipient key is held twice")
15 ✔
573
                     : tr("Cannot check the recipient keys"),
574
                describeKeyLinesHeldTwice(held));
5 ✔
575
  return true;
5 ✔
576
}
577

578
auto Pass::enabledKeyLines(const QList<UserInfo> &users) -> QStringList {
82 ✔
579
  QStringList lines;
82 ✔
580
  for (const UserInfo &user : users) {
175 ✔
581
    if (user.enabled) {
93 ✔
582
      lines << user.key_id;
92 ✔
583
    }
584
  }
585
  return lines;
82 ✔
586
}
587

588
auto Pass::keyLinesHeldTwice(const QStringList &lines)
363 ✔
589
    -> std::optional<QHash<QString, QStringList>> {
590
  if (std::none_of(lines.cbegin(), lines.cend(), [](const QString &line) {
363 ✔
591
        return !keyOfLine(line).isEmpty();
6,340 ✔
592
      })) {
593
    return QHash<QString, QStringList>();
87 ✔
594
  }
595
  QString listing;
276 ✔
596
  const int rc = fullKeyListing(&listing);
276 ✔
597
  // A gpg that does not start encrypts to nobody either: the operation
598
  // fails on its own, as it did before this check. One that starts but
599
  // cannot list its keyring is not trusted to resolve a key line.
600
  if (rc == -1) {
276 ✔
601
    return QHash<QString, QStringList>();
7 ✔
602
  }
603
  if (rc != 0) {
269 ✔
604
    return std::nullopt;
1 ✔
605
  }
606
  return keyLinesHeldTwiceIn(lines, listing);
268 ✔
607
}
608

609
auto Pass::keyLinesHeldTwiceIn(const QStringList &lines, const QString &listing)
271 ✔
610
    -> QHash<QString, QStringList> {
611
  // The listing split once, each line looked up in it. A line with "!" is
612
  // judged the same: gpg then takes exactly the key named, so it cannot be
613
  // redirected to the other block's own subkey, but naming a key two blocks
614
  // hold is refused all the same, which is only stricter.
615
  const QList<KeyBlock> blocks = keyBlocks(listing);
271 ✔
616
  QHash<QString, QStringList> held;
271 ✔
617
  for (const QString &line : lines) {
649 ✔
618
    const QString key = keyOfLine(line);
378 ✔
619
    if (key.isEmpty()) {
378 ✔
620
      continue;
621
    }
622
    const bool isId = key.size() == 8 || key.size() == 16;
354 ✔
623
    QStringList named;
354 ✔
624
    for (const KeyBlock &block : blocks) {
904 ✔
625
      const bool holds =
626
          isId ? std::any_of(
550 ✔
627
                     block.keyIds.cbegin(), block.keyIds.cend(),
628
                     [&key](const QString &id) { return id.endsWith(key); })
130 ✔
629
               : block.fprs.contains(key);
550 ✔
630
      if (holds) {
550 ✔
631
        named << holderName(block);
386 ✔
632
      }
633
    }
634
    if (named.size() > 1) {
354 ✔
635
      held.insert(line, named);
636
    }
637
  }
638
  return held;
271 ✔
639
}
×
640

641
auto Pass::describeKeyLinesHeldTwice(
7 ✔
642
    const std::optional<QHash<QString, QStringList>> &held) -> QString {
643
  if (!held) {
7 ✔
644
    return tr("gpg could not list the keyring, so QtPass cannot tell whether "
645
              "each key ID and fingerprint in the recipient list names one "
646
              "key. Nothing was encrypted.");
647
  }
648
  QStringList lines = held->keys();
6 ✔
649
  lines.sort();
650
  QStringList parts;
6 ✔
651
  for (const QString &line : std::as_const(lines)) {
12 ✔
652
    parts << tr("%1 is held by more than one key: %2")
6 ✔
653
                 .arg(line, held->value(line).join(QStringLiteral(", ")));
12 ✔
654
  }
655
  return parts.join(QStringLiteral("\n")) + QStringLiteral("\n\n") +
12 ✔
656
         tr("gpg may encrypt to any of them, so nothing is encrypted to this "
6 ✔
657
            "list. A key that holds someone else's key as a subkey was "
658
            "made to do so: look at it, and delete it if you did not expect "
659
            "it.");
6 ✔
660
}
661

662
auto Pass::entryReaders(const QString &path) -> QStringList {
10 ✔
663
  // As ImitatePass::getKeysFromFile(): --decrypt --list-only, capped, so
664
  // data that is not encrypted goes nowhere.
665
  QProcess process;
10 ✔
666
  process.setProcessEnvironment(storeEnvironment());
10 ✔
667
  QString status;
10 ✔
668
  if (Executor::executeBlocking(
120 ✔
669
          process, m_settings.gpgExecutable,
670
          {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
10 ✔
671
           QStringLiteral("--decrypt"), QStringLiteral("--list-only"),
10 ✔
672
           QStringLiteral("--max-output"), QStringLiteral("1"),
10 ✔
673
           QStringLiteral("--status-fd=1"),
10 ✔
674
           QStringLiteral("--keyid-format=long"), QStringLiteral("--"),
10 ✔
675
           Executor::translatePathForWsl(path, m_settings.gpgExecutable)},
10 ✔
676
          QString(), &status) != 0) {
20 ✔
677
    return {};
×
678
  }
679
  static const QRegularExpression encTo(
680
      QStringLiteral("^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
12 ✔
681
  QStringList ids;
10 ✔
682
  for (const QString &line :
683
       status.split(Util::newLinesRegex(), Qt::SkipEmptyParts)) {
33 ✔
684
    const QRegularExpressionMatch match = encTo.match(line);
13 ✔
685
    if (match.hasMatch()) {
13 ✔
686
      ids << match.captured(1).toUpper();
26 ✔
687
    }
688
  }
13 ✔
689
  return ids;
690
}
20 ✔
691

692
auto Pass::exactRecipientArg(const QString &line) -> QString {
6,427 ✔
693
  static const QRegularExpression bareAddress(
694
      QStringLiteral("^[^=<>@*+#&\\s][^<>@\\s]*@[^<>@\\s]+$"));
6,437 ✔
695
  return bareAddress.match(line).hasMatch()
6,427 ✔
696
             ? QLatin1Char('<') + line + QLatin1Char('>')
6,427 ✔
697
             : line;
6,442 ✔
698
}
699

700
auto Pass::recipientArgument(const QString &line) const -> QString {
6,164 ✔
701
  return exactRecipientArg(line);
6,164 ✔
702
}
703

704
auto Pass::encryptionReaches(const QStringList &recipients)
87 ✔
705
    -> std::optional<QStringList> {
706
  if (recipients.isEmpty()) {
87 ✔
707
    return std::nullopt;
×
708
  }
709
  QTemporaryDir scratch;
87 ✔
710
  if (!scratch.isValid()) {
87 ✔
711
    return std::nullopt;
×
712
  }
713
  const QString &gpg = m_settings.gpgExecutable;
87 ✔
714
  const QString probe = Executor::translatePathForWsl(
715
      scratch.filePath(QStringLiteral("probe.gpg")), gpg);
174 ✔
716
  // --no-throw-keyids: with throw-keyids in gpg.conf the probe would name
717
  // no one.
718
  QStringList args{QStringLiteral("--batch"),
174 ✔
719
                   QStringLiteral("--no-tty"),
87 ✔
720
                   QStringLiteral("--yes"),
87 ✔
721
                   QStringLiteral("--quiet"),
87 ✔
722
                   QStringLiteral("--no-throw-keyids"),
87 ✔
723
                   QStringLiteral("--no-auto-key-locate"),
87 ✔
724
                   QStringLiteral("--no-encrypt-to"),
87 ✔
725
                   QStringLiteral("--output"),
87 ✔
726
                   probe,
727
                   QStringLiteral("--encrypt")};
1,044 ✔
728
  for (const QString &recipient : recipients) {
6,262 ✔
729
    args << QStringLiteral("-r") << recipientArgument(recipient);
12,350 ✔
730
  }
731
  if (Executor::executeBlocking(gpg, args, QStringLiteral("probe")) != 0) {
174 ✔
732
    return std::nullopt;
21 ✔
733
  }
734
  // As ImitatePass::getKeysFromFile(): --decrypt --list-only, capped.
735
  QString status;
66 ✔
736
  if (Executor::executeBlocking(
792 ✔
737
          gpg,
738
          {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
66 ✔
739
           QStringLiteral("--decrypt"), QStringLiteral("--list-only"),
66 ✔
740
           QStringLiteral("--max-output"), QStringLiteral("1"),
66 ✔
741
           QStringLiteral("--status-fd=1"),
66 ✔
742
           QStringLiteral("--keyid-format=long"), QStringLiteral("--"), probe},
66 ✔
743
          QString(), &status) != 0) {
132 ✔
744
    return QStringList();
×
745
  }
746
  static const QRegularExpression encTo(
747
      QStringLiteral("^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
74 ✔
748
  QStringList ids;
66 ✔
749
  for (const QString &line :
750
       status.split(Util::newLinesRegex(), Qt::SkipEmptyParts)) {
366 ✔
751
    const QRegularExpressionMatch match = encTo.match(line);
234 ✔
752
    if (match.hasMatch()) {
234 ✔
753
      ids << match.captured(1).toUpper();
32 ✔
754
    }
755
  }
234 ✔
756
  return ids;
757
}
87 ✔
758

759
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
203 ✔
760
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
1,421 ✔
761
  args.append(secret ? "--list-secret-keys" : "--list-keys");
535 ✔
762

763
  for (const QString &keystring : std::as_const(keystrings)) {
6,482 ✔
764
    if (!keystring.isEmpty()) {
6,279 ✔
765
      args.append(keystring);
766
    }
767
  }
768
  QString p_out;
203 ✔
769
  if (Executor::executeBlocking(m_settings.gpgExecutable, args, &p_out) != 0) {
203 ✔
770
    return {};
6 ✔
771
  }
772
  return parseGpgColonOutput(p_out, secret);
197 ✔
773
}
774

775
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
159 ✔
776
  return listKeys(QStringList(keystring), secret);
318 ✔
777
}
778

779
namespace {
780

781
auto containsAny(const QString &str, const QStringList &patterns) -> bool {
130 ✔
782
  for (const QString &p : patterns) {
360 ✔
783
    if (str.contains(p)) {
252 ✔
784
      return true;
785
    }
786
  }
787
  return false;
788
}
789

790
// @p patterns must already be lowercase; only @p str is lowered.
791
auto containsAnyCaseInsensitive(const QString &str, const QStringList &patterns)
107 ✔
792
    -> bool {
793
  const QString lower = str.toLower();
794
  for (const QString &p : patterns) {
265 ✔
795
    if (lower.contains(p)) {
169 ✔
796
      return true;
797
    }
798
  }
799
  return false;
800
}
801

802
} // namespace
803

804
auto gpgErrorMessage(const QString &err) -> QString {
48 ✔
805
  // Machine-readable status tokens added by --status-fd 2
806
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYEXPIRED"),
240 ✔
807
                        QStringLiteral("[GNUPG:] INV_RECP 5 ")}))
48 ✔
808
    return QCoreApplication::translate(
809
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
810
                "replace it.");
5 ✔
811
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYREVOKED"),
215 ✔
812
                        QStringLiteral("[GNUPG:] INV_RECP 4 ")}))
43 ✔
813
    return QCoreApplication::translate(
814
        "Pass", "Encryption failed: GPG key has been revoked.");
4 ✔
815
  if (containsAny(err, {QStringLiteral("[GNUPG:] NO_PUBKEY"),
195 ✔
816
                        QStringLiteral("[GNUPG:] INV_RECP")}))
39 ✔
817
    return QCoreApplication::translate(
818
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
819
                "Check that the key ID in .gpg-id is correct and imported.");
13 ✔
820
  if (err.contains(QStringLiteral("[GNUPG:] FAILURE")))
26 ✔
821
    return QCoreApplication::translate(
822
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
823

824
  // Locale-dependent fallbacks
825
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has expired"),
100 ✔
826
                                       QLatin1String("key expired")}))
827
    return QCoreApplication::translate(
828
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
829
                "replace it.");
1 ✔
830
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has been revoked"),
96 ✔
831
                                       QLatin1String("revoked")}))
832
    return QCoreApplication::translate(
833
        "Pass", "Encryption failed: GPG key has been revoked.");
1 ✔
834
  // pass passes no --status-fd, so this is all gpg says about a key that is
835
  // present but cannot encrypt: expired, revoked, without an encryption
836
  // subkey, or not trusted ("There is no assurance this key belongs to the
837
  // named user"). "Not found ... imported" would send the user the wrong
838
  // way; gpg's own lines, shown below this, say which it is.
839
  if (containsAnyCaseInsensitive(err, {QLatin1String("unusable public key")}))
69 ✔
840
    return QCoreApplication::translate(
841
        "Pass", "Encryption failed: a recipient's GPG key cannot be used. It "
842
                "may have expired or been revoked, have no encryption subkey, "
843
                "or not be trusted; gpg's message below says which.");
3 ✔
844
  if (containsAnyCaseInsensitive(err, {QLatin1String("no public key"),
80 ✔
845
                                       QLatin1String("no secret key")}))
846
    return QCoreApplication::translate(
847
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
848
                "Check that the key ID in .gpg-id is correct and imported.");
5 ✔
849
  if (containsAnyCaseInsensitive(err, {QLatin1String("encryption failed")}))
45 ✔
850
    return QCoreApplication::translate(
851
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
852

853
  return {};
14 ✔
854
}
×
855

856
void Pass::finished(int id, int exitCode, const QString &out,
332 ✔
857
                    const QString &err) {
858
  auto pid = static_cast<PROCESS>(id);
332 ✔
859

860
  // Pop the Show() this completion belongs to whether it worked or not, or
861
  // the next result would be attributed to the wrong file.
862
  QString shownFile;
332 ✔
863
  if (pid == PASS_SHOW && !m_pendingShows.isEmpty()) {
332 ✔
864
    shownFile = m_pendingShows.dequeue();
82 ✔
865
  }
866
  // Count this insert off, success or failure, before its result goes out, so
867
  // insertsPending() tracks the inserts still awaiting a report. Each insert
868
  // reaches here once as PASS_INSERT.
869
  // Its entry is handed out (reportedInsert()) while the report goes out.
870
  QString reported;
332 ✔
871
  if (pid == PASS_INSERT && m_insertsPending > 0) {
332 ✔
872
    --m_insertsPending;
124 ✔
873
    if (!m_insertedEntries.isEmpty()) {
124 ✔
874
      reported = m_insertedEntries.dequeue();
124 ✔
875
    }
876
  }
877
  m_reportedInsert = reported;
332 ✔
878
  const auto reportedOut = qScopeGuard([this] { m_reportedInsert.clear(); });
332 ✔
879

880
  if (exitCode != 0) {
332 ✔
881
    handleProcessError(pid, exitCode, out, err);
67 ✔
882
    return;
883
  }
884

885
  if (pid == PASS_SHOW) {
265 ✔
886
    emit finishedShow(out, shownFile, exec.lastOutputLossless());
51 ✔
887
    return;
888
  }
889
  emitProcessFinishedSignal(pid, out, err);
214 ✔
890
}
891

892
void Pass::handleProcessError(PROCESS pid, int exitCode, const QString &out,
67 ✔
893
                              const QString &err) {
894
  Q_UNUSED(out);
895

896
  if (pid == PASS_INSERT) {
67 ✔
897
    const QString friendly = gpgErrorMessage(err);
20 ✔
898
    const QString why =
899
        friendly.isEmpty() ? err : formatInsertError(friendly, err);
20 ✔
900
    const bool written = insertWritten(err);
20 ✔
901
    emit insertFailed(why, written);
20 ✔
902
    if (written) {
20 ✔
903
      // The entry is in the store; a git step after it failed (a commit
904
      // that could not be signed, with pass.signcommits, say). The dialog
905
      // closes on this, so say it here rather than only in the output
906
      // panel.
907
      emit critical(tr("Saved, not committed"),
10 ✔
908
                    tr("The entry is saved in the store, but recording it "
5 ✔
909
                       "in git failed. What was reported:\n\n%1")
910
                        .arg(err.trimmed()));
10 ✔
911
    }
912
    emit processErrorExit(exitCode, why);
20 ✔
913
    return;
914
  }
915

916
  if (pid == GPG_GENKEYS) {
47 ✔
917
    emit generateGPGKeysFailed(err);
1 ✔
918
  }
919
  emit processErrorExit(exitCode, err);
47 ✔
920
}
921

922
auto Pass::withoutStatusLines(const QString &err) -> QString {
54 ✔
923
  QStringList humanLines;
54 ✔
924
  for (const QString &line : err.split('\n')) {
1,655 ✔
925
    QString cleanedLine = line;
926
    cleanedLine.remove('\r');
1,547 ✔
927
    if (!cleanedLine.startsWith(QLatin1String("[GNUPG:]")))
1,547 ✔
928
      humanLines.append(cleanedLine);
929
  }
930
  return humanLines.join('\n');
54 ✔
931
}
932

933
auto Pass::formatInsertError(const QString &friendly, const QString &err)
7 ✔
934
    -> QString {
935
  const QString humanErr = withoutStatusLines(err).trimmed();
14 ✔
936
  return humanErr.isEmpty() ? friendly : friendly + "\n\n" + humanErr;
14 ✔
937
}
938

939
void Pass::emitProcessFinishedSignal(PROCESS pid, const QString &out,
214 ✔
940
                                     const QString &err) {
941
  // Only output that cannot contain a secret reaches the generic listeners
942
  // (the output panel among them); Enums::processInfo is the one table.
943
  if (pid >= 0 && pid < Enums::PROCESS_COUNT &&
214 ✔
944
      !Enums::processInfo(pid).secret) {
212 ✔
945
    emit finishedAnyWithPid(out, err, pid);
101 ✔
946
  }
947

948
  // The kind-specific signal. PASS_SHOW is emitted by finished(), which
949
  // knows the file. Content search runs in-process (NativeGrep), not
950
  // through `pass grep`, and emits finishedGrep itself.
951
  using Signal = void (Pass::*)(const QString &, const QString &);
952
  static const QHash<int, Signal> kSignals{
953
      {GIT_INIT, &Pass::finishedGitInit},
954
      {GIT_PULL, &Pass::finishedGitPull},
955
      {GIT_PUSH, &Pass::finishedGitPush},
956
      {PASS_INSERT, &Pass::finishedInsert},
957
      {PASS_REMOVE, &Pass::finishedRemove},
958
      {PASS_INIT, &Pass::finishedInit},
959
      {PASS_MOVE, &Pass::finishedMove},
960
      {PASS_COPY, &Pass::finishedCopy},
961
      {GPG_GENKEYS, &Pass::finishedGenerateGPGKeys},
962
  };
220 ✔
963
  // A store that became a repository after updateEnv() gets its pin now,
964
  // before anything is staged in it.
965
  if (pid == GIT_INIT) {
214 ✔
966
    pinStoreGitAttributes();
3 ✔
967
  }
968
  if (const Signal signal = kSignals.value(pid, nullptr)) {
214 ✔
969
    (this->*signal)(out, err);
210 ✔
970
  }
971
}
214 ✔
972

973
void Pass::setEnvVar(const QString &name, const QString &value) {
4,501 ✔
974
  if (value.isEmpty())
4,501 ✔
975
    env.remove(name);
1,491 ✔
976
  else
977
    env.insert(name, value);
3,010 ✔
978
}
4,501 ✔
979

980
void Pass::updateEnv() {
499 ✔
981
  setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY"),
998 ✔
982
            m_settings.passSigningKey);
499 ✔
983
  setEnvVar(QStringLiteral("PASSWORD_STORE_DIR"), m_settings.passStore);
998 ✔
984
  // Every path QtPass hands git names one file or folder: an entry called
985
  // "a*.gpg" must not make `git rm -f -- a*.gpg` remove every entry that
986
  // matches. Also reaches the git that pass runs, which passes names the
987
  // same way.
988
  setEnvVar(QStringLiteral("GIT_LITERAL_PATHSPECS"), QStringLiteral("1"));
998 ✔
989

990
  const PasswordConfiguration &passConfig = m_settings.passwordConfiguration;
499 ✔
991
  setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH"),
998 ✔
992
            QString::number(passConfig.length));
499 ✔
993

994
  setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET"),
998 ✔
995
            effectiveCharset(passConfig));
499 ✔
996

997
  // pass hands PASSWORD_STORE_GPG_OPTS to every gpg it runs: the user's own
998
  // options (split as pass's shell splits them: spaces, tabs, newlines),
999
  // then the output limit ImitatePass passes directly.
1000
  QStringList gpgOpts = QProcessEnvironment::systemEnvironment()
499 ✔
1001
                            .value(QStringLiteral("PASSWORD_STORE_GPG_OPTS"))
998 ✔
1002
                            .split(QRegularExpression(QStringLiteral("\\s+")),
998 ✔
1003
                                   Qt::SkipEmptyParts);
998 ✔
1004
  gpgOpts << maxOutputArgs();
998 ✔
1005
  setEnvVar(QStringLiteral("PASSWORD_STORE_GPG_OPTS"),
998 ✔
1006
            gpgOpts.join(QLatin1Char(' ')));
499 ✔
1007

1008
  // As pass does: git never looks for a repository above the store's own
1009
  // parent. A store that is not a repository itself but lies inside one (a
1010
  // dotfiles repository in the home folder) would otherwise have its entries
1011
  // committed and pushed there by native git mode. Only in the environment
1012
  // of the processes QtPass runs for the store, never QtPass's own, which a
1013
  // file manager or terminal it opens would inherit. pass sets its own
1014
  // ceiling whatever this says. A store kept inside a larger repository on
1015
  // purpose opts out (gitUseParentRepository), and then, as without a
1016
  // store, whatever ceiling QtPass was started with applies.
1017
  // A ceiling git cannot take as one entry (the parent's path holds the
1018
  // list separator) is backed by GIT_DIR and GIT_WORK_TREE naming the
1019
  // store's own repository (Util::gitStoreVariables()); pass unsets those
1020
  // for itself and keeps its own ceiling.
1021
  setEnvVar(QStringLiteral("GIT_DIR"), QString());
998 ✔
1022
  setEnvVar(QStringLiteral("GIT_WORK_TREE"), QString());
998 ✔
1023
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
499 ✔
1024
    setEnvVar(QStringLiteral("GIT_CEILING_DIRECTORIES"),
40 ✔
1025
              qEnvironmentVariable("GIT_CEILING_DIRECTORIES"));
40 ✔
1026
  } else {
1027
    for (const auto &[name, value] : Util::gitStoreVariables(
1028
             m_settings.passStore, m_settings.gitExecutable)) {
1,441 ✔
1029
      setEnvVar(name, value);
483 ✔
1030
    }
1031
  }
1032

1033
  // Refuse a repository pushed into the store: git started in a folder laid
1034
  // out as a bare repository would read its pushed config and run a command
1035
  // named there. This reaches the git that pass runs too, which inherits the
1036
  // environment.
1037
  Util::requireExplicitBareRepository(env);
499 ✔
1038
  // pass under WSL needs them too: the count and every entry below it.
1039
  QStringList gitConfig{QStringLiteral("GIT_CONFIG_COUNT/u")};
998 ✔
1040
  if (env.contains(QStringLiteral("GIT_CONFIG_PARAMETERS"))) {
998 ✔
1041
    gitConfig << QStringLiteral("GIT_CONFIG_PARAMETERS/u");
×
1042
  }
1043
  const int gitConfigCount =
1044
      env.value(QStringLiteral("GIT_CONFIG_COUNT")).toInt();
998 ✔
1045
  for (int i = 0; i < gitConfigCount; ++i) {
998 ✔
1046
    gitConfig << QStringLiteral("GIT_CONFIG_KEY_%1/u").arg(i)
998 ✔
1047
              << QStringLiteral("GIT_CONFIG_VALUE_%1/u").arg(i);
998 ✔
1048
  }
1049
  mergeIntoWslenv(env, gitConfig);
499 ✔
1050

1051
  exec.setEnvironment(env);
499 ✔
1052

1053
  pinStoreGitAttributes();
499 ✔
1054
}
499 ✔
1055

1056
namespace {
1057
/**
1058
 * @brief The lines of an `info/attributes` file outside the QtPass block:
1059
 *        the block's own lines after @p marker are dropped, and the
1060
 *        trailing blank lines but one.
1061
 * @param existing The file's text; empty when it does not exist.
1062
 * @param marker The line that opens the QtPass block.
1063
 * @return The lines to keep, each ending in a newline; empty for none.
1064
 */
1065
auto userAttributeLines(const QString &existing, const QString &marker)
9 ✔
1066
    -> QString {
1067
  QString preserved;
9 ✔
1068
  if (existing.isEmpty()) {
9 ✔
1069
    return preserved;
1070
  }
NEW
1071
  const QStringList lines = existing.split(QLatin1Char('\n'));
×
1072
  bool inBlock = false;
NEW
1073
  for (const QString &line : lines) {
×
NEW
1074
    if (line == marker) {
×
1075
      inBlock = true;
NEW
1076
      continue;
×
1077
    }
NEW
1078
    if (inBlock) {
×
NEW
1079
      if (line.startsWith(QStringLiteral("*.gpg ")) ||
×
NEW
1080
          line.startsWith(QStringLiteral(".gpg-id ")) ||
×
NEW
1081
          line.startsWith(QStringLiteral(".gpg-id.sig "))) {
×
NEW
1082
        continue;
×
1083
      }
1084
      inBlock = false;
1085
    }
NEW
1086
    preserved += line + QLatin1Char('\n');
×
1087
  }
NEW
1088
  while (preserved.endsWith(QStringLiteral("\n\n"))) {
×
NEW
1089
    preserved.chop(1);
×
1090
  }
1091
  return preserved;
1092
}
1093
} // namespace
1094

1095
void Pass::pinStoreGitAttributes() {
502 ✔
1096
  if (m_settings.passStore.isEmpty()) {
502 ✔
1097
    return;
493 ✔
1098
  }
1099
  // Only the common layout, where the store is its own repository, is handled
1100
  // by writing directly: a ".git" directory. A worktree ".git" file or a store
1101
  // nested in a larger repository is left as-is rather than risk touching
1102
  // another repository's attributes.
1103
  const QString gitDir =
1104
      QDir(m_settings.passStore).absoluteFilePath(QStringLiteral(".git"));
976 ✔
1105
  if (!QFileInfo(gitDir).isDir()) {
488 ✔
1106
    return;
1107
  }
1108

1109
  // The marker lets us recognise and refresh our own block without disturbing
1110
  // anything a user put in info/attributes by hand. Disabling text/eol,
1111
  // working-tree-encoding, filter and ident keeps Git from rewriting the
1112
  // bytes gpg produced for these paths - a co-writer can push a .gitattributes
1113
  // ("*.gpg text", a working-tree-encoding, a filter) that otherwise corrupts
1114
  // the ciphertext QtPass commits. info/attributes outranks the in-tree file.
1115
  // diff is left alone: it only changes what Git shows, and pass's own
1116
  // "*.gpg diff=gpg" gives decrypted diffs.
1117
  static const QString marker =
1118
      QStringLiteral("# QtPass: keep encrypted store files byte-for-byte");
53 ✔
1119
  const QString block =
1120
      marker + QStringLiteral("\n") +
98 ✔
1121
      QStringLiteral(
98 ✔
1122
          "*.gpg -text -filter -ident -working-tree-encoding\n"
1123
          ".gpg-id -text -filter -ident -working-tree-encoding\n"
1124
          ".gpg-id.sig -text -filter -ident -working-tree-encoding\n");
1125

1126
  const QString infoDir = gitDir + QStringLiteral("/info");
98 ✔
1127
  const QString attrPath = infoDir + QStringLiteral("/attributes");
98 ✔
1128

1129
  QString existing;
49 ✔
1130
  QFile attr(attrPath);
49 ✔
1131
  if (attr.exists()) {
49 ✔
1132
    // Unreadable: writing now would drop the user's own lines in it.
1133
    if (!attr.open(QIODevice::ReadOnly | QIODevice::Text)) {
40 ✔
1134
      qCWarning(lcQtPass) << "Cannot read" << attrPath
×
1135
                          << "to pin attributes:" << attr.errorString();
×
1136
      return;
×
1137
    }
1138
    existing = QString::fromUtf8(attr.readAll());
40 ✔
1139
    attr.close();
40 ✔
1140
    if (existing.contains(block)) {
40 ✔
1141
      return; // already pinned and unchanged
1142
    }
1143
  }
1144

1145
  if (!QDir().mkpath(infoDir)) {
18 ✔
1146
    qCWarning(lcQtPass) << "Cannot create" << infoDir << "to pin attributes";
×
1147
    return;
×
1148
  }
1149

1150
  // Keep any lines the user added themselves (outside our block), then append a
1151
  // fresh copy of our block. A previous QtPass block is dropped so an updated
1152
  // set of lines replaces an older one.
1153
  const QString preserved = userAttributeLines(existing, marker);
9 ✔
1154

1155
  QSaveFile out(attrPath);
9 ✔
1156
  const QByteArray payload = (preserved + block).toUtf8();
9 ✔
1157
  if (!out.open(QIODevice::WriteOnly | QIODevice::Text) ||
18 ✔
1158
      out.write(payload) != payload.size() || !out.commit()) {
18 ✔
1159
    qCWarning(lcQtPass) << "Cannot write" << attrPath
×
1160
                        << "to pin attributes:" << out.errorString();
×
1161
  }
1162
}
58 ✔
1163

1164
auto Pass::withCurrentGitPin(QProcessEnvironment base) const
2,085 ✔
1165
    -> QProcessEnvironment {
1166
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
2,085 ✔
1167
    return base;
17 ✔
1168
  }
1169
  base.remove(QStringLiteral("GIT_DIR"));
4,136 ✔
1170
  base.remove(QStringLiteral("GIT_WORK_TREE"));
4,136 ✔
1171
  for (const auto &[name, value] : Util::gitStoreVariables(
1172
           m_settings.passStore, m_settings.gitExecutable)) {
6,214 ✔
1173
    base.insert(name, value);
2,078 ✔
1174
  }
1175
  return base;
2,068 ✔
1176
}
1177

1178
auto Pass::maxOutputArgs() -> QStringList {
1,205 ✔
1179
  return {QStringLiteral("--max-output"), QString::number(kMaxPlaintextBytes)};
3,615 ✔
1180
}
1,205 ✔
1181

1182
namespace {
1183
/// File names compare the way the platform's file system compares them:
1184
/// "C:/Store" and "c:/store" are the same directory on Windows.
1185
#ifdef Q_OS_WIN
1186
constexpr auto kPathCase = Qt::CaseInsensitive;
1187
#else
1188
constexpr auto kPathCase = Qt::CaseSensitive;
1189
#endif
1190

1191
/// Whether @p path is @p dir or lies under it.
1192
auto isAtOrUnder(const QString &path, const QString &dir,
4,363 ✔
1193
                 const QString &dirPrefix) -> bool {
1194
  return path.compare(dir, kPathCase) == 0 ||
7,854 ✔
1195
         path.startsWith(dirPrefix, kPathCase);
3,491 ✔
1196
}
1197

1198
/// Where the lookup of a .gpg-id starts and the store that bounds it.
1199
struct GpgIdLookup {
1200
  QDir start;
1201
  /// The folder whose list is wanted, whether it exists or not.
1202
  QString folder;
1203
  QString storeDir;
1204
  QString storePrefix;
1205
};
1206

1207
/// The folder whose list @p for_file wants: its own for a folder, its
1208
/// folder's for an entry.
1209
auto gpgIdLookup(const QString &for_file, const QString &passStore)
1,308 ✔
1210
    -> GpgIdLookup {
1211
  const QString normalizedFile = QDir::fromNativeSeparators(for_file);
1,308 ✔
1212
  // Inside the store means at a path boundary: "/store-other/x" is not
1213
  // under "/store", however the prefix compares.
1214
  const QString storeDir =
1215
      QDir::cleanPath(QDir::fromNativeSeparators(passStore));
1,308 ✔
1216
  const QString storePrefix = storeDir.endsWith(QLatin1Char('/'))
1,308 ✔
1217
                                  ? storeDir
1,308 ✔
1218
                                  : storeDir + QLatin1Char('/');
1,308 ✔
1219
  const QString cleanFile = QDir::cleanPath(normalizedFile);
1,308 ✔
1220
  const bool insideStore = isAtOrUnder(cleanFile, storeDir, storePrefix);
1,308 ✔
1221
  // A relative name is one inside the store; an absolute path outside it
1222
  // stays what it is and the walk stops at once.
1223
  const QString fullPath =
1224
      insideStore || (QDir::isAbsolutePath(cleanFile) &&
21 ✔
1225
                      !cleanFile.startsWith(QLatin1Char(':')))
5 ✔
1226
          ? cleanFile
1,308 ✔
1227
          : storePrefix + cleanFile;
11 ✔
1228
  // A folder (trailing separator, which cleanPath() dropped, or an existing
1229
  // directory) wants its own list; an entry wants its folder's.
1230
  const bool isFolder =
1231
      normalizedFile.endsWith(QLatin1Char('/')) || QFileInfo(fullPath).isDir();
1,308 ✔
1232
  // A folder that does not exist yet (an entry saved into a new folder, a
1233
  // move to one) starts the walk at its nearest existing ancestor in the
1234
  // store, as pass's set_gpg_recipients does: otherwise the walk ended at
1235
  // once and the store root's list was taken over the one in between.
1236
  const QString folder =
1237
      QDir::cleanPath(isFolder ? fullPath : QFileInfo(fullPath).absolutePath());
3,317 ✔
1238
  QString start = folder;
1239
  while (!QFileInfo(start).exists() &&
1,344 ✔
1240
         isAtOrUnder(QDir::cleanPath(start), storeDir, storePrefix) &&
2,670 ✔
1241
         QDir::cleanPath(start) != storeDir) {
1,344 ✔
1242
    start = QFileInfo(start).absolutePath();
36 ✔
1243
  }
1244
  return {QDir(start), folder, storeDir, storePrefix};
1,308 ✔
1245
}
1,308 ✔
1246

1247
/// Whether @p candidate can be its folder's .gpg-id: a regular file, as
1248
/// pass looks for (test -f), so a folder under the name is passed over as
1249
/// pass passes it. A link under the name is not: whoever planted it chose
1250
/// the recipients elsewhere.
1251
auto isOwnGpgId(const QFileInfo &candidate) -> bool {
2,364 ✔
1252
  return candidate.isFile() && !candidate.isSymLink() &&
3,034 ✔
1253
         !candidate.isJunction();
670 ✔
1254
}
1255

1256
/// Walk up from the lookup's start to the first folder inside the store
1257
/// that has its own .gpg-id; nothing when none does. A link under the name
1258
/// is skipped, so the parent's list applies instead.
1259
auto nearestGpgId(const GpgIdLookup &lookup) -> std::optional<QString> {
717 ✔
1260
  QDir dir = lookup.start;
717 ✔
1261
  while (dir.exists() && isAtOrUnder(QDir::cleanPath(dir.absolutePath()),
4,328 ✔
1262
                                     lookup.storeDir, lookup.storePrefix)) {
1,082 ✔
1263
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
931 ✔
1264
    if (isOwnGpgId(candidate)) {
931 ✔
1265
      return candidate.absoluteFilePath();
566 ✔
1266
    }
1267
    if (!dir.cdUp()) {
365 ✔
1268
      break;
1269
    }
1270
  }
931 ✔
1271
  return std::nullopt;
151 ✔
1272
}
717 ✔
1273

1274
} // namespace
1275

1276
auto Pass::heldScopes() -> QSet<QString> & {
278 ✔
1277
  static QSet<QString> scopes;
284 ✔
1278
  return scopes;
278 ✔
1279
}
1280

1281
auto Pass::scopePath(const QString &path) const -> QString {
278 ✔
1282
  return QDir::cleanPath(QDir(m_settings.passStore).absoluteFilePath(path));
556 ✔
1283
}
1284

1285
auto Pass::autoPushHeld() const -> bool {
68 ✔
1286
  const QString store = scopePath(QString());
68 ✔
1287
  const QSet<QString> &scopes = heldScopes();
68 ✔
1288
  return std::any_of(scopes.cbegin(), scopes.cend(),
68 ✔
1289
                     [&store](const QString &s) {
183 ✔
1290
                       return isAtOrUnder(s, store, store + QLatin1Char('/'));
366 ✔
1291
                     });
68 ✔
1292
}
1293

1294
void Pass::GitPushAutomatic() {
15 ✔
1295
  m_pushIsAutomatic = true;
15 ✔
1296
  GitPush();
15 ✔
1297
  m_pushIsAutomatic = false;
15 ✔
1298
}
15 ✔
1299

1300
auto Pass::pushIsAutomatic() const -> bool { return m_pushIsAutomatic; }
10 ✔
1301

1302
void Pass::holdAutoPush(const QString &scope) {
105 ✔
1303
  heldScopes().insert(scopePath(scope));
105 ✔
1304
}
105 ✔
1305

1306
void Pass::releaseAutoPush(const QString &folder) {
105 ✔
1307
  const QString root = scopePath(folder);
105 ✔
1308
  QSet<QString> &scopes = heldScopes();
105 ✔
1309
  for (auto it = scopes.begin(); it != scopes.end();) {
1310
    it = isAtOrUnder(*it, root, root + QLatin1Char('/')) ? scopes.erase(it)
1,260 ✔
1311
                                                         : std::next(it);
630 ✔
1312
  }
1313
}
105 ✔
1314

1315
auto Pass::refuseLinkedPath(const QString &path, LinkScope scope,
825 ✔
1316
                            PathSpelling spelling) -> bool {
1317
  const QString full = Util::joinPath(m_settings.passStore, path);
825 ✔
1318
  // The link check below walks only under the store as configured: a path
1319
  // spelled through the root's link target would get no more than the
1320
  // entry itself judged. No caller makes one; say so if one starts to.
1321
  if (spelling == PathSpelling::Configured &&
1,355 ✔
1322
      PathValidator::isTargetSpelled(m_settings.passStore, full)) {
530 ✔
1323
    qCWarning(lcQtPass)
4 ✔
1324
        << "Path spelled through the store root's link target, not as the "
1325
           "store is configured; Pass operations expect the configured "
1326
           "spelling:"
2 ✔
1327
        << full;
2 ✔
1328
  }
1329
  if (!Util::isUnderLink(full, m_settings.passStore,
825 ✔
1330
                         scope == LinkScope::EntryAndParents)) {
1331
    return false;
1332
  }
1333
  const QString why =
1334
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
×
1335
         "points to is not part of the password store and is left alone.")
1336
          .arg(QDir::toNativeSeparators(QDir::cleanPath(full)));
62 ✔
1337
  refuseAsNotPartOfStore(why);
31 ✔
1338
  return true;
1339
}
1340

1341
auto Pass::refuseFolderOutsideStore(const QString &folder, QString *relative)
96 ✔
1342
    -> bool {
1343
  if (const std::optional<QString> inStore =
96 ✔
1344
          PathValidator::storeRelativePath(m_settings.passStore, folder)) {
96 ✔
1345
    if (relative != nullptr) {
91 ✔
1346
      *relative = *inStore;
91 ✔
1347
    }
1348
    return false;
1349
  }
1350
  refuseAsNotPartOfStore(
5 ✔
1351
      tr("%1 is not inside the password store. Recipients are set for the "
5 ✔
1352
         "store or a folder in it.")
1353
          .arg(QDir::toNativeSeparators(QDir::cleanPath(folder))));
10 ✔
1354
  return true;
5 ✔
1355
}
1356

1357
auto Pass::unfinishedGitOperationReason() -> QString {
833 ✔
1358
  if (!m_settings.useGit) {
833 ✔
1359
    return {};
620 ✔
1360
  }
1361
  // One git call names the path of each marker file or directory, whether or
1362
  // not it exists; the backend runs it in the store (ImitatePass with
1363
  // `-C <store>`, RealPass through `pass git`). The markers, paired with the
1364
  // operation each one means, in the order git prints them back.
1365
  // The names are Git's own commands, which the user then runs with --abort or
1366
  // --continue; the translator comments say so.
1367
  const std::array<std::pair<QLatin1String, QString>, 6> markers{{
1368
      //: The Git command `git rebase`, inserted into "in the middle of a %1".
1369
      //: Best kept as Git's command name.
1370
      {QLatin1String("rebase-merge"), tr("rebase")},
213 ✔
1371
      //: The Git command `git rebase`, inserted into "in the middle of a %1".
1372
      //: Best kept as Git's command name.
1373
      {QLatin1String("rebase-apply"), tr("rebase")},
213 ✔
1374
      //: The Git command `git merge`, inserted into "in the middle of a %1".
1375
      //: Best kept as Git's command name.
1376
      {QLatin1String("MERGE_HEAD"), tr("merge")},
213 ✔
1377
      //: The Git command `git cherry-pick`, inserted into "in the middle of a
1378
      //: %1". Best kept as Git's command name.
1379
      {QLatin1String("CHERRY_PICK_HEAD"), tr("cherry-pick")},
213 ✔
1380
      //: The Git command `git revert`, inserted into "in the middle of a %1".
1381
      //: Best kept as Git's command name.
1382
      {QLatin1String("REVERT_HEAD"), tr("revert")},
213 ✔
1383
      // A multi-commit cherry-pick or revert keeps its sequencer state after a
1384
      // conflict resolution is committed, when CHERRY_PICK_HEAD/REVERT_HEAD is
1385
      // already gone but `--continue` has more commits to apply. Checked last,
1386
      // so the specific head above names the operation when it is still there.
1387
      //: The Git commands `git cherry-pick` and `git revert`, inserted into
1388
      //: "in the middle of a %1". Best kept as Git's command names.
1389
      {QLatin1String("sequencer"), tr("cherry-pick or revert")},
213 ✔
1390
  }};
×
1391
  QStringList args{QStringLiteral("rev-parse")};
426 ✔
1392
  for (const auto &marker : markers) {
1,491 ✔
1393
    args << QStringLiteral("--git-path") << marker.first;
1,278 ✔
1394
  }
1395
  QString out;
213 ✔
1396
  if (!storeGit(args, &out)) {
213 ✔
1397
    // Git is off, the store is not a repository, or git could not be asked:
1398
    // nothing is refused, as the operation would run anyway.
1399
    return {};
14 ✔
1400
  }
1401
  const QStringList paths = out.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
199 ✔
1402
  for (int i = 0; i < paths.size() && i < static_cast<int>(markers.size());
825 ✔
1403
       ++i) {
1404
    const QString path = paths.at(i).trimmed();
1405
    const QString full = QDir::isAbsolutePath(path)
1406
                             ? path
633 ✔
1407
                             : QDir(m_settings.passStore).filePath(path);
633 ✔
1408
    if (!QFileInfo::exists(full)) {
633 ✔
1409
      continue;
1410
    }
1411
    //: %1 is a Git command name: rebase, merge, cherry-pick, revert, or
1412
    //: "cherry-pick or revert".
1413
    return tr("The password store's Git repository is in the middle of a %1. "
7 ✔
1414
              "Finish or abort it with Git before changing the password store, "
1415
              "or what you change may be lost.")
1416
        .arg(markers.at(static_cast<size_t>(i)).second);
7 ✔
1417
  }
1418
  return {};
192 ✔
1419
}
1420

1421
auto Pass::refusePendingPull() -> bool {
205 ✔
1422
  if (!m_settings.useGit || !exec.hasQueued(Enums::GIT_PULL)) {
252 ✔
1423
    return false;
1424
  }
1425
  const QString why =
1426
      tr("The password store is being updated (a Git pull is in progress). "
1427
         "Wait until it has finished, then try again.");
1428
  // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
1429
  // and is released by processErrorExit(); a refusal starts nothing.
1430
  emit startingExecuteWrapper();
3 ✔
1431
  emit critical(tr("Update in progress"), why);
3 ✔
1432
  emit processErrorExit(1, why);
3 ✔
1433
  return true;
1434
}
1435

1436
auto Pass::initIfUnchanged(const QString &path, const QList<UserInfo> &users,
12 ✔
1437
                           const QString &dir, const QString &passStore,
1438
                           const RecipientsForEditing &read) -> bool {
1439
  m_expectedList = ExpectedList{dir, passStore, read.state, read.recipients};
12 ✔
1440
  m_expectedListRefused = false;
12 ✔
1441
  const auto done = qScopeGuard([this] { m_expectedList.reset(); });
1442
  Init(path, users);
12 ✔
1443
  return !m_expectedListRefused;
12 ✔
1444
}
1445

1446
auto Pass::refuseChangedList() -> bool {
82 ✔
1447
  if (!m_expectedList) {
82 ✔
1448
    return false;
1449
  }
1450
  const RecipientsForEditing now =
1451
      recipientsForEditing(m_expectedList->dir, m_expectedList->passStore);
5 ✔
1452
  if (now.state == m_expectedList->state &&
5 ✔
1453
      now.recipients == m_expectedList->recipients) {
5 ✔
1454
    return false;
1455
  }
1456
  const QString why =
1457
      tr("The recipient list of this folder changed after the users dialog "
1458
         "read it, for example through an update from Git. Nothing was "
1459
         "written. Open the dialog again to see the new list.");
1460
  m_expectedListRefused = true;
3 ✔
1461
  emit startingExecuteWrapper();
3 ✔
1462
  emit critical(tr("Recipients not changed"), why);
3 ✔
1463
  emit processErrorExit(1, why);
3 ✔
1464
  return true;
1465
}
1466

1467
auto Pass::refuseBusyForExpectedList() -> bool {
39 ✔
1468
  if (!m_expectedList || exec.isIdle()) {
39 ✔
1469
    return false;
1470
  }
1471
  const QString why =
1472
      tr("Another operation is still running. Wait until it has finished, "
1473
         "then save the recipients again.");
1474
  m_expectedListRefused = true;
1 ✔
1475
  emit startingExecuteWrapper();
1 ✔
1476
  emit critical(tr("Recipients not changed"), why);
1 ✔
1477
  emit processErrorExit(1, why);
1 ✔
1478
  return true;
1479
}
1480

1481
auto Pass::refuseUnfinishedGitOperation() -> bool {
600 ✔
1482
  const QString why = unfinishedGitOperationReason();
600 ✔
1483
  if (why.isEmpty()) {
600 ✔
1484
    return false;
1485
  }
1486
  // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
1487
  // and is released by finished()/processErrorExit(); a refusal starts
1488
  // nothing, so it emits both ends.
1489
  emit startingExecuteWrapper();
5 ✔
1490
  emit critical(tr("Unfinished Git operation"), why);
5 ✔
1491
  emit processErrorExit(1, why);
5 ✔
1492
  return true;
1493
}
1494

1495
void Pass::refuseAsNotPartOfStore(const QString &why) {
36 ✔
1496
  // The interface arms itself when an operation starts and is released by
1497
  // finished or processErrorExit; a refusal starts nothing, so emits both.
1498
  emit startingExecuteWrapper();
36 ✔
1499
  emit critical(tr("Not part of the store"), why);
36 ✔
1500
  emit processErrorExit(1, why);
36 ✔
1501
}
36 ✔
1502

1503
auto Pass::getGpgIdPath(const QString &for_file, const QString &passStore)
717 ✔
1504
    -> QString {
1505
  return nearestGpgId(gpgIdLookup(for_file, passStore))
1,434 ✔
1506
      .value_or(
1507
          QDir(QDir::fromNativeSeparators(passStore)).filePath(".gpg-id"));
2,868 ✔
1508
}
1509

1510
auto Pass::refuseSkippedGpgId(const QString &file, bool signing,
239 ✔
1511
                              const QString &except, SkippedWalks *walks)
1512
    -> bool {
1513
  // Without a signing key the parent's list applies, as it does for pass.
1514
  if (!signing) {
239 ✔
1515
    return false;
1516
  }
1517
  QString recordError;
54 ✔
1518
  const std::optional<QString> skipped =
1519
      skippedGpgId(file, m_settings.passStore, &recordError, walks);
54 ✔
1520
  if (!skipped || (!except.isEmpty() &&
54 ✔
1521
                   QDir::cleanPath(*skipped) == QDir::cleanPath(except))) {
56 ✔
1522
    return false;
1523
  }
1524
  // The strings keep the context they were translated in.
1525
  if (!recordError.isEmpty()) {
4 ✔
1526
    emit critical(QCoreApplication::translate(
×
1527
                      "ImitatePass", "Cannot check the recipient list"),
1528
                  QCoreApplication::translate(
×
1529
                      "ImitatePass", "%1 Whether %2 was removed cannot be "
1530
                                     "told, so nothing was encrypted.")
1531
                      .arg(recordError, QDir::toNativeSeparators(*skipped)));
×
1532
    return true;
×
1533
  }
1534
  emit critical(
4 ✔
1535
      QCoreApplication::translate("ImitatePass", "Recipient list missing"),
8 ✔
1536
      QCoreApplication::translate(
4 ✔
1537
          "ImitatePass",
1538
          "The signed recipient list %1 is missing or is not a regular file. "
1539
          "QtPass does not fall back to a parent folder's list for it: that "
1540
          "list was not signed for this folder. If a link is under that name, "
1541
          "remove it. Then open Users for that folder and save its "
1542
          "recipients, which writes and signs a fresh list.")
1543
          .arg(QDir::toNativeSeparators(*skipped)));
8 ✔
1544
  return true;
4 ✔
1545
}
1546

1547
auto Pass::verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile,
77 ✔
1548
                            QByteArray *contents, QString *why) const -> bool {
1549
  if (!signer.verifyFile(gpgIdFile, contents)) {
77 ✔
1550
    // A good signature refused for its key (held by two key blocks) says
1551
    // why, and what to do.
1552
    if (why != nullptr && !signer.refusal().isEmpty()) {
22 ✔
1553
      *why = signer.refusal();
1 ✔
1554
    }
1555
    return false;
18 ✔
1556
  }
1557
  // Authentic and unmodified is not the same as current: an older signed
1558
  // list put back into the store is refused once this device has seen a
1559
  // newer one, and one signed for another folder is refused here.
1560
  QString reason;
59 ✔
1561
  if (GpgIdGeneration::accept(gpgIdFile, *contents, m_settings.passStore,
59 ✔
1562
                              &reason) != GpgIdGeneration::Verdict::Accepted) {
1563
    if (why != nullptr) {
19 ✔
1564
      *why = reason;
14 ✔
1565
    }
1566
    return false;
19 ✔
1567
  }
1568
  return true;
1569
}
1570

1571
auto Pass::skippedGpgId(const QString &forFile, const QString &passStore,
287 ✔
1572
                        QString *recordError, SkippedWalks *walks)
1573
    -> std::optional<QString> {
1574
  const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
287 ✔
1575
  // A folder's answer depends only on it and the folders above it: kept
1576
  // for every folder climbed, a tree check asks each one record lookup,
1577
  // where climbing again from every folder cost depth squared.
1578
  QStringList climbed;
287 ✔
1579
  // By value: on a hit they come out of walks, which the inserts below
1580
  // may rehash.
1581
  const auto answer = [&climbed, walks, recordError](
287 ✔
1582
                          std::optional<QString> skipped, QString why) {
1583
    if (walks != nullptr) {
287 ✔
1584
      for (const QString &folder : std::as_const(climbed)) {
430 ✔
1585
        walks->insert(folder, {skipped, why});
430 ✔
1586
      }
1587
    }
1588
    if (recordError != nullptr && !why.isEmpty()) {
287 ✔
1589
      *recordError = why;
1 ✔
1590
    }
1591
    return skipped;
287 ✔
1592
  };
287 ✔
1593
  // The same walk as nearestGpgId(), stopping at the list it finds, and
1594
  // short of the store root: the root's own list has no parent to fall
1595
  // back to, and the signature check refuses it when it is missing. It
1596
  // starts at the folder asked for, not at its nearest existing one: a
1597
  // folder removed together with its list is asked of the record too.
1598
  QString dir = lookup.folder;
1599
  while (dir.startsWith(lookup.storePrefix, kPathCase)) {
711 ✔
1600
    if (walks != nullptr) {
657 ✔
1601
      if (const auto known = walks->constFind(dir);
413 ✔
1602
          known != walks->constEnd()) {
1603
        return answer(known->skipped, known->recordError);
396 ✔
1604
      }
1605
    }
1606
    climbed << dir;
1607
    const QFileInfo candidate(dir + QStringLiteral("/.gpg-id"));
918 ✔
1608
    if (isOwnGpgId(candidate)) {
459 ✔
1609
      return answer(std::nullopt, QString());
34 ✔
1610
    }
1611
    // A link under the name (dangling or not), or nothing under it where
1612
    // this device accepted a list before: both are the folder's list gone,
1613
    // not a folder that never had one.
1614
    if (candidate.isSymLink() || candidate.isJunction()) {
442 ✔
1615
      return answer(candidate.absoluteFilePath(), QString());
10 ✔
1616
    }
1617
    // An unreadable record is not "never seen": whether a list was accepted
1618
    // here cannot be told, so this folder is refused too (fail closed), with
1619
    // the record's own reason for the caller to show.
1620
    QString why;
437 ✔
1621
    const std::optional<bool> seen =
1622
        GpgIdGeneration::seen(candidate.absoluteFilePath(), &why);
874 ✔
1623
    if (!seen) {
437 ✔
1624
      return answer(candidate.absoluteFilePath(),
2 ✔
1625
                    why.isEmpty()
1626
                        ? tr("The generation record of the recipient lists "
2 ✔
1627
                             "cannot be read.")
1628
                        : why);
1 ✔
1629
    }
1630
    if (*seen) {
436 ✔
1631
      return answer(candidate.absoluteFilePath(), QString());
24 ✔
1632
    }
1633
    const QString parent = QDir::cleanPath(QFileInfo(dir).absolutePath());
848 ✔
1634
    if (parent == dir) {
424 ✔
1635
      break;
1636
    }
1637
    dir = parent;
424 ✔
1638
  }
459 ✔
1639
  return answer(std::nullopt, QString());
108 ✔
1640
}
287 ✔
1641

1642
auto Pass::linkedGpgId(const QString &forFile, const QString &passStore,
304 ✔
1643
                       LinkedWalks *walks) -> std::optional<QString> {
1644
  const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
304 ✔
1645
  // As in skippedGpgId(): a folder's answer depends only on it and the
1646
  // folders above it, so a tree check climbs each folder once instead of
1647
  // once per folder below it.
1648
  QStringList climbed;
304 ✔
1649
  const auto answer = [&climbed, walks](std::optional<QString> linked) {
304 ✔
1650
    if (walks != nullptr) {
304 ✔
1651
      for (const QString &folder : std::as_const(climbed)) {
381 ✔
1652
        walks->insert(folder, linked);
218 ✔
1653
      }
1654
    }
1655
    return linked;
304 ✔
1656
  };
304 ✔
1657
  // The walk of nearestGpgId(), root included, stopping at the list it
1658
  // finds.
1659
  QDir dir = lookup.start;
304 ✔
1660
  while (dir.exists()) {
1,142 ✔
1661
    const QString here = QDir::cleanPath(dir.absolutePath());
1,142 ✔
1662
    if (!isAtOrUnder(here, lookup.storeDir, lookup.storePrefix)) {
1,142 ✔
1663
      break;
1664
    }
1665
    if (walks != nullptr) {
1,062 ✔
1666
      // By value: the inserts in answer() may rehash walks.
1667
      if (const auto known = walks->constFind(here);
306 ✔
1668
          known != walks->constEnd()) {
1669
        return answer(std::optional<QString>(*known));
176 ✔
1670
      }
1671
    }
1672
    climbed << here;
1673
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
974 ✔
1674
    if (isOwnGpgId(candidate)) {
974 ✔
1675
      return answer(std::nullopt);
174 ✔
1676
    }
1677
    if (candidate.isSymLink() || candidate.isJunction()) {
887 ✔
1678
      return answer(candidate.absoluteFilePath());
98 ✔
1679
    }
1680
    if (!dir.cdUp()) {
838 ✔
1681
      break;
1682
    }
1683
  }
974 ✔
1684
  return answer(std::nullopt);
160 ✔
1685
}
608 ✔
1686

1687
namespace {
1688

1689
/// What the Users dialog may preselect for a verified list, given what the
1690
/// generation record says about it.
1691
auto judgedRecipients(GpgIdGeneration::Verdict verdict,
7 ✔
1692
                      const QByteArray &contents, const QString &gpgIdPath,
1693
                      const QString &why) -> Pass::RecipientsForEditing {
1694
  using RecipientsForEditing = Pass::RecipientsForEditing;
1695
  RecipientsForEditing result;
7 ✔
1696
  switch (verdict) {
7 ✔
1697
  case GpgIdGeneration::Verdict::Accepted:
1 ✔
1698
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1699
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1700
    break;
1 ✔
1701
  case GpgIdGeneration::Verdict::Rollback:
1 ✔
1702
    // Authentic and this folder's, only older: the recovery goes through
1703
    // this dialog, so it is preselected, with the reason in view.
1704
    result.state = RecipientsForEditing::State::VerifiedRollback;
1 ✔
1705
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1706
    result.warning = why;
1 ✔
1707
    break;
1 ✔
1708
  case GpgIdGeneration::Verdict::Unbound:
5 ✔
1709
  case GpgIdGeneration::Verdict::Conflict:
1710
  case GpgIdGeneration::Verdict::WrongFolder:
1711
  case GpgIdGeneration::Verdict::WrongStore:
1712
  case GpgIdGeneration::Verdict::Malformed:
1713
  case GpgIdGeneration::Verdict::RecordUnavailable:
1714
    // Signed, but not shown to be this folder's list, not a list to trust,
1715
    // or nothing to judge it by: preselecting it would sign it in.
1716
    result.state = RecipientsForEditing::State::Rejected;
5 ✔
1717
    result.warning =
1718
        Pass::tr("%1 Nothing is preselected: saving would sign whatever is "
5 ✔
1719
                 "in it. Select the recipients yourself.")
1720
            .arg(why);
10 ✔
1721
    break;
5 ✔
1722
  }
1723
  return result;
7 ✔
1724
}
1725

1726
} // namespace
1727

1728
auto Pass::recipientsForEditing(const QString &dir, const QString &passStore)
90 ✔
1729
    -> RecipientsForEditing {
1730
  RecipientsForEditing result;
90 ✔
1731
  const QString folder = dir.isEmpty() ? QString() : dir;
90 ✔
1732
  const QString gpgIdPath = getGpgIdPath(folder, passStore);
90 ✔
1733
  GpgIdSigner signer(m_settings.gpgExecutable,
1734
                     GpgIdSigner::keysFromSetting(m_settings.passSigningKey));
270 ✔
1735
  signer.setStoreRoot(passStore);
1736
  if (!signer.enabled()) {
90 ✔
1737
    // A list that is there but cannot be read as one (too large, not a
1738
    // regular file, unreadable) is not an empty list: preselecting nothing
1739
    // without a word would let OK write a new list over it, and later
1740
    // re-encryptions drop whoever it named.
1741
    // Read once and parsed from those bytes: a second read could find
1742
    // something else under the name. A link counts as there, dangling too.
1743
    const QFileInfo info(gpgIdPath);
80 ✔
1744
    if (!info.exists() && !info.isSymLink()) {
80 ✔
1745
      result.state = RecipientsForEditing::State::Unsigned;
1746
      return result;
18 ✔
1747
    }
1748
    const std::optional<QByteArray> bytes = Util::readRegularFileInStore(
1749
        passStore, gpgIdPath, Util::kMaxGpgIdBytes);
62 ✔
1750
    if (!bytes) {
62 ✔
1751
      result.state = RecipientsForEditing::State::Rejected;
2 ✔
1752
      result.warning =
1753
          tr("%1 cannot be read as a recipient list (a regular file of at "
2 ✔
1754
             "most %2), so nothing is preselected. Check it before choosing "
1755
             "recipients here: OK writes a new list over it.")
1756
              .arg(gpgIdPath,
2 ✔
1757
                   QLocale().formattedDataSize(Util::kMaxGpgIdBytes));
4 ✔
1758
      return result;
2 ✔
1759
    }
1760
    result.state = RecipientsForEditing::State::Unsigned;
1761
    result.recipients = parseRecipients(*bytes, gpgIdPath);
60 ✔
1762
    const QString misread = passReadsDifferently(*bytes);
60 ✔
1763
    if (!misread.isEmpty()) {
60 ✔
1764
      //: %1 is the list's path, %2 says what is wrong with it.
1765
      result.warning =
1766
          tr("pass reads %1 differently from this dialog (%2), so it may "
3 ✔
1767
             "encrypt to recipients not shown here. QtPass will not encrypt "
1768
             "with it through pass: check the recipients, then OK writes the "
1769
             "list anew.")
1770
              .arg(gpgIdPath, misread);
6 ✔
1771
    }
1772
    return result;
60 ✔
1773
  }
80 ✔
1774
  QString recordError;
10 ✔
1775
  if (const std::optional<QString> skipped =
10 ✔
1776
          skippedGpgId(folder, passStore, &recordError)) {
10 ✔
1777
    // The folder's own list was removed or replaced by a link (or the record
1778
    // that would tell cannot be read): the list the walk found further up
1779
    // was not signed for this folder, so preselecting it would sign it in
1780
    // here with one click.
1781
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1782
    result.warning =
1783
        recordError.isEmpty()
1784
            ? tr("The recipient list %1 is missing or is not a regular file, "
2 ✔
1785
                 "so nothing is preselected: the list of a parent folder was "
1786
                 "not signed for this one. Select this folder's recipients "
1787
                 "yourself; OK writes and signs a fresh list.")
1788
                  .arg(*skipped)
1789
            : tr("%1 Nothing is preselected: whether %2 was removed cannot "
1 ✔
1790
                 "be told.")
1791
                  .arg(recordError, *skipped);
1792
    return result;
1 ✔
1793
  }
1794
  if (!QFileInfo::exists(gpgIdPath)) {
9 ✔
1795
    // A folder without a list yet (new store, new profile): nothing to
1796
    // verify and nothing to preselect.
1797
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1798
    return result;
1 ✔
1799
  }
1800
  QByteArray contents;
8 ✔
1801
  if (!signer.verifyFile(gpgIdPath, &contents)) {
8 ✔
1802
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1803
    result.warning =
1804
        tr("The recipient list %1 does not verify against the signing key, "
1 ✔
1805
           "so nothing is preselected: saving would sign whatever is in it. "
1806
           "Select the recipients yourself; OK writes and signs a fresh list.")
1807
            .arg(gpgIdPath);
2 ✔
1808
    return result;
1 ✔
1809
  }
1810
  QString why;
7 ✔
1811
  const GpgIdGeneration::Verdict verdict =
1812
      GpgIdGeneration::accept(gpgIdPath, contents, passStore, &why);
7 ✔
1813
  return judgedRecipients(verdict, contents, gpgIdPath, why);
7 ✔
1814
}
90 ✔
1815

1816
auto Pass::getRecipientList(const QString &for_file, const QString &passStore)
57 ✔
1817
    -> QStringList {
1818
  const QString gpgIdPath = getGpgIdPath(for_file, passStore);
57 ✔
1819
  // The root .gpg-id comes back whatever it is; a link is not a list.
1820
  if (Util::isLinkedFolder(gpgIdPath)) {
57 ✔
1821
    return {};
1 ✔
1822
  }
1823
  const std::optional<QByteArray> bytes =
1824
      Util::readRegularFileInStore(passStore, gpgIdPath, Util::kMaxGpgIdBytes);
56 ✔
1825
  if (!bytes) {
56 ✔
1826
    return {};
29 ✔
1827
  }
1828
  return parseRecipients(*bytes, gpgIdPath);
27 ✔
1829
}
1830

1831
auto Pass::parseRecipients(const QByteArray &contents,
321 ✔
1832
                           const QString &sourceName) -> QStringList {
1833
  QStringList recipients;
321 ✔
1834
  const QString text = QString::fromUtf8(contents);
1835
  for (const QString &line : text.split(QLatin1Char('\n'))) {
7,196 ✔
1836
    QString recipient = line.split(QLatin1Char('#')).first().trimmed();
13,750 ✔
1837
    if (recipient.isEmpty()) {
6,875 ✔
1838
      continue;
422 ✔
1839
    }
1840
    if (!Util::isValidKeyId(recipient)) {
6,453 ✔
1841
      // Never drop a recipient silently: the list is written back verbatim
1842
      // by UsersDialog, so a skipped line disappears from .gpg-id.
1843
      qCWarning(lcQtPass) << "Skipping unusable recipient in" << sourceName
4 ✔
1844
                          << ":" << recipient;
2 ✔
1845
      continue;
2 ✔
1846
    }
2 ✔
1847
    recipients += recipient;
1848
  }
1849
  return recipients;
321 ✔
1850
}
1851

1852
auto Pass::passReadsDifferently(const QByteArray &contents) -> QString {
107 ✔
1853
  if (contents.startsWith("\xEF\xBB\xBF")) {
107 ✔
1854
    return tr("it starts with a byte-order mark");
1855
  }
1856
  if (contents.contains('\0')) {
106 ✔
1857
    return tr("it holds a NUL byte");
1858
  }
1859
  if (contents.contains('\r')) {
104 ✔
1860
    return tr("it has Windows line ends (a carriage return)");
1861
  }
1862
  const QString text = QString::fromUtf8(contents);
1863
  if (text.toUtf8() != contents) {
103 ✔
1864
    return tr("it is not valid UTF-8");
1865
  }
1866
  const QStringList lines = text.split(QLatin1Char('\n'));
102 ✔
1867
  for (qsizetype i = 0; i < lines.size(); ++i) {
6,432 ✔
1868
    const QString &line = lines.at(i);
1869
    const QString recipient = line.left(line.indexOf(QLatin1Char('#')));
6,340 ✔
1870
    for (const QChar c : recipient) {
132,806 ✔
1871
      // read strips blanks and tabs; trimmed() strips every space.
1872
      if (c.isSpace() && c != QLatin1Char(' ') && c != QLatin1Char('\t')) {
126,473 ✔
1873
        return tr("line %1 holds whitespace other than blanks and tabs")
7 ✔
1874
            .arg(i + 1);
7 ✔
1875
      }
1876
    }
1877
    const QString trimmed = recipient.trimmed();
1878
    if (trimmed.startsWith(QLatin1Char('-'))) {
6,333 ✔
1879
      return tr("line %1 starts with a dash").arg(i + 1);
2 ✔
1880
    }
1881
    // The text after the last line feed: read hands it over but the loop
1882
    // ends without using it.
1883
    if (i == lines.size() - 1 && !trimmed.isEmpty()) {
6,331 ✔
1884
      return tr("its last line has no line end");
1885
    }
1886
  }
1887
  return {};
92 ✔
1888
}
1889

1890
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
1891
 */
1892

1893
auto Pass::boundedRandom(quint32 bound) -> quint32 {
7,620 ✔
1894
  if (bound < 2) {
7,620 ✔
1895
    return 0;
1896
  }
1897

1898
  quint32 randval;
1899
  // arc4random_uniform-style rejection against modulo bias: drop values
1900
  // below 2^32 % bound, which (1 + ~bound) % bound computes in quint32.
1901
  const quint32 rejectionThreshold = (1 + ~bound) % bound;
7,616 ✔
1902

1903
  do {
1904
    randval = QRandomGenerator::system()->generate();
1905
  } while (randval < rejectionThreshold);
7,616 ✔
1906

1907
  return randval % bound;
7,616 ✔
1908
}
1909

1910
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,209 ✔
1911
    -> QString {
1912
  if (charset.isEmpty() || length == 0U) {
1,209 ✔
1913
    return {};
2 ✔
1914
  }
1915
  QString out;
1,207 ✔
1916
  for (unsigned int i = 0; i < length; ++i) {
8,827 ✔
1917
    out.append(charset.at(static_cast<int>(
7,620 ✔
1918
        boundedRandom(static_cast<quint32>(charset.length())))));
7,620 ✔
1919
  }
1920
  return out;
1921
}
1922

1923
auto Pass::pullTimedOut(int timeoutMs) -> QString {
2 ✔
1924
  // The count in a variable first: older lupdate versions lose a tr() with
1925
  // template arguments among its arguments.
1926
  const int seconds = (timeoutMs + 999) / 1000;
2 ✔
1927
  return tr("Git pull did not finish within %n second(s); editing the entry "
1928
            "as it is here.",
1929
            nullptr, seconds);
2 ✔
1930
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc