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

IJHack / QtPass / 46256559824

29 Nov 2026 11:18AM UTC coverage: 94.504% (+0.01%) from 94.493%
46256559824

push

github

web-flow
pass backend: ask before a pass run gives entries new readers (#2391)

pass init, pass mv and pass cp re-encrypt every entry of a folder
themselves; mv and cp end with reencrypt_path on where the moved item
landed. An entry someone with push access copied in from a folder you
are not on was handed to the folder's recipients by your next Users
save, or by a move, rename or copy that touched its folder.

RealPass::entriesInitWouldWiden() and entriesMoveWouldWiden() name,
before pass runs, the entries it would re-encrypt that would become
readable by someone on their target list who cannot read them now: a
throwaway encryption to the list (Pass::encryptionReaches()) against the
entry's recipient IDs (Pass::entryReaders(), path translated for a WSL
gpg), less whom the change adds. A list the probe cannot read, or an
entry whose recipients cannot be listed, is asked about. For a move,
both the entries already in the destination folder and those inside a
folder that moves are checked, each against the list it will get. The
Users dialog, a drop in the tree and MainWindow's move and rename ask,
under a wait cursor (PlainMessageBox::confirmPassRun()); No runs
nothing, Yes lets pass go on as before.

Tests: with a fake gpg whose ciphertext lists its recipients, a planted
copy is named for a Users save, a move into its folder and a rename of
its folder; an entry the change adds someone to is not; an unlistable
entry is asked about. The Users dialog and a tree drop ask, and No runs
nothing. Each guard was reverted once and its test failed.

Scan finding ANT-2026-SEN4VBBB.

Signed-off-by: Anne Jan Brouwer <brouwer@annejan.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

126 of 132 new or added lines in 7 files covered. (95.45%)

11039 of 11681 relevant lines covered (94.5%)

23924.6 hits per line

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

96.11
/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,694 ✔
54
}
55

56
auto effectiveCharset(const PasswordConfiguration &passConfig) -> QString {
487 ✔
57
  int sel = passConfig.selected;
487 ✔
58
  if (sel < 0 || sel >= PasswordConfiguration::CHARSETS_COUNT)
487 ✔
59
    sel = PasswordConfiguration::ALLCHARS;
60
  return fallbackCharset(
61
      passConfig.Characters[sel],
487 ✔
62
      passConfig.Characters[PasswordConfiguration::ALLCHARS]);
487 ✔
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) {
967 ✔
72
  QStringList parts = env.value(QStringLiteral("WSLENV"))
1,934 ✔
73
                          .split(QLatin1Char(':'), Qt::SkipEmptyParts);
967 ✔
74
  for (const QString &name : names) {
5,788 ✔
75
    if (!parts.contains(name)) {
4,821 ✔
76
      parts.append(name);
77
    }
78
  }
79
  env.insert(QStringLiteral("WSLENV"), parts.join(QLatin1Char(':')));
1,934 ✔
80
}
967 ✔
81
} // namespace
82

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

87
  connect(&exec, &Executor::starting, this, &Pass::startingExecuteWrapper);
480 ✔
88
  connect(&exec, &Executor::drained, this, [this] {
480 ✔
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;
134 ✔
98
    m_insertedEntries.clear();
134 ✔
99
    emit idle();
134 ✔
100
  });
134 ✔
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) {
480 ✔
105
    if (completes) {
374 ✔
106
      exec.setEnvironment(withCurrentGitPin(env));
366 ✔
107
    }
108
  });
374 ✔
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"),
960 ✔
117
      QStringLiteral("PASSWORD_STORE_SIGNING_KEY/u"),
480 ✔
118
      QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH/u"),
480 ✔
119
      QStringLiteral("PASSWORD_STORE_CHARACTER_SET/u"),
480 ✔
120
      QStringLiteral("PASSWORD_STORE_GPG_OPTS/u"),
480 ✔
121
      QStringLiteral("GIT_CEILING_DIRECTORIES/p"),
480 ✔
122
      QStringLiteral("GIT_LITERAL_PATHSPECS/u")};
3,840 ✔
123
  mergeIntoWslenv(env, wslenvVars);
480 ✔
124
}
480 ✔
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,
374 ✔
133
                          const QStringList &args, QString input,
134
                          bool readStdout, bool readStderr) {
135
  beforeExecute(id);
374 ✔
136
  qCDebug(lcQtPass) << app << loggableArgs(args);
374 ✔
137
  exec.execute(id, m_settings.passStore, app, args, std::move(input),
374 ✔
138
               readStdout, readStderr);
139
}
374 ✔
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")};
44 ✔
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) {
950 ✔
172
  m_settings = settings;
950 ✔
173
#ifdef __APPLE__
174
  // If it exists, prepend gpgtools to PATH
175
  if (QFile(QStringLiteral("/usr/local/MacGPG2/bin")).exists())
176
    env.insert(QStringLiteral("PATH"),
177
               QStringLiteral("/usr/local/MacGPG2/bin:") +
178
                   env.value(QStringLiteral("PATH")));
179
  // Add missing /usr/local/bin (exact component match, no leading colon)
180
  const QString currentPath = env.value(QStringLiteral("PATH"));
181
  if (!currentPath.split(':', Qt::SkipEmptyParts)
182
           .contains(QStringLiteral("/usr/local/bin"))) {
183
    env.insert(QStringLiteral("PATH"),
184
               currentPath.isEmpty()
185
                   ? QStringLiteral("/usr/local/bin")
186
                   : QStringLiteral("/usr/local/bin:") + currentPath);
187
  }
188
#endif
189

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

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

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

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

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

350
QString findGpgconfInGpgDir(const QString &gpgPath) {
8 ✔
351
  QFileInfo gpgInfo(gpgPath);
8 ✔
352
  if (!gpgInfo.isAbsolute()) {
8 ✔
353
    return {};
1 ✔
354
  }
355

356
  QDir dir(gpgInfo.absolutePath());
7 ✔
357

358
#ifdef Q_OS_WIN
359
  QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
360
  if (candidateExe.isExecutable()) {
361
    return candidateExe.filePath();
362
  }
363
#endif
364

365
  QFileInfo candidate(dir.filePath("gpgconf"));
7 ✔
366
  if (candidate.isExecutable()) {
7 ✔
367
    return candidate.filePath();
5 ✔
368
  }
369
  return {};
2 ✔
370
}
8 ✔
371

372
} // namespace
373

374
auto Pass::resolveGpgconfCommand(const QString &gpgPath)
22 ✔
375
    -> ResolvedGpgconfCommand {
376
  if (gpgPath.trimmed().isEmpty()) {
22 ✔
377
    return {"gpgconf", {}};
378
  }
379

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

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

402
  if (!first.contains('/') && !first.contains('\\')) {
9 ✔
403
    return {"gpgconf", {}};
404
  }
405

406
  QString gpgconfPath = findGpgconfInGpgDir(first);
8 ✔
407
  if (!gpgconfPath.isEmpty()) {
8 ✔
408
    return {gpgconfPath, {}};
5 ✔
409
  }
410

411
  return {"gpgconf", {}};
412
}
22 ✔
413

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

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

442
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
16 ✔
443
                 std::move(batch), true, true);
444
}
445

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

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

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

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

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

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

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

573
auto Pass::enabledKeyLines(const QList<UserInfo> &users) -> QStringList {
82 ✔
574
  QStringList lines;
82 ✔
575
  for (const UserInfo &user : users) {
175 ✔
576
    if (user.enabled) {
93 ✔
577
      lines << user.key_id;
92 ✔
578
    }
579
  }
580
  return lines;
82 ✔
581
}
582

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

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

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

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

687
auto Pass::encryptionReaches(const QStringList &recipients)
84 ✔
688
    -> std::optional<QStringList> {
689
  if (recipients.isEmpty()) {
84 ✔
690
    return std::nullopt;
×
691
  }
692
  QTemporaryDir scratch;
84 ✔
693
  if (!scratch.isValid()) {
84 ✔
694
    return std::nullopt;
×
695
  }
696
  const QString &gpg = m_settings.gpgExecutable;
84 ✔
697
  const QString probe = Executor::translatePathForWsl(
698
      scratch.filePath(QStringLiteral("probe.gpg")), gpg);
168 ✔
699
  // --no-throw-keyids: with throw-keyids in gpg.conf the probe would name
700
  // no one.
701
  QStringList args{QStringLiteral("--batch"),
168 ✔
702
                   QStringLiteral("--no-tty"),
84 ✔
703
                   QStringLiteral("--yes"),
84 ✔
704
                   QStringLiteral("--quiet"),
84 ✔
705
                   QStringLiteral("--no-throw-keyids"),
84 ✔
706
                   QStringLiteral("--no-auto-key-locate"),
84 ✔
707
                   QStringLiteral("--no-encrypt-to"),
84 ✔
708
                   QStringLiteral("--output"),
84 ✔
709
                   probe,
710
                   QStringLiteral("--encrypt")};
1,008 ✔
711
  for (const QString &recipient : recipients) {
6,256 ✔
712
    args << QStringLiteral("-r") << recipient;
6,172 ✔
713
  }
714
  if (Executor::executeBlocking(gpg, args, QStringLiteral("probe")) != 0) {
168 ✔
715
    return std::nullopt;
18 ✔
716
  }
717
  // As ImitatePass::getKeysFromFile(): --decrypt --list-only, capped.
718
  QString status;
66 ✔
719
  if (Executor::executeBlocking(
792 ✔
720
          gpg,
721
          {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
66 ✔
722
           QStringLiteral("--decrypt"), QStringLiteral("--list-only"),
66 ✔
723
           QStringLiteral("--max-output"), QStringLiteral("1"),
66 ✔
724
           QStringLiteral("--status-fd=1"),
66 ✔
725
           QStringLiteral("--keyid-format=long"), QStringLiteral("--"), probe},
66 ✔
726
          QString(), &status) != 0) {
132 ✔
727
    return QStringList();
×
728
  }
729
  static const QRegularExpression encTo(
730
      QStringLiteral("^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
74 ✔
731
  QStringList ids;
66 ✔
732
  for (const QString &line :
733
       status.split(Util::newLinesRegex(), Qt::SkipEmptyParts)) {
366 ✔
734
    const QRegularExpressionMatch match = encTo.match(line);
234 ✔
735
    if (match.hasMatch()) {
234 ✔
736
      ids << match.captured(1).toUpper();
32 ✔
737
    }
738
  }
234 ✔
739
  return ids;
740
}
84 ✔
741

742
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
201 ✔
743
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
1,407 ✔
744
  args.append(secret ? "--list-secret-keys" : "--list-keys");
530 ✔
745

746
  for (const QString &keystring : std::as_const(keystrings)) {
6,478 ✔
747
    if (!keystring.isEmpty()) {
6,277 ✔
748
      args.append(keystring);
749
    }
750
  }
751
  QString p_out;
201 ✔
752
  if (Executor::executeBlocking(m_settings.gpgExecutable, args, &p_out) != 0) {
201 ✔
753
    return {};
6 ✔
754
  }
755
  return parseGpgColonOutput(p_out, secret);
195 ✔
756
}
757

758
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
157 ✔
759
  return listKeys(QStringList(keystring), secret);
314 ✔
760
}
761

762
namespace {
763

764
auto containsAny(const QString &str, const QStringList &patterns) -> bool {
127 ✔
765
  for (const QString &p : patterns) {
352 ✔
766
    if (str.contains(p)) {
246 ✔
767
      return true;
768
    }
769
  }
770
  return false;
771
}
772

773
// @p patterns must already be lowercase; only @p str is lowered.
774
auto containsAnyCaseInsensitive(const QString &str, const QStringList &patterns)
107 ✔
775
    -> bool {
776
  const QString lower = str.toLower();
777
  for (const QString &p : patterns) {
265 ✔
778
    if (lower.contains(p)) {
169 ✔
779
      return true;
780
    }
781
  }
782
  return false;
783
}
784

785
} // namespace
786

787
auto gpgErrorMessage(const QString &err) -> QString {
47 ✔
788
  // Machine-readable status tokens added by --status-fd 2
789
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYEXPIRED"),
235 ✔
790
                        QStringLiteral("[GNUPG:] INV_RECP 5 ")}))
47 ✔
791
    return QCoreApplication::translate(
792
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
793
                "replace it.");
5 ✔
794
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYREVOKED"),
210 ✔
795
                        QStringLiteral("[GNUPG:] INV_RECP 4 ")}))
42 ✔
796
    return QCoreApplication::translate(
797
        "Pass", "Encryption failed: GPG key has been revoked.");
4 ✔
798
  if (containsAny(err, {QStringLiteral("[GNUPG:] NO_PUBKEY"),
190 ✔
799
                        QStringLiteral("[GNUPG:] INV_RECP")}))
38 ✔
800
    return QCoreApplication::translate(
801
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
802
                "Check that the key ID in .gpg-id is correct and imported.");
12 ✔
803
  if (err.contains(QStringLiteral("[GNUPG:] FAILURE")))
26 ✔
804
    return QCoreApplication::translate(
805
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
806

807
  // Locale-dependent fallbacks
808
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has expired"),
100 ✔
809
                                       QLatin1String("key expired")}))
810
    return QCoreApplication::translate(
811
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
812
                "replace it.");
1 ✔
813
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has been revoked"),
96 ✔
814
                                       QLatin1String("revoked")}))
815
    return QCoreApplication::translate(
816
        "Pass", "Encryption failed: GPG key has been revoked.");
1 ✔
817
  // pass passes no --status-fd, so this is all gpg says about a key that is
818
  // present but cannot encrypt: expired, revoked, without an encryption
819
  // subkey, or not trusted ("There is no assurance this key belongs to the
820
  // named user"). "Not found ... imported" would send the user the wrong
821
  // way; gpg's own lines, shown below this, say which it is.
822
  if (containsAnyCaseInsensitive(err, {QLatin1String("unusable public key")}))
69 ✔
823
    return QCoreApplication::translate(
824
        "Pass", "Encryption failed: a recipient's GPG key cannot be used. It "
825
                "may have expired or been revoked, have no encryption subkey, "
826
                "or not be trusted; gpg's message below says which.");
3 ✔
827
  if (containsAnyCaseInsensitive(err, {QLatin1String("no public key"),
80 ✔
828
                                       QLatin1String("no secret key")}))
829
    return QCoreApplication::translate(
830
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
831
                "Check that the key ID in .gpg-id is correct and imported.");
5 ✔
832
  if (containsAnyCaseInsensitive(err, {QLatin1String("encryption failed")}))
45 ✔
833
    return QCoreApplication::translate(
834
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
835

836
  return {};
14 ✔
837
}
×
838

839
void Pass::finished(int id, int exitCode, const QString &out,
322 ✔
840
                    const QString &err) {
841
  auto pid = static_cast<PROCESS>(id);
322 ✔
842

843
  // Pop the Show() this completion belongs to whether it worked or not, or
844
  // the next result would be attributed to the wrong file.
845
  QString shownFile;
322 ✔
846
  if (pid == PASS_SHOW && !m_pendingShows.isEmpty()) {
322 ✔
847
    shownFile = m_pendingShows.dequeue();
80 ✔
848
  }
849
  // Count this insert off, success or failure, before its result goes out, so
850
  // insertsPending() tracks the inserts still awaiting a report. Each insert
851
  // reaches here once as PASS_INSERT.
852
  // Its entry is handed out (reportedInsert()) while the report goes out.
853
  QString reported;
322 ✔
854
  if (pid == PASS_INSERT && m_insertsPending > 0) {
322 ✔
855
    --m_insertsPending;
121 ✔
856
    if (!m_insertedEntries.isEmpty()) {
121 ✔
857
      reported = m_insertedEntries.dequeue();
121 ✔
858
    }
859
  }
860
  m_reportedInsert = reported;
322 ✔
861
  const auto reportedOut = qScopeGuard([this] { m_reportedInsert.clear(); });
322 ✔
862

863
  if (exitCode != 0) {
322 ✔
864
    handleProcessError(pid, exitCode, out, err);
60 ✔
865
    return;
866
  }
867

868
  if (pid == PASS_SHOW) {
262 ✔
869
    emit finishedShow(out, shownFile, exec.lastOutputLossless());
53 ✔
870
    return;
871
  }
872
  emitProcessFinishedSignal(pid, out, err);
209 ✔
873
}
874

875
void Pass::handleProcessError(PROCESS pid, int exitCode, const QString &out,
60 ✔
876
                              const QString &err) {
877
  Q_UNUSED(out);
878

879
  if (pid == PASS_INSERT) {
60 ✔
880
    const QString friendly = gpgErrorMessage(err);
19 ✔
881
    const QString why =
882
        friendly.isEmpty() ? err : formatInsertError(friendly, err);
19 ✔
883
    const bool written = insertWritten(err);
19 ✔
884
    emit insertFailed(why, written);
19 ✔
885
    if (written) {
19 ✔
886
      // The entry is in the store; a git step after it failed (a commit
887
      // that could not be signed, with pass.signcommits, say). The dialog
888
      // closes on this, so say it here rather than only in the output
889
      // panel.
890
      emit critical(tr("Saved, not committed"),
10 ✔
891
                    tr("The entry is saved in the store, but recording it "
5 ✔
892
                       "in git failed. What was reported:\n\n%1")
893
                        .arg(err.trimmed()));
10 ✔
894
    }
895
    emit processErrorExit(exitCode, why);
19 ✔
896
    return;
897
  }
898

899
  if (pid == GPG_GENKEYS) {
41 ✔
900
    emit generateGPGKeysFailed(err);
1 ✔
901
  }
902
  emit processErrorExit(exitCode, err);
41 ✔
903
}
904

905
auto Pass::withoutStatusLines(const QString &err) -> QString {
53 ✔
906
  QStringList humanLines;
53 ✔
907
  for (const QString &line : err.split('\n')) {
1,648 ✔
908
    QString cleanedLine = line;
909
    cleanedLine.remove('\r');
1,542 ✔
910
    if (!cleanedLine.startsWith(QLatin1String("[GNUPG:]")))
1,542 ✔
911
      humanLines.append(cleanedLine);
912
  }
913
  return humanLines.join('\n');
53 ✔
914
}
915

916
auto Pass::formatInsertError(const QString &friendly, const QString &err)
6 ✔
917
    -> QString {
918
  const QString humanErr = withoutStatusLines(err).trimmed();
12 ✔
919
  return humanErr.isEmpty() ? friendly : friendly + "\n\n" + humanErr;
12 ✔
920
}
921

922
void Pass::emitProcessFinishedSignal(PROCESS pid, const QString &out,
209 ✔
923
                                     const QString &err) {
924
  // Only output that cannot contain a secret reaches the generic listeners
925
  // (the output panel among them); Enums::processInfo is the one table.
926
  if (pid >= 0 && pid < Enums::PROCESS_COUNT &&
209 ✔
927
      !Enums::processInfo(pid).secret) {
207 ✔
928
    emit finishedAnyWithPid(out, err, pid);
98 ✔
929
  }
930

931
  // The kind-specific signal. PASS_SHOW is emitted by finished(), which
932
  // knows the file. Content search runs in-process (NativeGrep), not
933
  // through `pass grep`, and emits finishedGrep itself.
934
  using Signal = void (Pass::*)(const QString &, const QString &);
935
  static const QHash<int, Signal> kSignals{
936
      {GIT_INIT, &Pass::finishedGitInit},
937
      {GIT_PULL, &Pass::finishedGitPull},
938
      {GIT_PUSH, &Pass::finishedGitPush},
939
      {PASS_INSERT, &Pass::finishedInsert},
940
      {PASS_REMOVE, &Pass::finishedRemove},
941
      {PASS_INIT, &Pass::finishedInit},
942
      {PASS_MOVE, &Pass::finishedMove},
943
      {PASS_COPY, &Pass::finishedCopy},
944
      {GPG_GENKEYS, &Pass::finishedGenerateGPGKeys},
945
  };
215 ✔
946
  // A store that became a repository after updateEnv() gets its pin now,
947
  // before anything is staged in it.
948
  if (pid == GIT_INIT) {
209 ✔
949
    pinStoreGitAttributes();
3 ✔
950
  }
951
  if (const Signal signal = kSignals.value(pid, nullptr)) {
209 ✔
952
    (this->*signal)(out, err);
205 ✔
953
  }
954
}
209 ✔
955

956
void Pass::setEnvVar(const QString &name, const QString &value) {
4,393 ✔
957
  if (value.isEmpty())
4,393 ✔
958
    env.remove(name);
1,459 ✔
959
  else
960
    env.insert(name, value);
2,934 ✔
961
}
4,393 ✔
962

963
void Pass::updateEnv() {
487 ✔
964
  setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY"),
974 ✔
965
            m_settings.passSigningKey);
487 ✔
966
  setEnvVar(QStringLiteral("PASSWORD_STORE_DIR"), m_settings.passStore);
974 ✔
967
  // Every path QtPass hands git names one file or folder: an entry called
968
  // "a*.gpg" must not make `git rm -f -- a*.gpg` remove every entry that
969
  // matches. Also reaches the git that pass runs, which passes names the
970
  // same way.
971
  setEnvVar(QStringLiteral("GIT_LITERAL_PATHSPECS"), QStringLiteral("1"));
974 ✔
972

973
  const PasswordConfiguration &passConfig = m_settings.passwordConfiguration;
487 ✔
974
  setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH"),
974 ✔
975
            QString::number(passConfig.length));
487 ✔
976

977
  setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET"),
974 ✔
978
            effectiveCharset(passConfig));
487 ✔
979

980
  // pass hands PASSWORD_STORE_GPG_OPTS to every gpg it runs: the user's own
981
  // options (split as pass's shell splits them: spaces, tabs, newlines),
982
  // then the output limit ImitatePass passes directly.
983
  QStringList gpgOpts = QProcessEnvironment::systemEnvironment()
487 ✔
984
                            .value(QStringLiteral("PASSWORD_STORE_GPG_OPTS"))
974 ✔
985
                            .split(QRegularExpression(QStringLiteral("\\s+")),
974 ✔
986
                                   Qt::SkipEmptyParts);
974 ✔
987
  gpgOpts << maxOutputArgs();
974 ✔
988
  setEnvVar(QStringLiteral("PASSWORD_STORE_GPG_OPTS"),
974 ✔
989
            gpgOpts.join(QLatin1Char(' ')));
487 ✔
990

991
  // As pass does: git never looks for a repository above the store's own
992
  // parent. A store that is not a repository itself but lies inside one (a
993
  // dotfiles repository in the home folder) would otherwise have its entries
994
  // committed and pushed there by native git mode. Only in the environment
995
  // of the processes QtPass runs for the store, never QtPass's own, which a
996
  // file manager or terminal it opens would inherit. pass sets its own
997
  // ceiling whatever this says. A store kept inside a larger repository on
998
  // purpose opts out (gitUseParentRepository), and then, as without a
999
  // store, whatever ceiling QtPass was started with applies.
1000
  // A ceiling git cannot take as one entry (the parent's path holds the
1001
  // list separator) is backed by GIT_DIR and GIT_WORK_TREE naming the
1002
  // store's own repository (Util::gitStoreVariables()); pass unsets those
1003
  // for itself and keeps its own ceiling.
1004
  setEnvVar(QStringLiteral("GIT_DIR"), QString());
974 ✔
1005
  setEnvVar(QStringLiteral("GIT_WORK_TREE"), QString());
974 ✔
1006
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
487 ✔
1007
    setEnvVar(QStringLiteral("GIT_CEILING_DIRECTORIES"),
40 ✔
1008
              qEnvironmentVariable("GIT_CEILING_DIRECTORIES"));
40 ✔
1009
  } else {
1010
    for (const auto &[name, value] : Util::gitStoreVariables(
1011
             m_settings.passStore, m_settings.gitExecutable)) {
1,405 ✔
1012
      setEnvVar(name, value);
471 ✔
1013
    }
1014
  }
1015

1016
  // Refuse a repository pushed into the store: git started in a folder laid
1017
  // out as a bare repository would read its pushed config and run a command
1018
  // named there. This reaches the git that pass runs too, which inherits the
1019
  // environment.
1020
  Util::requireExplicitBareRepository(env);
487 ✔
1021
  // pass under WSL needs them too: the count and every entry below it.
1022
  QStringList gitConfig{QStringLiteral("GIT_CONFIG_COUNT/u")};
974 ✔
1023
  if (env.contains(QStringLiteral("GIT_CONFIG_PARAMETERS"))) {
974 ✔
1024
    gitConfig << QStringLiteral("GIT_CONFIG_PARAMETERS/u");
×
1025
  }
1026
  const int gitConfigCount =
1027
      env.value(QStringLiteral("GIT_CONFIG_COUNT")).toInt();
974 ✔
1028
  for (int i = 0; i < gitConfigCount; ++i) {
974 ✔
1029
    gitConfig << QStringLiteral("GIT_CONFIG_KEY_%1/u").arg(i)
974 ✔
1030
              << QStringLiteral("GIT_CONFIG_VALUE_%1/u").arg(i);
974 ✔
1031
  }
1032
  mergeIntoWslenv(env, gitConfig);
487 ✔
1033

1034
  exec.setEnvironment(env);
487 ✔
1035

1036
  pinStoreGitAttributes();
487 ✔
1037
}
487 ✔
1038

1039
void Pass::pinStoreGitAttributes() {
490 ✔
1040
  if (m_settings.passStore.isEmpty()) {
490 ✔
1041
    return;
481 ✔
1042
  }
1043
  // Only the common layout, where the store is its own repository, is handled
1044
  // by writing directly: a ".git" directory. A worktree ".git" file or a store
1045
  // nested in a larger repository is left as-is rather than risk touching
1046
  // another repository's attributes.
1047
  const QString gitDir =
1048
      QDir(m_settings.passStore).absoluteFilePath(QStringLiteral(".git"));
952 ✔
1049
  if (!QFileInfo(gitDir).isDir()) {
476 ✔
1050
    return;
1051
  }
1052

1053
  // The marker lets us recognise and refresh our own block without disturbing
1054
  // anything a user put in info/attributes by hand. Disabling text/eol,
1055
  // working-tree-encoding, filter and ident keeps Git from rewriting the
1056
  // bytes gpg produced for these paths - a co-writer can push a .gitattributes
1057
  // ("*.gpg text", a working-tree-encoding, a filter) that otherwise corrupts
1058
  // the ciphertext QtPass commits. info/attributes outranks the in-tree file.
1059
  // diff is left alone: it only changes what Git shows, and pass's own
1060
  // "*.gpg diff=gpg" gives decrypted diffs.
1061
  static const QString marker =
1062
      QStringLiteral("# QtPass: keep encrypted store files byte-for-byte");
53 ✔
1063
  const QString block =
1064
      marker + QStringLiteral("\n") +
98 ✔
1065
      QStringLiteral(
98 ✔
1066
          "*.gpg -text -filter -ident -working-tree-encoding\n"
1067
          ".gpg-id -text -filter -ident -working-tree-encoding\n"
1068
          ".gpg-id.sig -text -filter -ident -working-tree-encoding\n");
1069

1070
  const QString infoDir = gitDir + QStringLiteral("/info");
98 ✔
1071
  const QString attrPath = infoDir + QStringLiteral("/attributes");
98 ✔
1072

1073
  QString existing;
49 ✔
1074
  QFile attr(attrPath);
49 ✔
1075
  if (attr.exists()) {
49 ✔
1076
    // Unreadable: writing now would drop the user's own lines in it.
1077
    if (!attr.open(QIODevice::ReadOnly | QIODevice::Text)) {
40 ✔
1078
      qCWarning(lcQtPass) << "Cannot read" << attrPath
×
1079
                          << "to pin attributes:" << attr.errorString();
×
1080
      return;
×
1081
    }
1082
    existing = QString::fromUtf8(attr.readAll());
40 ✔
1083
    attr.close();
40 ✔
1084
    if (existing.contains(block)) {
40 ✔
1085
      return; // already pinned and unchanged
1086
    }
1087
  }
1088

1089
  if (!QDir().mkpath(infoDir)) {
18 ✔
1090
    qCWarning(lcQtPass) << "Cannot create" << infoDir << "to pin attributes";
×
1091
    return;
×
1092
  }
1093

1094
  // Keep any lines the user added themselves (outside our block), then append a
1095
  // fresh copy of our block. A previous QtPass block is dropped so an updated
1096
  // set of lines replaces an older one.
1097
  QString preserved;
9 ✔
1098
  if (!existing.isEmpty()) {
9 ✔
1099
    const QStringList lines = existing.split(QLatin1Char('\n'));
×
1100
    bool inBlock = false;
1101
    for (const QString &line : lines) {
×
1102
      if (line == marker) {
×
1103
        inBlock = true;
1104
        continue;
×
1105
      }
1106
      if (inBlock) {
×
1107
        if (line.startsWith(QStringLiteral("*.gpg ")) ||
×
1108
            line.startsWith(QStringLiteral(".gpg-id ")) ||
×
1109
            line.startsWith(QStringLiteral(".gpg-id.sig "))) {
×
1110
          continue;
×
1111
        }
1112
        inBlock = false;
1113
      }
1114
      preserved += line + QLatin1Char('\n');
×
1115
    }
1116
    while (preserved.endsWith(QStringLiteral("\n\n"))) {
×
1117
      preserved.chop(1);
×
1118
    }
1119
  }
1120

1121
  QSaveFile out(attrPath);
9 ✔
1122
  const QByteArray payload = (preserved + block).toUtf8();
9 ✔
1123
  if (!out.open(QIODevice::WriteOnly | QIODevice::Text) ||
18 ✔
1124
      out.write(payload) != payload.size() || !out.commit()) {
18 ✔
1125
    qCWarning(lcQtPass) << "Cannot write" << attrPath
×
1126
                        << "to pin attributes:" << out.errorString();
×
1127
  }
1128
}
58 ✔
1129

1130
auto Pass::withCurrentGitPin(QProcessEnvironment base) const
1,974 ✔
1131
    -> QProcessEnvironment {
1132
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
1,974 ✔
1133
    return base;
17 ✔
1134
  }
1135
  base.remove(QStringLiteral("GIT_DIR"));
3,914 ✔
1136
  base.remove(QStringLiteral("GIT_WORK_TREE"));
3,914 ✔
1137
  for (const auto &[name, value] : Util::gitStoreVariables(
1138
           m_settings.passStore, m_settings.gitExecutable)) {
5,881 ✔
1139
    base.insert(name, value);
1,967 ✔
1140
  }
1141
  return base;
1,957 ✔
1142
}
1143

1144
auto Pass::maxOutputArgs() -> QStringList {
1,191 ✔
1145
  return {QStringLiteral("--max-output"), QString::number(kMaxPlaintextBytes)};
3,573 ✔
1146
}
1,191 ✔
1147

1148
namespace {
1149
/// File names compare the way the platform's file system compares them:
1150
/// "C:/Store" and "c:/store" are the same directory on Windows.
1151
#ifdef Q_OS_WIN
1152
constexpr auto kPathCase = Qt::CaseInsensitive;
1153
#else
1154
constexpr auto kPathCase = Qt::CaseSensitive;
1155
#endif
1156

1157
/// Whether @p path is @p dir or lies under it.
1158
auto isAtOrUnder(const QString &path, const QString &dir,
4,525 ✔
1159
                 const QString &dirPrefix) -> bool {
1160
  return path.compare(dir, kPathCase) == 0 ||
8,103 ✔
1161
         path.startsWith(dirPrefix, kPathCase);
3,578 ✔
1162
}
1163

1164
/// Where the lookup of a .gpg-id starts and the store that bounds it.
1165
struct GpgIdLookup {
1166
  QDir start;
1167
  /// The folder whose list is wanted, whether it exists or not.
1168
  QString folder;
1169
  QString storeDir;
1170
  QString storePrefix;
1171
};
1172

1173
/// The folder whose list @p for_file wants: its own for a folder, its
1174
/// folder's for an entry.
1175
auto gpgIdLookup(const QString &for_file, const QString &passStore)
1,385 ✔
1176
    -> GpgIdLookup {
1177
  const QString normalizedFile = QDir::fromNativeSeparators(for_file);
1,385 ✔
1178
  // Inside the store means at a path boundary: "/store-other/x" is not
1179
  // under "/store", however the prefix compares.
1180
  const QString storeDir =
1181
      QDir::cleanPath(QDir::fromNativeSeparators(passStore));
1,385 ✔
1182
  const QString storePrefix = storeDir.endsWith(QLatin1Char('/'))
1,385 ✔
1183
                                  ? storeDir
1,385 ✔
1184
                                  : storeDir + QLatin1Char('/');
1,385 ✔
1185
  const QString cleanFile = QDir::cleanPath(normalizedFile);
1,385 ✔
1186
  const bool insideStore = isAtOrUnder(cleanFile, storeDir, storePrefix);
1,385 ✔
1187
  // A relative name is one inside the store; an absolute path outside it
1188
  // stays what it is and the walk stops at once.
1189
  const QString fullPath =
1190
      insideStore || (QDir::isAbsolutePath(cleanFile) &&
21 ✔
1191
                      !cleanFile.startsWith(QLatin1Char(':')))
5 ✔
1192
          ? cleanFile
1,385 ✔
1193
          : storePrefix + cleanFile;
11 ✔
1194
  // A folder (trailing separator, which cleanPath() dropped, or an existing
1195
  // directory) wants its own list; an entry wants its folder's.
1196
  const bool isFolder =
1197
      normalizedFile.endsWith(QLatin1Char('/')) || QFileInfo(fullPath).isDir();
1,385 ✔
1198
  // A folder that does not exist yet (an entry saved into a new folder, a
1199
  // move to one) starts the walk at its nearest existing ancestor in the
1200
  // store, as pass's set_gpg_recipients does: otherwise the walk ended at
1201
  // once and the store root's list was taken over the one in between.
1202
  const QString folder =
1203
      QDir::cleanPath(isFolder ? fullPath : QFileInfo(fullPath).absolutePath());
3,469 ✔
1204
  QString start = folder;
1205
  while (!QFileInfo(start).exists() &&
1,421 ✔
1206
         isAtOrUnder(QDir::cleanPath(start), storeDir, storePrefix) &&
2,824 ✔
1207
         QDir::cleanPath(start) != storeDir) {
1,421 ✔
1208
    start = QFileInfo(start).absolutePath();
36 ✔
1209
  }
1210
  return {QDir(start), folder, storeDir, storePrefix};
1,385 ✔
1211
}
1,385 ✔
1212

1213
/// Whether @p candidate can be its folder's .gpg-id: a regular file, as
1214
/// pass looks for (test -f), so a folder under the name is passed over as
1215
/// pass passes it. A link under the name is not: whoever planted it chose
1216
/// the recipients elsewhere.
1217
auto isOwnGpgId(const QFileInfo &candidate) -> bool {
2,442 ✔
1218
  return candidate.isFile() && !candidate.isSymLink() &&
3,190 ✔
1219
         !candidate.isJunction();
748 ✔
1220
}
1221

1222
/// Walk up from the lookup's start to the first folder inside the store
1223
/// that has its own .gpg-id; nothing when none does. A link under the name
1224
/// is skipped, so the parent's list applies instead.
1225
auto nearestGpgId(const GpgIdLookup &lookup) -> std::optional<QString> {
795 ✔
1226
  QDir dir = lookup.start;
795 ✔
1227
  while (dir.exists() && isAtOrUnder(QDir::cleanPath(dir.absolutePath()),
4,640 ✔
1228
                                     lookup.storeDir, lookup.storePrefix)) {
1,160 ✔
1229
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
1,009 ✔
1230
    if (isOwnGpgId(candidate)) {
1,009 ✔
1231
      return candidate.absoluteFilePath();
644 ✔
1232
    }
1233
    if (!dir.cdUp()) {
365 ✔
1234
      break;
1235
    }
1236
  }
1,009 ✔
1237
  return std::nullopt;
151 ✔
1238
}
795 ✔
1239

1240
} // namespace
1241

1242
auto Pass::heldScopes() -> QSet<QString> & {
278 ✔
1243
  static QSet<QString> scopes;
284 ✔
1244
  return scopes;
278 ✔
1245
}
1246

1247
auto Pass::scopePath(const QString &path) const -> QString {
278 ✔
1248
  return QDir::cleanPath(QDir(m_settings.passStore).absoluteFilePath(path));
556 ✔
1249
}
1250

1251
auto Pass::autoPushHeld() const -> bool {
68 ✔
1252
  const QString store = scopePath(QString());
68 ✔
1253
  const QSet<QString> &scopes = heldScopes();
68 ✔
1254
  return std::any_of(scopes.cbegin(), scopes.cend(),
68 ✔
1255
                     [&store](const QString &s) {
190 ✔
1256
                       return isAtOrUnder(s, store, store + QLatin1Char('/'));
380 ✔
1257
                     });
68 ✔
1258
}
1259

1260
void Pass::GitPushAutomatic() {
15 ✔
1261
  m_pushIsAutomatic = true;
15 ✔
1262
  GitPush();
15 ✔
1263
  m_pushIsAutomatic = false;
15 ✔
1264
}
15 ✔
1265

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

1268
void Pass::holdAutoPush(const QString &scope) {
105 ✔
1269
  heldScopes().insert(scopePath(scope));
105 ✔
1270
}
105 ✔
1271

1272
void Pass::releaseAutoPush(const QString &folder) {
105 ✔
1273
  const QString root = scopePath(folder);
105 ✔
1274
  QSet<QString> &scopes = heldScopes();
105 ✔
1275
  for (auto it = scopes.begin(); it != scopes.end();) {
1276
    it = isAtOrUnder(*it, root, root + QLatin1Char('/')) ? scopes.erase(it)
1,260 ✔
1277
                                                         : std::next(it);
630 ✔
1278
  }
1279
}
105 ✔
1280

1281
auto Pass::refuseLinkedPath(const QString &path, LinkScope scope,
819 ✔
1282
                            PathSpelling spelling) -> bool {
1283
  const QString full = Util::joinPath(m_settings.passStore, path);
819 ✔
1284
  // The link check below walks only under the store as configured: a path
1285
  // spelled through the root's link target would get no more than the
1286
  // entry itself judged. No caller makes one; say so if one starts to.
1287
  if (spelling == PathSpelling::Configured &&
1,343 ✔
1288
      PathValidator::isTargetSpelled(m_settings.passStore, full)) {
524 ✔
1289
    qCWarning(lcQtPass)
4 ✔
1290
        << "Path spelled through the store root's link target, not as the "
1291
           "store is configured; Pass operations expect the configured "
1292
           "spelling:"
2 ✔
1293
        << full;
2 ✔
1294
  }
1295
  if (!Util::isUnderLink(full, m_settings.passStore,
819 ✔
1296
                         scope == LinkScope::EntryAndParents)) {
1297
    return false;
1298
  }
1299
  const QString why =
1300
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
×
1301
         "points to is not part of the password store and is left alone.")
1302
          .arg(QDir::toNativeSeparators(QDir::cleanPath(full)));
62 ✔
1303
  refuseAsNotPartOfStore(why);
31 ✔
1304
  return true;
1305
}
1306

1307
auto Pass::refuseFolderOutsideStore(const QString &folder, QString *relative)
96 ✔
1308
    -> bool {
1309
  if (const std::optional<QString> inStore =
96 ✔
1310
          PathValidator::storeRelativePath(m_settings.passStore, folder)) {
96 ✔
1311
    if (relative != nullptr) {
91 ✔
1312
      *relative = *inStore;
91 ✔
1313
    }
1314
    return false;
1315
  }
1316
  refuseAsNotPartOfStore(
5 ✔
1317
      tr("%1 is not inside the password store. Recipients are set for the "
5 ✔
1318
         "store or a folder in it.")
1319
          .arg(QDir::toNativeSeparators(QDir::cleanPath(folder))));
10 ✔
1320
  return true;
5 ✔
1321
}
1322

1323
auto Pass::unfinishedGitOperationReason() -> QString {
827 ✔
1324
  if (!m_settings.useGit) {
827 ✔
1325
    return {};
614 ✔
1326
  }
1327
  // One git call names the path of each marker file or directory, whether or
1328
  // not it exists; the backend runs it in the store (ImitatePass with
1329
  // `-C <store>`, RealPass through `pass git`). The markers, paired with the
1330
  // operation each one means, in the order git prints them back.
1331
  // The names are Git's own commands, which the user then runs with --abort or
1332
  // --continue; the translator comments say so.
1333
  const std::array<std::pair<QLatin1String, QString>, 6> markers{{
1334
      //: The Git command `git rebase`, inserted into "in the middle of a %1".
1335
      //: Best kept as Git's command name.
1336
      {QLatin1String("rebase-merge"), tr("rebase")},
213 ✔
1337
      //: The Git command `git rebase`, inserted into "in the middle of a %1".
1338
      //: Best kept as Git's command name.
1339
      {QLatin1String("rebase-apply"), tr("rebase")},
213 ✔
1340
      //: The Git command `git merge`, inserted into "in the middle of a %1".
1341
      //: Best kept as Git's command name.
1342
      {QLatin1String("MERGE_HEAD"), tr("merge")},
213 ✔
1343
      //: The Git command `git cherry-pick`, inserted into "in the middle of a
1344
      //: %1". Best kept as Git's command name.
1345
      {QLatin1String("CHERRY_PICK_HEAD"), tr("cherry-pick")},
213 ✔
1346
      //: The Git command `git revert`, inserted into "in the middle of a %1".
1347
      //: Best kept as Git's command name.
1348
      {QLatin1String("REVERT_HEAD"), tr("revert")},
213 ✔
1349
      // A multi-commit cherry-pick or revert keeps its sequencer state after a
1350
      // conflict resolution is committed, when CHERRY_PICK_HEAD/REVERT_HEAD is
1351
      // already gone but `--continue` has more commits to apply. Checked last,
1352
      // so the specific head above names the operation when it is still there.
1353
      //: The Git commands `git cherry-pick` and `git revert`, inserted into
1354
      //: "in the middle of a %1". Best kept as Git's command names.
1355
      {QLatin1String("sequencer"), tr("cherry-pick or revert")},
213 ✔
1356
  }};
×
1357
  QStringList args{QStringLiteral("rev-parse")};
426 ✔
1358
  for (const auto &marker : markers) {
1,491 ✔
1359
    args << QStringLiteral("--git-path") << marker.first;
1,278 ✔
1360
  }
1361
  QString out;
213 ✔
1362
  if (!storeGit(args, &out)) {
213 ✔
1363
    // Git is off, the store is not a repository, or git could not be asked:
1364
    // nothing is refused, as the operation would run anyway.
1365
    return {};
14 ✔
1366
  }
1367
  const QStringList paths = out.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
199 ✔
1368
  for (int i = 0; i < paths.size() && i < static_cast<int>(markers.size());
825 ✔
1369
       ++i) {
1370
    const QString path = paths.at(i).trimmed();
1371
    const QString full = QDir::isAbsolutePath(path)
1372
                             ? path
633 ✔
1373
                             : QDir(m_settings.passStore).filePath(path);
633 ✔
1374
    if (!QFileInfo::exists(full)) {
633 ✔
1375
      continue;
1376
    }
1377
    //: %1 is a Git command name: rebase, merge, cherry-pick, revert, or
1378
    //: "cherry-pick or revert".
1379
    return tr("The password store's Git repository is in the middle of a %1. "
7 ✔
1380
              "Finish or abort it with Git before changing the password store, "
1381
              "or what you change may be lost.")
1382
        .arg(markers.at(static_cast<size_t>(i)).second);
7 ✔
1383
  }
1384
  return {};
192 ✔
1385
}
1386

1387
auto Pass::refusePendingPull() -> bool {
205 ✔
1388
  if (!m_settings.useGit || !exec.hasQueued(Enums::GIT_PULL)) {
252 ✔
1389
    return false;
1390
  }
1391
  const QString why =
1392
      tr("The password store is being updated (a Git pull is in progress). "
1393
         "Wait until it has finished, then try again.");
1394
  // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
1395
  // and is released by processErrorExit(); a refusal starts nothing.
1396
  emit startingExecuteWrapper();
3 ✔
1397
  emit critical(tr("Update in progress"), why);
3 ✔
1398
  emit processErrorExit(1, why);
3 ✔
1399
  return true;
1400
}
1401

1402
auto Pass::initIfUnchanged(const QString &path, const QList<UserInfo> &users,
12 ✔
1403
                           const QString &dir, const QString &passStore,
1404
                           const RecipientsForEditing &read) -> bool {
1405
  m_expectedList = ExpectedList{dir, passStore, read.state, read.recipients};
12 ✔
1406
  m_expectedListRefused = false;
12 ✔
1407
  const auto done = qScopeGuard([this] { m_expectedList.reset(); });
1408
  Init(path, users);
12 ✔
1409
  return !m_expectedListRefused;
12 ✔
1410
}
1411

1412
auto Pass::refuseChangedList() -> bool {
82 ✔
1413
  if (!m_expectedList) {
82 ✔
1414
    return false;
1415
  }
1416
  const RecipientsForEditing now =
1417
      recipientsForEditing(m_expectedList->dir, m_expectedList->passStore);
5 ✔
1418
  if (now.state == m_expectedList->state &&
5 ✔
1419
      now.recipients == m_expectedList->recipients) {
5 ✔
1420
    return false;
1421
  }
1422
  const QString why =
1423
      tr("The recipient list of this folder changed after the users dialog "
1424
         "read it, for example through an update from Git. Nothing was "
1425
         "written. Open the dialog again to see the new list.");
1426
  m_expectedListRefused = true;
3 ✔
1427
  emit startingExecuteWrapper();
3 ✔
1428
  emit critical(tr("Recipients not changed"), why);
3 ✔
1429
  emit processErrorExit(1, why);
3 ✔
1430
  return true;
1431
}
1432

1433
auto Pass::refuseBusyForExpectedList() -> bool {
39 ✔
1434
  if (!m_expectedList || exec.isIdle()) {
39 ✔
1435
    return false;
1436
  }
1437
  const QString why =
1438
      tr("Another operation is still running. Wait until it has finished, "
1439
         "then save the recipients again.");
1440
  m_expectedListRefused = true;
1 ✔
1441
  emit startingExecuteWrapper();
1 ✔
1442
  emit critical(tr("Recipients not changed"), why);
1 ✔
1443
  emit processErrorExit(1, why);
1 ✔
1444
  return true;
1445
}
1446

1447
auto Pass::refuseUnfinishedGitOperation() -> bool {
596 ✔
1448
  const QString why = unfinishedGitOperationReason();
596 ✔
1449
  if (why.isEmpty()) {
596 ✔
1450
    return false;
1451
  }
1452
  // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
1453
  // and is released by finished()/processErrorExit(); a refusal starts
1454
  // nothing, so it emits both ends.
1455
  emit startingExecuteWrapper();
5 ✔
1456
  emit critical(tr("Unfinished Git operation"), why);
5 ✔
1457
  emit processErrorExit(1, why);
5 ✔
1458
  return true;
1459
}
1460

1461
void Pass::refuseAsNotPartOfStore(const QString &why) {
36 ✔
1462
  // The interface arms itself when an operation starts and is released by
1463
  // finished or processErrorExit; a refusal starts nothing, so emits both.
1464
  emit startingExecuteWrapper();
36 ✔
1465
  emit critical(tr("Not part of the store"), why);
36 ✔
1466
  emit processErrorExit(1, why);
36 ✔
1467
}
36 ✔
1468

1469
auto Pass::getGpgIdPath(const QString &for_file, const QString &passStore)
795 ✔
1470
    -> QString {
1471
  return nearestGpgId(gpgIdLookup(for_file, passStore))
1,590 ✔
1472
      .value_or(
1473
          QDir(QDir::fromNativeSeparators(passStore)).filePath(".gpg-id"));
3,180 ✔
1474
}
1475

1476
auto Pass::refuseSkippedGpgId(const QString &file, bool signing,
235 ✔
1477
                              const QString &except, SkippedWalks *walks)
1478
    -> bool {
1479
  // Without a signing key the parent's list applies, as it does for pass.
1480
  if (!signing) {
235 ✔
1481
    return false;
1482
  }
1483
  QString recordError;
53 ✔
1484
  const std::optional<QString> skipped =
1485
      skippedGpgId(file, m_settings.passStore, &recordError, walks);
53 ✔
1486
  if (!skipped || (!except.isEmpty() &&
53 ✔
1487
                   QDir::cleanPath(*skipped) == QDir::cleanPath(except))) {
55 ✔
1488
    return false;
1489
  }
1490
  // The strings keep the context they were translated in.
1491
  if (!recordError.isEmpty()) {
4 ✔
1492
    emit critical(QCoreApplication::translate(
×
1493
                      "ImitatePass", "Cannot check the recipient list"),
1494
                  QCoreApplication::translate(
×
1495
                      "ImitatePass", "%1 Whether %2 was removed cannot be "
1496
                                     "told, so nothing was encrypted.")
1497
                      .arg(recordError, QDir::toNativeSeparators(*skipped)));
×
1498
    return true;
×
1499
  }
1500
  emit critical(
4 ✔
1501
      QCoreApplication::translate("ImitatePass", "Recipient list missing"),
8 ✔
1502
      QCoreApplication::translate(
4 ✔
1503
          "ImitatePass",
1504
          "The signed recipient list %1 is missing or is not a regular file. "
1505
          "QtPass does not fall back to a parent folder's list for it: that "
1506
          "list was not signed for this folder. If a link is under that name, "
1507
          "remove it. Then open Users for that folder and save its "
1508
          "recipients, which writes and signs a fresh list.")
1509
          .arg(QDir::toNativeSeparators(*skipped)));
8 ✔
1510
  return true;
4 ✔
1511
}
1512

1513
auto Pass::verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile,
76 ✔
1514
                            QByteArray *contents, QString *why) const -> bool {
1515
  if (!signer.verifyFile(gpgIdFile, contents)) {
76 ✔
1516
    return false;
1517
  }
1518
  // Authentic and unmodified is not the same as current: an older signed
1519
  // list put back into the store is refused once this device has seen a
1520
  // newer one, and one signed for another folder is refused here.
1521
  QString reason;
59 ✔
1522
  if (GpgIdGeneration::accept(gpgIdFile, *contents, m_settings.passStore,
59 ✔
1523
                              &reason) != GpgIdGeneration::Verdict::Accepted) {
1524
    if (why != nullptr) {
19 ✔
1525
      *why = reason;
14 ✔
1526
    }
1527
    return false;
19 ✔
1528
  }
1529
  return true;
1530
}
1531

1532
auto Pass::skippedGpgId(const QString &forFile, const QString &passStore,
286 ✔
1533
                        QString *recordError, SkippedWalks *walks)
1534
    -> std::optional<QString> {
1535
  const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
286 ✔
1536
  // A folder's answer depends only on it and the folders above it: kept
1537
  // for every folder climbed, a tree check asks each one record lookup,
1538
  // where climbing again from every folder cost depth squared.
1539
  QStringList climbed;
286 ✔
1540
  // By value: on a hit they come out of walks, which the inserts below
1541
  // may rehash.
1542
  const auto answer = [&climbed, walks, recordError](
286 ✔
1543
                          std::optional<QString> skipped, QString why) {
1544
    if (walks != nullptr) {
286 ✔
1545
      for (const QString &folder : std::as_const(climbed)) {
430 ✔
1546
        walks->insert(folder, {skipped, why});
430 ✔
1547
      }
1548
    }
1549
    if (recordError != nullptr && !why.isEmpty()) {
286 ✔
1550
      *recordError = why;
1 ✔
1551
    }
1552
    return skipped;
286 ✔
1553
  };
286 ✔
1554
  // The same walk as nearestGpgId(), stopping at the list it finds, and
1555
  // short of the store root: the root's own list has no parent to fall
1556
  // back to, and the signature check refuses it when it is missing. It
1557
  // starts at the folder asked for, not at its nearest existing one: a
1558
  // folder removed together with its list is asked of the record too.
1559
  QString dir = lookup.folder;
1560
  while (dir.startsWith(lookup.storePrefix, kPathCase)) {
710 ✔
1561
    if (walks != nullptr) {
657 ✔
1562
      if (const auto known = walks->constFind(dir);
413 ✔
1563
          known != walks->constEnd()) {
1564
        return answer(known->skipped, known->recordError);
396 ✔
1565
      }
1566
    }
1567
    climbed << dir;
1568
    const QFileInfo candidate(dir + QStringLiteral("/.gpg-id"));
918 ✔
1569
    if (isOwnGpgId(candidate)) {
459 ✔
1570
      return answer(std::nullopt, QString());
34 ✔
1571
    }
1572
    // A link under the name (dangling or not), or nothing under it where
1573
    // this device accepted a list before: both are the folder's list gone,
1574
    // not a folder that never had one.
1575
    if (candidate.isSymLink() || candidate.isJunction()) {
442 ✔
1576
      return answer(candidate.absoluteFilePath(), QString());
10 ✔
1577
    }
1578
    // An unreadable record is not "never seen": whether a list was accepted
1579
    // here cannot be told, so this folder is refused too (fail closed), with
1580
    // the record's own reason for the caller to show.
1581
    QString why;
437 ✔
1582
    const std::optional<bool> seen =
1583
        GpgIdGeneration::seen(candidate.absoluteFilePath(), &why);
874 ✔
1584
    if (!seen) {
437 ✔
1585
      return answer(candidate.absoluteFilePath(),
2 ✔
1586
                    why.isEmpty()
1587
                        ? tr("The generation record of the recipient lists "
2 ✔
1588
                             "cannot be read.")
1589
                        : why);
1 ✔
1590
    }
1591
    if (*seen) {
436 ✔
1592
      return answer(candidate.absoluteFilePath(), QString());
24 ✔
1593
    }
1594
    const QString parent = QDir::cleanPath(QFileInfo(dir).absolutePath());
848 ✔
1595
    if (parent == dir) {
424 ✔
1596
      break;
1597
    }
1598
    dir = parent;
424 ✔
1599
  }
459 ✔
1600
  return answer(std::nullopt, QString());
106 ✔
1601
}
286 ✔
1602

1603
auto Pass::linkedGpgId(const QString &forFile, const QString &passStore,
304 ✔
1604
                       LinkedWalks *walks) -> std::optional<QString> {
1605
  const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
304 ✔
1606
  // As in skippedGpgId(): a folder's answer depends only on it and the
1607
  // folders above it, so a tree check climbs each folder once instead of
1608
  // once per folder below it.
1609
  QStringList climbed;
304 ✔
1610
  const auto answer = [&climbed, walks](std::optional<QString> linked) {
304 ✔
1611
    if (walks != nullptr) {
304 ✔
1612
      for (const QString &folder : std::as_const(climbed)) {
381 ✔
1613
        walks->insert(folder, linked);
218 ✔
1614
      }
1615
    }
1616
    return linked;
304 ✔
1617
  };
304 ✔
1618
  // The walk of nearestGpgId(), root included, stopping at the list it
1619
  // finds.
1620
  QDir dir = lookup.start;
304 ✔
1621
  while (dir.exists()) {
1,142 ✔
1622
    const QString here = QDir::cleanPath(dir.absolutePath());
1,142 ✔
1623
    if (!isAtOrUnder(here, lookup.storeDir, lookup.storePrefix)) {
1,142 ✔
1624
      break;
1625
    }
1626
    if (walks != nullptr) {
1,062 ✔
1627
      // By value: the inserts in answer() may rehash walks.
1628
      if (const auto known = walks->constFind(here);
306 ✔
1629
          known != walks->constEnd()) {
1630
        return answer(std::optional<QString>(*known));
176 ✔
1631
      }
1632
    }
1633
    climbed << here;
1634
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
974 ✔
1635
    if (isOwnGpgId(candidate)) {
974 ✔
1636
      return answer(std::nullopt);
174 ✔
1637
    }
1638
    if (candidate.isSymLink() || candidate.isJunction()) {
887 ✔
1639
      return answer(candidate.absoluteFilePath());
98 ✔
1640
    }
1641
    if (!dir.cdUp()) {
838 ✔
1642
      break;
1643
    }
1644
  }
974 ✔
1645
  return answer(std::nullopt);
160 ✔
1646
}
608 ✔
1647

1648
namespace {
1649

1650
/// What the Users dialog may preselect for a verified list, given what the
1651
/// generation record says about it.
1652
auto judgedRecipients(GpgIdGeneration::Verdict verdict,
7 ✔
1653
                      const QByteArray &contents, const QString &gpgIdPath,
1654
                      const QString &why) -> Pass::RecipientsForEditing {
1655
  using RecipientsForEditing = Pass::RecipientsForEditing;
1656
  RecipientsForEditing result;
7 ✔
1657
  switch (verdict) {
7 ✔
1658
  case GpgIdGeneration::Verdict::Accepted:
1 ✔
1659
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1660
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1661
    break;
1 ✔
1662
  case GpgIdGeneration::Verdict::Rollback:
1 ✔
1663
    // Authentic and this folder's, only older: the recovery goes through
1664
    // this dialog, so it is preselected, with the reason in view.
1665
    result.state = RecipientsForEditing::State::VerifiedRollback;
1 ✔
1666
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1667
    result.warning = why;
1 ✔
1668
    break;
1 ✔
1669
  case GpgIdGeneration::Verdict::Unbound:
5 ✔
1670
  case GpgIdGeneration::Verdict::Conflict:
1671
  case GpgIdGeneration::Verdict::WrongFolder:
1672
  case GpgIdGeneration::Verdict::WrongStore:
1673
  case GpgIdGeneration::Verdict::Malformed:
1674
  case GpgIdGeneration::Verdict::RecordUnavailable:
1675
    // Signed, but not shown to be this folder's list, not a list to trust,
1676
    // or nothing to judge it by: preselecting it would sign it in.
1677
    result.state = RecipientsForEditing::State::Rejected;
5 ✔
1678
    result.warning =
1679
        Pass::tr("%1 Nothing is preselected: saving would sign whatever is "
5 ✔
1680
                 "in it. Select the recipients yourself.")
1681
            .arg(why);
10 ✔
1682
    break;
5 ✔
1683
  }
1684
  return result;
7 ✔
1685
}
1686

1687
} // namespace
1688

1689
auto Pass::recipientsForEditing(const QString &dir, const QString &passStore)
89 ✔
1690
    -> RecipientsForEditing {
1691
  RecipientsForEditing result;
89 ✔
1692
  const QString folder = dir.isEmpty() ? QString() : dir;
89 ✔
1693
  const QString gpgIdPath = getGpgIdPath(folder, passStore);
89 ✔
1694
  GpgIdSigner signer(m_settings.gpgExecutable,
1695
                     GpgIdSigner::keysFromSetting(m_settings.passSigningKey));
267 ✔
1696
  signer.setStoreRoot(passStore);
1697
  if (!signer.enabled()) {
89 ✔
1698
    // A list that is there but cannot be read as one (too large, not a
1699
    // regular file, unreadable) is not an empty list: preselecting nothing
1700
    // without a word would let OK write a new list over it, and later
1701
    // re-encryptions drop whoever it named.
1702
    // Read once and parsed from those bytes: a second read could find
1703
    // something else under the name. A link counts as there, dangling too.
1704
    const QFileInfo info(gpgIdPath);
79 ✔
1705
    if (!info.exists() && !info.isSymLink()) {
79 ✔
1706
      result.state = RecipientsForEditing::State::Unsigned;
1707
      return result;
18 ✔
1708
    }
1709
    const std::optional<QByteArray> bytes = Util::readRegularFileInStore(
1710
        passStore, gpgIdPath, Util::kMaxGpgIdBytes);
61 ✔
1711
    if (!bytes) {
61 ✔
1712
      result.state = RecipientsForEditing::State::Rejected;
2 ✔
1713
      result.warning =
1714
          tr("%1 cannot be read as a recipient list (a regular file of at "
2 ✔
1715
             "most %2), so nothing is preselected. Check it before choosing "
1716
             "recipients here: OK writes a new list over it.")
1717
              .arg(gpgIdPath,
2 ✔
1718
                   QLocale().formattedDataSize(Util::kMaxGpgIdBytes));
4 ✔
1719
      return result;
2 ✔
1720
    }
1721
    result.state = RecipientsForEditing::State::Unsigned;
1722
    result.recipients = parseRecipients(*bytes, gpgIdPath);
59 ✔
1723
    const QString misread = passReadsDifferently(*bytes);
59 ✔
1724
    if (!misread.isEmpty()) {
59 ✔
1725
      //: %1 is the list's path, %2 says what is wrong with it.
1726
      result.warning =
1727
          tr("pass reads %1 differently from this dialog (%2), so it may "
3 ✔
1728
             "encrypt to recipients not shown here. QtPass will not encrypt "
1729
             "with it through pass: check the recipients, then OK writes the "
1730
             "list anew.")
1731
              .arg(gpgIdPath, misread);
6 ✔
1732
    }
1733
    return result;
59 ✔
1734
  }
79 ✔
1735
  QString recordError;
10 ✔
1736
  if (const std::optional<QString> skipped =
10 ✔
1737
          skippedGpgId(folder, passStore, &recordError)) {
10 ✔
1738
    // The folder's own list was removed or replaced by a link (or the record
1739
    // that would tell cannot be read): the list the walk found further up
1740
    // was not signed for this folder, so preselecting it would sign it in
1741
    // here with one click.
1742
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1743
    result.warning =
1744
        recordError.isEmpty()
1745
            ? tr("The recipient list %1 is missing or is not a regular file, "
2 ✔
1746
                 "so nothing is preselected: the list of a parent folder was "
1747
                 "not signed for this one. Select this folder's recipients "
1748
                 "yourself; OK writes and signs a fresh list.")
1749
                  .arg(*skipped)
1750
            : tr("%1 Nothing is preselected: whether %2 was removed cannot "
1 ✔
1751
                 "be told.")
1752
                  .arg(recordError, *skipped);
1753
    return result;
1 ✔
1754
  }
1755
  if (!QFileInfo::exists(gpgIdPath)) {
9 ✔
1756
    // A folder without a list yet (new store, new profile): nothing to
1757
    // verify and nothing to preselect.
1758
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1759
    return result;
1 ✔
1760
  }
1761
  QByteArray contents;
8 ✔
1762
  if (!signer.verifyFile(gpgIdPath, &contents)) {
8 ✔
1763
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1764
    result.warning =
1765
        tr("The recipient list %1 does not verify against the signing key, "
1 ✔
1766
           "so nothing is preselected: saving would sign whatever is in it. "
1767
           "Select the recipients yourself; OK writes and signs a fresh list.")
1768
            .arg(gpgIdPath);
2 ✔
1769
    return result;
1 ✔
1770
  }
1771
  QString why;
7 ✔
1772
  const GpgIdGeneration::Verdict verdict =
1773
      GpgIdGeneration::accept(gpgIdPath, contents, passStore, &why);
7 ✔
1774
  return judgedRecipients(verdict, contents, gpgIdPath, why);
7 ✔
1775
}
89 ✔
1776

1777
auto Pass::getRecipientList(const QString &for_file, const QString &passStore)
57 ✔
1778
    -> QStringList {
1779
  const QString gpgIdPath = getGpgIdPath(for_file, passStore);
57 ✔
1780
  // The root .gpg-id comes back whatever it is; a link is not a list.
1781
  if (Util::isLinkedFolder(gpgIdPath)) {
57 ✔
1782
    return {};
1 ✔
1783
  }
1784
  const std::optional<QByteArray> bytes =
1785
      Util::readRegularFileInStore(passStore, gpgIdPath, Util::kMaxGpgIdBytes);
56 ✔
1786
  if (!bytes) {
56 ✔
1787
    return {};
29 ✔
1788
  }
1789
  return parseRecipients(*bytes, gpgIdPath);
27 ✔
1790
}
1791

1792
auto Pass::parseRecipients(const QByteArray &contents,
317 ✔
1793
                           const QString &sourceName) -> QStringList {
1794
  QStringList recipients;
317 ✔
1795
  const QString text = QString::fromUtf8(contents);
1796
  for (const QString &line : text.split(QLatin1Char('\n'))) {
7,181 ✔
1797
    QString recipient = line.split(QLatin1Char('#')).first().trimmed();
13,728 ✔
1798
    if (recipient.isEmpty()) {
6,864 ✔
1799
      continue;
418 ✔
1800
    }
1801
    if (!Util::isValidKeyId(recipient)) {
6,446 ✔
1802
      // Never drop a recipient silently: the list is written back verbatim
1803
      // by UsersDialog, so a skipped line disappears from .gpg-id.
1804
      qCWarning(lcQtPass) << "Skipping unusable recipient in" << sourceName
4 ✔
1805
                          << ":" << recipient;
2 ✔
1806
      continue;
2 ✔
1807
    }
2 ✔
1808
    recipients += recipient;
1809
  }
1810
  return recipients;
317 ✔
1811
}
1812

1813
auto Pass::passReadsDifferently(const QByteArray &contents) -> QString {
106 ✔
1814
  if (contents.startsWith("\xEF\xBB\xBF")) {
106 ✔
1815
    return tr("it starts with a byte-order mark");
1816
  }
1817
  if (contents.contains('\0')) {
105 ✔
1818
    return tr("it holds a NUL byte");
1819
  }
1820
  if (contents.contains('\r')) {
103 ✔
1821
    return tr("it has Windows line ends (a carriage return)");
1822
  }
1823
  const QString text = QString::fromUtf8(contents);
1824
  if (text.toUtf8() != contents) {
102 ✔
1825
    return tr("it is not valid UTF-8");
1826
  }
1827
  const QStringList lines = text.split(QLatin1Char('\n'));
101 ✔
1828
  for (qsizetype i = 0; i < lines.size(); ++i) {
6,429 ✔
1829
    const QString &line = lines.at(i);
1830
    const QString recipient = line.left(line.indexOf(QLatin1Char('#')));
6,338 ✔
1831
    for (const QChar c : recipient) {
132,789 ✔
1832
      // read strips blanks and tabs; trimmed() strips every space.
1833
      if (c.isSpace() && c != QLatin1Char(' ') && c != QLatin1Char('\t')) {
126,458 ✔
1834
        return tr("line %1 holds whitespace other than blanks and tabs")
7 ✔
1835
            .arg(i + 1);
7 ✔
1836
      }
1837
    }
1838
    const QString trimmed = recipient.trimmed();
1839
    if (trimmed.startsWith(QLatin1Char('-'))) {
6,331 ✔
1840
      return tr("line %1 starts with a dash").arg(i + 1);
2 ✔
1841
    }
1842
    // The text after the last line feed: read hands it over but the loop
1843
    // ends without using it.
1844
    if (i == lines.size() - 1 && !trimmed.isEmpty()) {
6,329 ✔
1845
      return tr("its last line has no line end");
1846
    }
1847
  }
1848
  return {};
91 ✔
1849
}
1850

1851
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
1852
 */
1853

1854
auto Pass::boundedRandom(quint32 bound) -> quint32 {
7,620 ✔
1855
  if (bound < 2) {
7,620 ✔
1856
    return 0;
1857
  }
1858

1859
  quint32 randval;
1860
  // arc4random_uniform-style rejection against modulo bias: drop values
1861
  // below 2^32 % bound, which (1 + ~bound) % bound computes in quint32.
1862
  const quint32 rejectionThreshold = (1 + ~bound) % bound;
7,616 ✔
1863

1864
  do {
1865
    randval = QRandomGenerator::system()->generate();
1866
  } while (randval < rejectionThreshold);
7,616 ✔
1867

1868
  return randval % bound;
7,616 ✔
1869
}
1870

1871
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,209 ✔
1872
    -> QString {
1873
  if (charset.isEmpty() || length == 0U) {
1,209 ✔
1874
    return {};
2 ✔
1875
  }
1876
  QString out;
1,207 ✔
1877
  for (unsigned int i = 0; i < length; ++i) {
8,827 ✔
1878
    out.append(charset.at(static_cast<int>(
7,620 ✔
1879
        boundedRandom(static_cast<quint32>(charset.length())))));
7,620 ✔
1880
  }
1881
  return out;
1882
}
1883

1884
auto Pass::pullTimedOut(int timeoutMs) -> QString {
2 ✔
1885
  // The count in a variable first: older lupdate versions lose a tr() with
1886
  // template arguments among its arguments.
1887
  const int seconds = (timeoutMs + 999) / 1000;
2 ✔
1888
  return tr("Git pull did not finish within %n second(s); editing the entry "
1889
            "as it is here.",
1890
            nullptr, seconds);
2 ✔
1891
}
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