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

IJHack / QtPass / 46165298070

28 Nov 2026 04:27PM UTC coverage: 94.471% (+0.03%) from 94.442%
46165298070

push

github

web-flow
Refuse a recipient key that another key also holds (#2383)

gpg resolves a .gpg-id fingerprint or key ID among primary keys and
subkeys, and anyone can bind another person's public key to their own
as a subkey. After the user imported such an update of a colleague's
key, every entry saved or re-encrypted for the person the line names
was encrypted to the colleague instead, silently, with no access to
the store needed.

Pass::keyLinesHeldTwice() lists the keyring once, in the store's
environment, and finds every key ID or fingerprint line (grouped with
spaces too) that more than one key block holds. Such a line is
refused, naming both keys:

- native backend: Insert(), Init() and each folder of a re-encryption
  run;
- pass backend: insert, init and move/copy, right before pass runs and
  including every folder's own list below that pass re-encrypts to;
- the Users dialog keeps such a line as written, with a warning, and
  does not probe or search it;
- "Export my public key" refuses, and exports in the store's keyring.

A gpg that starts but cannot list its keyring refuses too; one that
does not start fails as before. Each check runs after the existing
refusals. Lost convenience: such a folder cannot be saved to until the
key that claims someone else's is deleted.

Tests: the listing parser (fingerprints, key IDs, "!", grouped lines,
v5 naming); ImitatePass refuses Insert() and re-encryption with nothing
encrypted, and a keyring that cannot be listed; RealPass refuses insert
and an init with a child list held twice (also past a decoy x.gpg
folder); the Users dialog keeps the line; export refuses. Each guard
was reverted once and its test failed.

Scan finding ANT-2026-ZQIJE21W.

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

164 of 170 new or added lines in 6 files covered. (96.47%)

10764 of 11394 relevant lines covered (94.47%)

24513.83 hits per line

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

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

37
#include "qtpasslogging.h"
38

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

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

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

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

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

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

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

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

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

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

170
void Pass::init(const AppSettings &settings) {
941 ✔
171
  m_settings = settings;
941 ✔
172
#ifdef __APPLE__
173
  // If it exists, prepend gpgtools to PATH
174
  if (QFile(QStringLiteral("/usr/local/MacGPG2/bin")).exists())
175
    env.insert(QStringLiteral("PATH"),
176
               QStringLiteral("/usr/local/MacGPG2/bin:") +
177
                   env.value(QStringLiteral("PATH")));
178
  // Add missing /usr/local/bin (exact component match, no leading colon)
179
  const QString currentPath = env.value(QStringLiteral("PATH"));
180
  if (!currentPath.split(':', Qt::SkipEmptyParts)
181
           .contains(QStringLiteral("/usr/local/bin"))) {
182
    env.insert(QStringLiteral("PATH"),
183
               currentPath.isEmpty()
184
                   ? QStringLiteral("/usr/local/bin")
185
                   : QStringLiteral("/usr/local/bin:") + currentPath);
186
  }
187
#endif
188

189
  // The configured gpgHome wins over GNUPGHOME only when it exists: a stale
190
  // one (#1711) fails every gpg call with "No secret key". Clearing the
191
  // setting restores the inherited value rather than keeping the old path.
192
  const QString inheritedHome = QProcessEnvironment::systemEnvironment().value(
1,882 ✔
193
      QStringLiteral("GNUPGHOME"));
1,882 ✔
194
  const auto useInheritedHome = [this, &inheritedHome]() {
883 ✔
195
    if (inheritedHome.isEmpty()) {
883 ✔
196
      env.remove(QStringLiteral("GNUPGHOME"));
1,220 ✔
197
    } else {
198
      env.insert(QStringLiteral("GNUPGHOME"), inheritedHome);
546 ✔
199
    }
200
  };
1,824 ✔
201
  if (m_settings.gpgHome.isEmpty()) {
941 ✔
202
    useInheritedHome();
881 ✔
203
  } else {
204
    QDir absHome(m_settings.gpgHome);
60 ✔
205
    absHome.makeAbsolute();
60 ✔
206
    if (absHome.exists()) {
60 ✔
207
      env.insert(QStringLiteral("GNUPGHOME"), absHome.path());
116 ✔
208
    } else {
209
      if (inheritedHome.isEmpty()) {
2 ✔
210
        qCWarning(lcQtPass) << "gpgHome" << absHome.path()
2 ✔
211
                            << "does not exist; using the default GnuPG home";
1 ✔
212
        emit statusMsg(tr("Configured GPG home %1 does not exist, using the "
1 ✔
213
                          "default keyring")
214
                           .arg(absHome.path()),
2 ✔
215
                       5000);
216
      } else {
217
        qCWarning(lcQtPass)
2 ✔
218
            << "gpgHome" << absHome.path() << "does not exist; using GNUPGHOME"
2 ✔
219
            << inheritedHome << "from the environment";
1 ✔
220
        emit statusMsg(tr("Configured GPG home %1 does not exist, using "
1 ✔
221
                          "GNUPGHOME %2 from the environment")
222
                           .arg(absHome.path(), inheritedHome),
2 ✔
223
                       5000);
224
      }
225
      useInheritedHome();
2 ✔
226
    }
227
  }
60 ✔
228
}
941 ✔
229

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

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

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

330
namespace {
331
auto resolveWslGpgconfPath(const QString &lastPart) -> QString {
8 ✔
332
  qsizetype lastSep = lastPart.lastIndexOf('/');
8 ✔
333
  if (lastSep < 0) {
8 ✔
334
    lastSep = lastPart.lastIndexOf('\\');
5 ✔
335
  }
336
  if (lastSep >= 0) {
5 ✔
337
    return lastPart.left(lastSep + 1) + "gpgconf";
6 ✔
338
  }
339
  return QStringLiteral("gpgconf");
5 ✔
340
}
341

342
QString findGpgconfInGpgDir(const QString &gpgPath) {
8 ✔
343
  QFileInfo gpgInfo(gpgPath);
8 ✔
344
  if (!gpgInfo.isAbsolute()) {
8 ✔
345
    return {};
1 ✔
346
  }
347

348
  QDir dir(gpgInfo.absolutePath());
7 ✔
349

350
#ifdef Q_OS_WIN
351
  QFileInfo candidateExe(dir.filePath("gpgconf.exe"));
352
  if (candidateExe.isExecutable()) {
353
    return candidateExe.filePath();
354
  }
355
#endif
356

357
  QFileInfo candidate(dir.filePath("gpgconf"));
7 ✔
358
  if (candidate.isExecutable()) {
7 ✔
359
    return candidate.filePath();
5 ✔
360
  }
361
  return {};
2 ✔
362
}
8 ✔
363

364
} // namespace
365

366
auto Pass::resolveGpgconfCommand(const QString &gpgPath)
22 ✔
367
    -> ResolvedGpgconfCommand {
368
  if (gpgPath.trimmed().isEmpty()) {
22 ✔
369
    return {"gpgconf", {}};
370
  }
371

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

383
  const QStringList parts = QProcess::splitCommand(gpgPath);
12 ✔
384
  if (parts.isEmpty()) {
12 ✔
385
    return {"gpgconf", {}};
386
  }
387
  const QString first = parts.first();
388
  if (QFileInfo(first).fileName().compare("wsl", Qt::CaseInsensitive) == 0 ||
33 ✔
389
      QFileInfo(first).fileName().compare("wsl.exe", Qt::CaseInsensitive) ==
30 ✔
390
          0) {
391
    return {"gpgconf", {}};
392
  }
393

394
  if (!first.contains('/') && !first.contains('\\')) {
9 ✔
395
    return {"gpgconf", {}};
396
  }
397

398
  QString gpgconfPath = findGpgconfInGpgDir(first);
8 ✔
399
  if (!gpgconfPath.isEmpty()) {
8 ✔
400
    return {gpgconfPath, {}};
5 ✔
401
  }
402

403
  return {"gpgconf", {}};
404
}
22 ✔
405

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

423
  // A stale gpg-agent holding the key database lock causes "database locked"
424
  // timeouts during key generation.
425
  ResolvedGpgconfCommand resolvedGpgconf = resolveGpgconfCommand(gpgPath);
2 ✔
426
  QStringList killArgs = resolvedGpgconf.arguments;
427
  killArgs << "--kill";
2 ✔
428
  killArgs << "gpg-agent";
2 ✔
429
  // Use same environment as key generation to target correct gpg-agent
430
  if (Executor::executeBlocking(env, resolvedGpgconf.program, killArgs) != 0) {
2 ✔
431
    qCWarning(lcQtPass) << "Failed to kill gpg-agent";
2 ✔
432
  }
433

434
  executeWrapper(GPG_GENKEYS, gpgPath, {"--gen-key", "--no-tty", "--batch"},
16 ✔
435
                 std::move(batch), true, true);
436
}
437

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

469
/**
470
 * @brief One key block of a colon listing: its primary fingerprint and
471
 *        name, and the key IDs and fingerprints of the key and its subkeys.
472
 */
473
struct KeyBlock {
474
  QString primary;    ///< Primary fingerprint, upper case.
475
  QString name;       ///< First user ID.
476
  QStringList keyIds; ///< Key IDs of the key and its subkeys.
477
  QStringList fprs;   ///< Fingerprints of the key and its subkeys.
478
};
479

480
/**
481
 * @brief Split a `--with-colons --with-fingerprint
482
 *        --with-subkey-fingerprint` listing into key blocks, once.
483
 * @param listing The listing.
484
 * @return The blocks, in listing order.
485
 */
486
auto keyBlocks(const QString &listing) -> QList<KeyBlock> {
264 ✔
487
  QList<KeyBlock> blocks;
264 ✔
488
  bool expectPrimary = false;
489
  for (const QString &line :
490
       listing.split(Util::newLinesRegex(), Qt::SkipEmptyParts)) {
1,789 ✔
491
    const QStringList f = line.split(QLatin1Char(':'));
1,525 ✔
492
    const QString type = f.value(0);
1,525 ✔
493
    if (type == QLatin1String("pub")) {
1,525 ✔
494
      blocks.append(KeyBlock{});
620 ✔
495
      blocks.last().keyIds << f.value(4).toUpper();
620 ✔
496
      expectPrimary = true;
497
    } else if (blocks.isEmpty()) {
1,215 ✔
498
      continue;
499
    } else if (type == QLatin1String("sub")) {
1,098 ✔
500
      blocks.last().keyIds << f.value(4).toUpper();
478 ✔
501
      expectPrimary = false;
502
    } else if (type == QLatin1String("fpr")) {
859 ✔
503
      const QString fpr = f.value(9).toUpper();
1,098 ✔
504
      blocks.last().fprs << fpr;
549 ✔
505
      if (expectPrimary) {
549 ✔
506
        blocks.last().primary = fpr;
310 ✔
507
        expectPrimary = false;
508
      }
509
    } else if (type == QLatin1String("uid") && blocks.last().name.isEmpty()) {
620 ✔
510
      blocks.last().name = Util::displayable(f.value(9), false);
614 ✔
511
    }
512
  }
513
  return blocks;
264 ✔
514
}
515

516
/**
517
 * @brief How a holder is named: its first user ID and key ID (a v4
518
 *        fingerprint's tail, a v5/v6 one's head).
519
 * @param block The holder.
520
 * @return The name.
521
 */
522
auto holderName(const KeyBlock &block) -> QString {
185 ✔
523
  const QString id = block.primary.size() == 64 ? block.primary.left(16)
185 ✔
524
                                                : block.primary.right(16);
185 ✔
525
  return block.name.isEmpty() ? id
185 ✔
526
                              : QStringLiteral("%1 (%2)").arg(block.name, id);
367 ✔
527
}
528
} // namespace
529

530
auto Pass::fullKeyListing(QString *listing) -> int {
39 ✔
531
  // In the store's environment: the keyring encryption uses.
532
  QProcess process;
39 ✔
533
  process.setProcessEnvironment(storeEnvironment());
39 ✔
534
  return Executor::executeBlocking(
312 ✔
535
      process, m_settings.gpgExecutable,
39 ✔
536
      {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
39 ✔
537
       QStringLiteral("--with-colons"), QStringLiteral("--with-fingerprint"),
39 ✔
538
       QStringLiteral("--with-subkey-fingerprint"),
39 ✔
539
       QStringLiteral("--list-keys")},
39 ✔
540
      QString(), listing);
78 ✔
541
}
39 ✔
542

543
auto Pass::exportPublicKeys(const QString &gpg, const QStringList &keys,
2 ✔
544
                            QString *out, QString *err) -> int {
545
  QProcess process;
2 ✔
546
  process.setProcessEnvironment(storeEnvironment());
2 ✔
547
  return Executor::executeBlocking(
2 ✔
548
      process, gpg,
549
      QStringList{QStringLiteral("--armor"), QStringLiteral("--export")} + keys,
8 ✔
550
      QString(), out, err);
4 ✔
551
}
2 ✔
552

553
auto Pass::refuseKeyLinesHeldTwice(const QStringList &lines) -> bool {
305 ✔
554
  const std::optional<QHash<QString, QStringList>> held =
555
      keyLinesHeldTwice(lines);
305 ✔
556
  if (held && held->isEmpty()) {
305 ✔
557
    return false;
558
  }
559
  emit critical(held ? tr("A recipient key is held twice")
15 ✔
560
                     : tr("Cannot check the recipient keys"),
561
                describeKeyLinesHeldTwice(held));
5 ✔
562
  return true;
5 ✔
563
}
564

565
auto Pass::enabledKeyLines(const QList<UserInfo> &users) -> QStringList {
77 ✔
566
  QStringList lines;
77 ✔
567
  for (const UserInfo &user : users) {
162 ✔
568
    if (user.enabled) {
85 ✔
569
      lines << user.key_id;
84 ✔
570
    }
571
  }
572
  return lines;
77 ✔
573
}
574

575
auto Pass::keyLinesHeldTwice(const QStringList &lines)
353 ✔
576
    -> std::optional<QHash<QString, QStringList>> {
577
  if (std::none_of(lines.cbegin(), lines.cend(), [](const QString &line) {
353 ✔
578
        return !keyOfLine(line).isEmpty();
6,329 ✔
579
      })) {
580
    return QHash<QString, QStringList>();
84 ✔
581
  }
582
  QString listing;
269 ✔
583
  const int rc = fullKeyListing(&listing);
269 ✔
584
  // A gpg that does not start encrypts to nobody either: the operation
585
  // fails on its own, as it did before this check. One that starts but
586
  // cannot list its keyring is not trusted to resolve a key line.
587
  if (rc == -1) {
269 ✔
588
    return QHash<QString, QStringList>();
7 ✔
589
  }
590
  if (rc != 0) {
262 ✔
591
    return std::nullopt;
1 ✔
592
  }
593
  return keyLinesHeldTwiceIn(lines, listing);
261 ✔
594
}
595

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

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

649
auto Pass::encryptionReaches(const QStringList &recipients)
77 ✔
650
    -> std::optional<QStringList> {
651
  if (recipients.isEmpty()) {
77 ✔
652
    return std::nullopt;
×
653
  }
654
  QTemporaryDir scratch;
77 ✔
655
  if (!scratch.isValid()) {
77 ✔
656
    return std::nullopt;
×
657
  }
658
  const QString &gpg = m_settings.gpgExecutable;
77 ✔
659
  const QString probe = Executor::translatePathForWsl(
660
      scratch.filePath(QStringLiteral("probe.gpg")), gpg);
154 ✔
661
  // --no-throw-keyids: with throw-keyids in gpg.conf the probe would name
662
  // no one.
663
  QStringList args{QStringLiteral("--batch"),
154 ✔
664
                   QStringLiteral("--no-tty"),
77 ✔
665
                   QStringLiteral("--yes"),
77 ✔
666
                   QStringLiteral("--quiet"),
77 ✔
667
                   QStringLiteral("--no-throw-keyids"),
77 ✔
668
                   QStringLiteral("--no-auto-key-locate"),
77 ✔
669
                   QStringLiteral("--no-encrypt-to"),
77 ✔
670
                   QStringLiteral("--output"),
77 ✔
671
                   probe,
672
                   QStringLiteral("--encrypt")};
924 ✔
673
  for (const QString &recipient : recipients) {
6,238 ✔
674
    args << QStringLiteral("-r") << recipient;
6,161 ✔
675
  }
676
  if (Executor::executeBlocking(gpg, args, QStringLiteral("probe")) != 0) {
154 ✔
677
    return std::nullopt;
18 ✔
678
  }
679
  // As ImitatePass::getKeysFromFile(): --decrypt --list-only, capped.
680
  QString status;
59 ✔
681
  if (Executor::executeBlocking(
708 ✔
682
          gpg,
683
          {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
59 ✔
684
           QStringLiteral("--decrypt"), QStringLiteral("--list-only"),
59 ✔
685
           QStringLiteral("--max-output"), QStringLiteral("1"),
59 ✔
686
           QStringLiteral("--status-fd=1"),
59 ✔
687
           QStringLiteral("--keyid-format=long"), QStringLiteral("--"), probe},
59 ✔
688
          QString(), &status) != 0) {
118 ✔
689
    return QStringList();
×
690
  }
691
  static const QRegularExpression encTo(
692
      QStringLiteral("^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
65 ✔
693
  QStringList ids;
59 ✔
694
  for (const QString &line :
695
       status.split(Util::newLinesRegex(), Qt::SkipEmptyParts)) {
336 ✔
696
    const QRegularExpressionMatch match = encTo.match(line);
218 ✔
697
    if (match.hasMatch()) {
218 ✔
698
      ids << match.captured(1).toUpper();
12 ✔
699
    }
700
  }
218 ✔
701
  return ids;
702
}
77 ✔
703

704
auto Pass::listKeys(QStringList keystrings, bool secret) -> QList<UserInfo> {
198 ✔
705
  QStringList args = {"--no-tty", "--with-colons", "--with-fingerprint"};
1,386 ✔
706
  args.append(secret ? "--list-secret-keys" : "--list-keys");
522 ✔
707

708
  for (const QString &keystring : std::as_const(keystrings)) {
6,472 ✔
709
    if (!keystring.isEmpty()) {
6,274 ✔
710
      args.append(keystring);
711
    }
712
  }
713
  QString p_out;
198 ✔
714
  if (Executor::executeBlocking(m_settings.gpgExecutable, args, &p_out) != 0) {
198 ✔
715
    return {};
6 ✔
716
  }
717
  return parseGpgColonOutput(p_out, secret);
192 ✔
718
}
719

720
auto Pass::listKeys(const QString &keystring, bool secret) -> QList<UserInfo> {
155 ✔
721
  return listKeys(QStringList(keystring), secret);
310 ✔
722
}
723

724
namespace {
725

726
auto containsAny(const QString &str, const QStringList &patterns) -> bool {
127 ✔
727
  for (const QString &p : patterns) {
352 ✔
728
    if (str.contains(p)) {
246 ✔
729
      return true;
730
    }
731
  }
732
  return false;
733
}
734

735
// @p patterns must already be lowercase; only @p str is lowered.
736
auto containsAnyCaseInsensitive(const QString &str, const QStringList &patterns)
107 ✔
737
    -> bool {
738
  const QString lower = str.toLower();
739
  for (const QString &p : patterns) {
265 ✔
740
    if (lower.contains(p)) {
169 ✔
741
      return true;
742
    }
743
  }
744
  return false;
745
}
746

747
} // namespace
748

749
auto gpgErrorMessage(const QString &err) -> QString {
47 ✔
750
  // Machine-readable status tokens added by --status-fd 2
751
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYEXPIRED"),
235 ✔
752
                        QStringLiteral("[GNUPG:] INV_RECP 5 ")}))
47 ✔
753
    return QCoreApplication::translate(
754
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
755
                "replace it.");
5 ✔
756
  if (containsAny(err, {QStringLiteral("[GNUPG:] KEYREVOKED"),
210 ✔
757
                        QStringLiteral("[GNUPG:] INV_RECP 4 ")}))
42 ✔
758
    return QCoreApplication::translate(
759
        "Pass", "Encryption failed: GPG key has been revoked.");
4 ✔
760
  if (containsAny(err, {QStringLiteral("[GNUPG:] NO_PUBKEY"),
190 ✔
761
                        QStringLiteral("[GNUPG:] INV_RECP")}))
38 ✔
762
    return QCoreApplication::translate(
763
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
764
                "Check that the key ID in .gpg-id is correct and imported.");
12 ✔
765
  if (err.contains(QStringLiteral("[GNUPG:] FAILURE")))
26 ✔
766
    return QCoreApplication::translate(
767
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
768

769
  // Locale-dependent fallbacks
770
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has expired"),
100 ✔
771
                                       QLatin1String("key expired")}))
772
    return QCoreApplication::translate(
773
        "Pass", "Encryption failed: GPG key has expired. Please renew or "
774
                "replace it.");
1 ✔
775
  if (containsAnyCaseInsensitive(err, {QLatin1String("key has been revoked"),
96 ✔
776
                                       QLatin1String("revoked")}))
777
    return QCoreApplication::translate(
778
        "Pass", "Encryption failed: GPG key has been revoked.");
1 ✔
779
  // pass passes no --status-fd, so this is all gpg says about a key that is
780
  // present but cannot encrypt: expired, revoked, without an encryption
781
  // subkey, or not trusted ("There is no assurance this key belongs to the
782
  // named user"). "Not found ... imported" would send the user the wrong
783
  // way; gpg's own lines, shown below this, say which it is.
784
  if (containsAnyCaseInsensitive(err, {QLatin1String("unusable public key")}))
69 ✔
785
    return QCoreApplication::translate(
786
        "Pass", "Encryption failed: a recipient's GPG key cannot be used. It "
787
                "may have expired or been revoked, have no encryption subkey, "
788
                "or not be trusted; gpg's message below says which.");
3 ✔
789
  if (containsAnyCaseInsensitive(err, {QLatin1String("no public key"),
80 ✔
790
                                       QLatin1String("no secret key")}))
791
    return QCoreApplication::translate(
792
        "Pass", "Encryption failed: recipient GPG key not found or invalid. "
793
                "Check that the key ID in .gpg-id is correct and imported.");
5 ✔
794
  if (containsAnyCaseInsensitive(err, {QLatin1String("encryption failed")}))
45 ✔
795
    return QCoreApplication::translate(
796
        "Pass", "Encryption failed. Check that your GPG key is valid.");
1 ✔
797

798
  return {};
14 ✔
799
}
×
800

801
void Pass::finished(int id, int exitCode, const QString &out,
319 ✔
802
                    const QString &err) {
803
  auto pid = static_cast<PROCESS>(id);
319 ✔
804

805
  // Pop the Show() this completion belongs to whether it worked or not, or
806
  // the next result would be attributed to the wrong file.
807
  QString shownFile;
319 ✔
808
  if (pid == PASS_SHOW && !m_pendingShows.isEmpty()) {
319 ✔
809
    shownFile = m_pendingShows.dequeue();
80 ✔
810
  }
811
  // Count this insert off, success or failure, before its result goes out, so
812
  // insertsPending() tracks the inserts still awaiting a report. Each insert
813
  // reaches here once as PASS_INSERT.
814
  // Its entry is handed out (reportedInsert()) while the report goes out.
815
  QString reported;
319 ✔
816
  if (pid == PASS_INSERT && m_insertsPending > 0) {
319 ✔
817
    --m_insertsPending;
118 ✔
818
    if (!m_insertedEntries.isEmpty()) {
118 ✔
819
      reported = m_insertedEntries.dequeue();
118 ✔
820
    }
821
  }
822
  m_reportedInsert = reported;
319 ✔
823
  const auto reportedOut = qScopeGuard([this] { m_reportedInsert.clear(); });
319 ✔
824

825
  if (exitCode != 0) {
319 ✔
826
    handleProcessError(pid, exitCode, out, err);
61 ✔
827
    return;
828
  }
829

830
  if (pid == PASS_SHOW) {
258 ✔
831
    emit finishedShow(out, shownFile, exec.lastOutputLossless());
52 ✔
832
    return;
833
  }
834
  emitProcessFinishedSignal(pid, out, err);
206 ✔
835
}
836

837
void Pass::handleProcessError(PROCESS pid, int exitCode, const QString &out,
61 ✔
838
                              const QString &err) {
839
  Q_UNUSED(out);
840

841
  if (pid == PASS_INSERT) {
61 ✔
842
    const QString friendly = gpgErrorMessage(err);
19 ✔
843
    const QString why =
844
        friendly.isEmpty() ? err : formatInsertError(friendly, err);
19 ✔
845
    const bool written = insertWritten(err);
19 ✔
846
    emit insertFailed(why, written);
19 ✔
847
    if (written) {
19 ✔
848
      // The entry is in the store; a git step after it failed (a commit
849
      // that could not be signed, with pass.signcommits, say). The dialog
850
      // closes on this, so say it here rather than only in the output
851
      // panel.
852
      emit critical(tr("Saved, not committed"),
10 ✔
853
                    tr("The entry is saved in the store, but recording it "
5 ✔
854
                       "in git failed. What was reported:\n\n%1")
855
                        .arg(err.trimmed()));
10 ✔
856
    }
857
    emit processErrorExit(exitCode, why);
19 ✔
858
    return;
859
  }
860

861
  if (pid == GPG_GENKEYS) {
42 ✔
862
    emit generateGPGKeysFailed(err);
1 ✔
863
  }
864
  emit processErrorExit(exitCode, err);
42 ✔
865
}
866

867
auto Pass::withoutStatusLines(const QString &err) -> QString {
53 ✔
868
  QStringList humanLines;
53 ✔
869
  for (const QString &line : err.split('\n')) {
1,648 ✔
870
    QString cleanedLine = line;
871
    cleanedLine.remove('\r');
1,542 ✔
872
    if (!cleanedLine.startsWith(QLatin1String("[GNUPG:]")))
1,542 ✔
873
      humanLines.append(cleanedLine);
874
  }
875
  return humanLines.join('\n');
53 ✔
876
}
877

878
auto Pass::formatInsertError(const QString &friendly, const QString &err)
6 ✔
879
    -> QString {
880
  const QString humanErr = withoutStatusLines(err).trimmed();
12 ✔
881
  return humanErr.isEmpty() ? friendly : friendly + "\n\n" + humanErr;
12 ✔
882
}
883

884
void Pass::emitProcessFinishedSignal(PROCESS pid, const QString &out,
206 ✔
885
                                     const QString &err) {
886
  // Only output that cannot contain a secret reaches the generic listeners
887
  // (the output panel among them); Enums::processInfo is the one table.
888
  if (pid >= 0 && pid < Enums::PROCESS_COUNT &&
206 ✔
889
      !Enums::processInfo(pid).secret) {
204 ✔
890
    emit finishedAnyWithPid(out, err, pid);
98 ✔
891
  }
892

893
  // The kind-specific signal. PASS_SHOW is emitted by finished(), which
894
  // knows the file. Content search runs in-process (NativeGrep), not
895
  // through `pass grep`, and emits finishedGrep itself.
896
  using Signal = void (Pass::*)(const QString &, const QString &);
897
  static const QHash<int, Signal> kSignals{
898
      {GIT_INIT, &Pass::finishedGitInit},
899
      {GIT_PULL, &Pass::finishedGitPull},
900
      {GIT_PUSH, &Pass::finishedGitPush},
901
      {PASS_INSERT, &Pass::finishedInsert},
902
      {PASS_REMOVE, &Pass::finishedRemove},
903
      {PASS_INIT, &Pass::finishedInit},
904
      {PASS_MOVE, &Pass::finishedMove},
905
      {PASS_COPY, &Pass::finishedCopy},
906
      {GPG_GENKEYS, &Pass::finishedGenerateGPGKeys},
907
  };
212 ✔
908
  // A store that became a repository after updateEnv() gets its pin now,
909
  // before anything is staged in it.
910
  if (pid == GIT_INIT) {
206 ✔
911
    pinStoreGitAttributes();
3 ✔
912
  }
913
  if (const Signal signal = kSignals.value(pid, nullptr)) {
206 ✔
914
    (this->*signal)(out, err);
202 ✔
915
  }
916
}
206 ✔
917

918
void Pass::setEnvVar(const QString &name, const QString &value) {
4,339 ✔
919
  if (value.isEmpty())
4,339 ✔
920
    env.remove(name);
1,445 ✔
921
  else
922
    env.insert(name, value);
2,894 ✔
923
}
4,339 ✔
924

925
void Pass::updateEnv() {
481 ✔
926
  setEnvVar(QStringLiteral("PASSWORD_STORE_SIGNING_KEY"),
962 ✔
927
            m_settings.passSigningKey);
481 ✔
928
  setEnvVar(QStringLiteral("PASSWORD_STORE_DIR"), m_settings.passStore);
962 ✔
929
  // Every path QtPass hands git names one file or folder: an entry called
930
  // "a*.gpg" must not make `git rm -f -- a*.gpg` remove every entry that
931
  // matches. Also reaches the git that pass runs, which passes names the
932
  // same way.
933
  setEnvVar(QStringLiteral("GIT_LITERAL_PATHSPECS"), QStringLiteral("1"));
962 ✔
934

935
  const PasswordConfiguration &passConfig = m_settings.passwordConfiguration;
481 ✔
936
  setEnvVar(QStringLiteral("PASSWORD_STORE_GENERATED_LENGTH"),
962 ✔
937
            QString::number(passConfig.length));
481 ✔
938

939
  setEnvVar(QStringLiteral("PASSWORD_STORE_CHARACTER_SET"),
962 ✔
940
            effectiveCharset(passConfig));
481 ✔
941

942
  // pass hands PASSWORD_STORE_GPG_OPTS to every gpg it runs: the user's own
943
  // options (split as pass's shell splits them: spaces, tabs, newlines),
944
  // then the output limit ImitatePass passes directly.
945
  QStringList gpgOpts = QProcessEnvironment::systemEnvironment()
481 ✔
946
                            .value(QStringLiteral("PASSWORD_STORE_GPG_OPTS"))
962 ✔
947
                            .split(QRegularExpression(QStringLiteral("\\s+")),
962 ✔
948
                                   Qt::SkipEmptyParts);
962 ✔
949
  gpgOpts << maxOutputArgs();
962 ✔
950
  setEnvVar(QStringLiteral("PASSWORD_STORE_GPG_OPTS"),
962 ✔
951
            gpgOpts.join(QLatin1Char(' ')));
481 ✔
952

953
  // As pass does: git never looks for a repository above the store's own
954
  // parent. A store that is not a repository itself but lies inside one (a
955
  // dotfiles repository in the home folder) would otherwise have its entries
956
  // committed and pushed there by native git mode. Only in the environment
957
  // of the processes QtPass runs for the store, never QtPass's own, which a
958
  // file manager or terminal it opens would inherit. pass sets its own
959
  // ceiling whatever this says. A store kept inside a larger repository on
960
  // purpose opts out (gitUseParentRepository), and then, as without a
961
  // store, whatever ceiling QtPass was started with applies.
962
  // A ceiling git cannot take as one entry (the parent's path holds the
963
  // list separator) is backed by GIT_DIR and GIT_WORK_TREE naming the
964
  // store's own repository (Util::gitStoreVariables()); pass unsets those
965
  // for itself and keeps its own ceiling.
966
  setEnvVar(QStringLiteral("GIT_DIR"), QString());
962 ✔
967
  setEnvVar(QStringLiteral("GIT_WORK_TREE"), QString());
962 ✔
968
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
481 ✔
969
    setEnvVar(QStringLiteral("GIT_CEILING_DIRECTORIES"),
40 ✔
970
              qEnvironmentVariable("GIT_CEILING_DIRECTORIES"));
40 ✔
971
  } else {
972
    for (const auto &[name, value] : Util::gitStoreVariables(
973
             m_settings.passStore, m_settings.gitExecutable)) {
1,387 ✔
974
      setEnvVar(name, value);
465 ✔
975
    }
976
  }
977

978
  // Refuse a repository pushed into the store: git started in a folder laid
979
  // out as a bare repository would read its pushed config and run a command
980
  // named there. This reaches the git that pass runs too, which inherits the
981
  // environment.
982
  Util::requireExplicitBareRepository(env);
481 ✔
983
  // pass under WSL needs them too: the count and every entry below it.
984
  QStringList gitConfig{QStringLiteral("GIT_CONFIG_COUNT/u")};
962 ✔
985
  if (env.contains(QStringLiteral("GIT_CONFIG_PARAMETERS"))) {
962 ✔
986
    gitConfig << QStringLiteral("GIT_CONFIG_PARAMETERS/u");
×
987
  }
988
  const int gitConfigCount =
989
      env.value(QStringLiteral("GIT_CONFIG_COUNT")).toInt();
962 ✔
990
  for (int i = 0; i < gitConfigCount; ++i) {
962 ✔
991
    gitConfig << QStringLiteral("GIT_CONFIG_KEY_%1/u").arg(i)
962 ✔
992
              << QStringLiteral("GIT_CONFIG_VALUE_%1/u").arg(i);
962 ✔
993
  }
994
  mergeIntoWslenv(env, gitConfig);
481 ✔
995

996
  exec.setEnvironment(env);
481 ✔
997

998
  pinStoreGitAttributes();
481 ✔
999
}
481 ✔
1000

1001
void Pass::pinStoreGitAttributes() {
484 ✔
1002
  if (m_settings.passStore.isEmpty()) {
484 ✔
1003
    return;
475 ✔
1004
  }
1005
  // Only the common layout, where the store is its own repository, is handled
1006
  // by writing directly: a ".git" directory. A worktree ".git" file or a store
1007
  // nested in a larger repository is left as-is rather than risk touching
1008
  // another repository's attributes.
1009
  const QString gitDir =
1010
      QDir(m_settings.passStore).absoluteFilePath(QStringLiteral(".git"));
940 ✔
1011
  if (!QFileInfo(gitDir).isDir()) {
470 ✔
1012
    return;
1013
  }
1014

1015
  // The marker lets us recognise and refresh our own block without disturbing
1016
  // anything a user put in info/attributes by hand. Disabling text/eol,
1017
  // working-tree-encoding, filter and ident keeps Git from rewriting the
1018
  // bytes gpg produced for these paths - a co-writer can push a .gitattributes
1019
  // ("*.gpg text", a working-tree-encoding, a filter) that otherwise corrupts
1020
  // the ciphertext QtPass commits. info/attributes outranks the in-tree file.
1021
  // diff is left alone: it only changes what Git shows, and pass's own
1022
  // "*.gpg diff=gpg" gives decrypted diffs.
1023
  static const QString marker =
1024
      QStringLiteral("# QtPass: keep encrypted store files byte-for-byte");
53 ✔
1025
  const QString block =
1026
      marker + QStringLiteral("\n") +
98 ✔
1027
      QStringLiteral(
98 ✔
1028
          "*.gpg -text -filter -ident -working-tree-encoding\n"
1029
          ".gpg-id -text -filter -ident -working-tree-encoding\n"
1030
          ".gpg-id.sig -text -filter -ident -working-tree-encoding\n");
1031

1032
  const QString infoDir = gitDir + QStringLiteral("/info");
98 ✔
1033
  const QString attrPath = infoDir + QStringLiteral("/attributes");
98 ✔
1034

1035
  QString existing;
49 ✔
1036
  QFile attr(attrPath);
49 ✔
1037
  if (attr.exists()) {
49 ✔
1038
    // Unreadable: writing now would drop the user's own lines in it.
1039
    if (!attr.open(QIODevice::ReadOnly | QIODevice::Text)) {
40 ✔
1040
      qCWarning(lcQtPass) << "Cannot read" << attrPath
×
1041
                          << "to pin attributes:" << attr.errorString();
×
1042
      return;
×
1043
    }
1044
    existing = QString::fromUtf8(attr.readAll());
40 ✔
1045
    attr.close();
40 ✔
1046
    if (existing.contains(block)) {
40 ✔
1047
      return; // already pinned and unchanged
1048
    }
1049
  }
1050

1051
  if (!QDir().mkpath(infoDir)) {
18 ✔
1052
    qCWarning(lcQtPass) << "Cannot create" << infoDir << "to pin attributes";
×
1053
    return;
×
1054
  }
1055

1056
  // Keep any lines the user added themselves (outside our block), then append a
1057
  // fresh copy of our block. A previous QtPass block is dropped so an updated
1058
  // set of lines replaces an older one.
1059
  QString preserved;
9 ✔
1060
  if (!existing.isEmpty()) {
9 ✔
1061
    const QStringList lines = existing.split(QLatin1Char('\n'));
×
1062
    bool inBlock = false;
1063
    for (const QString &line : lines) {
×
1064
      if (line == marker) {
×
1065
        inBlock = true;
1066
        continue;
×
1067
      }
1068
      if (inBlock) {
×
1069
        if (line.startsWith(QStringLiteral("*.gpg ")) ||
×
1070
            line.startsWith(QStringLiteral(".gpg-id ")) ||
×
1071
            line.startsWith(QStringLiteral(".gpg-id.sig "))) {
×
1072
          continue;
×
1073
        }
1074
        inBlock = false;
1075
      }
1076
      preserved += line + QLatin1Char('\n');
×
1077
    }
1078
    while (preserved.endsWith(QStringLiteral("\n\n"))) {
×
1079
      preserved.chop(1);
×
1080
    }
1081
  }
1082

1083
  QSaveFile out(attrPath);
9 ✔
1084
  const QByteArray payload = (preserved + block).toUtf8();
9 ✔
1085
  if (!out.open(QIODevice::WriteOnly | QIODevice::Text) ||
18 ✔
1086
      out.write(payload) != payload.size() || !out.commit()) {
18 ✔
1087
    qCWarning(lcQtPass) << "Cannot write" << attrPath
×
1088
                        << "to pin attributes:" << out.errorString();
×
1089
  }
1090
}
58 ✔
1091

1092
auto Pass::withCurrentGitPin(QProcessEnvironment base) const
1,911 ✔
1093
    -> QProcessEnvironment {
1094
  if (m_settings.gitUseParentRepository || m_settings.passStore.isEmpty()) {
1,911 ✔
1095
    return base;
17 ✔
1096
  }
1097
  base.remove(QStringLiteral("GIT_DIR"));
3,788 ✔
1098
  base.remove(QStringLiteral("GIT_WORK_TREE"));
3,788 ✔
1099
  for (const auto &[name, value] : Util::gitStoreVariables(
1100
           m_settings.passStore, m_settings.gitExecutable)) {
5,692 ✔
1101
    base.insert(name, value);
1,904 ✔
1102
  }
1103
  return base;
1,894 ✔
1104
}
1105

1106
auto Pass::maxOutputArgs() -> QStringList {
1,185 ✔
1107
  return {QStringLiteral("--max-output"), QString::number(kMaxPlaintextBytes)};
3,555 ✔
1108
}
1,185 ✔
1109

1110
namespace {
1111
/// File names compare the way the platform's file system compares them:
1112
/// "C:/Store" and "c:/store" are the same directory on Windows.
1113
#ifdef Q_OS_WIN
1114
constexpr auto kPathCase = Qt::CaseInsensitive;
1115
#else
1116
constexpr auto kPathCase = Qt::CaseSensitive;
1117
#endif
1118

1119
/// Whether @p path is @p dir or lies under it.
1120
auto isAtOrUnder(const QString &path, const QString &dir,
4,453 ✔
1121
                 const QString &dirPrefix) -> bool {
1122
  return path.compare(dir, kPathCase) == 0 ||
7,980 ✔
1123
         path.startsWith(dirPrefix, kPathCase);
3,527 ✔
1124
}
1125

1126
/// Where the lookup of a .gpg-id starts and the store that bounds it.
1127
struct GpgIdLookup {
1128
  QDir start;
1129
  /// The folder whose list is wanted, whether it exists or not.
1130
  QString folder;
1131
  QString storeDir;
1132
  QString storePrefix;
1133
};
1134

1135
/// The folder whose list @p for_file wants: its own for a folder, its
1136
/// folder's for an entry.
1137
auto gpgIdLookup(const QString &for_file, const QString &passStore)
1,349 ✔
1138
    -> GpgIdLookup {
1139
  const QString normalizedFile = QDir::fromNativeSeparators(for_file);
1,349 ✔
1140
  // Inside the store means at a path boundary: "/store-other/x" is not
1141
  // under "/store", however the prefix compares.
1142
  const QString storeDir =
1143
      QDir::cleanPath(QDir::fromNativeSeparators(passStore));
1,349 ✔
1144
  const QString storePrefix = storeDir.endsWith(QLatin1Char('/'))
1,349 ✔
1145
                                  ? storeDir
1,349 ✔
1146
                                  : storeDir + QLatin1Char('/');
1,349 ✔
1147
  const QString cleanFile = QDir::cleanPath(normalizedFile);
1,349 ✔
1148
  const bool insideStore = isAtOrUnder(cleanFile, storeDir, storePrefix);
1,349 ✔
1149
  // A relative name is one inside the store; an absolute path outside it
1150
  // stays what it is and the walk stops at once.
1151
  const QString fullPath =
1152
      insideStore || (QDir::isAbsolutePath(cleanFile) &&
21 ✔
1153
                      !cleanFile.startsWith(QLatin1Char(':')))
5 ✔
1154
          ? cleanFile
1,349 ✔
1155
          : storePrefix + cleanFile;
11 ✔
1156
  // A folder (trailing separator, which cleanPath() dropped, or an existing
1157
  // directory) wants its own list; an entry wants its folder's.
1158
  const bool isFolder =
1159
      normalizedFile.endsWith(QLatin1Char('/')) || QFileInfo(fullPath).isDir();
1,349 ✔
1160
  // A folder that does not exist yet (an entry saved into a new folder, a
1161
  // move to one) starts the walk at its nearest existing ancestor in the
1162
  // store, as pass's set_gpg_recipients does: otherwise the walk ended at
1163
  // once and the store root's list was taken over the one in between.
1164
  const QString folder =
1165
      QDir::cleanPath(isFolder ? fullPath : QFileInfo(fullPath).absolutePath());
3,394 ✔
1166
  QString start = folder;
1167
  while (!QFileInfo(start).exists() &&
1,383 ✔
1168
         isAtOrUnder(QDir::cleanPath(start), storeDir, storePrefix) &&
2,749 ✔
1169
         QDir::cleanPath(start) != storeDir) {
1,383 ✔
1170
    start = QFileInfo(start).absolutePath();
34 ✔
1171
  }
1172
  return {QDir(start), folder, storeDir, storePrefix};
1,349 ✔
1173
}
1,349 ✔
1174

1175
/// Whether @p candidate can be its folder's .gpg-id: a regular file, as
1176
/// pass looks for (test -f), so a folder under the name is passed over as
1177
/// pass passes it. A link under the name is not: whoever planted it chose
1178
/// the recipients elsewhere.
1179
auto isOwnGpgId(const QFileInfo &candidate) -> bool {
2,401 ✔
1180
  return candidate.isFile() && !candidate.isSymLink() &&
3,115 ✔
1181
         !candidate.isJunction();
714 ✔
1182
}
1183

1184
/// Walk up from the lookup's start to the first folder inside the store
1185
/// that has its own .gpg-id; nothing when none does. A link under the name
1186
/// is skipped, so the parent's list applies instead.
1187
auto nearestGpgId(const GpgIdLookup &lookup) -> std::optional<QString> {
761 ✔
1188
  QDir dir = lookup.start;
761 ✔
1189
  while (dir.exists() && isAtOrUnder(QDir::cleanPath(dir.absolutePath()),
4,480 ✔
1190
                                     lookup.storeDir, lookup.storePrefix)) {
1,120 ✔
1191
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
970 ✔
1192
    if (isOwnGpgId(candidate)) {
970 ✔
1193
      return candidate.absoluteFilePath();
611 ✔
1194
    }
1195
    if (!dir.cdUp()) {
359 ✔
1196
      break;
1197
    }
1198
  }
970 ✔
1199
  return std::nullopt;
150 ✔
1200
}
761 ✔
1201

1202
} // namespace
1203

1204
auto Pass::heldScopes() -> QSet<QString> & {
274 ✔
1205
  static QSet<QString> scopes;
280 ✔
1206
  return scopes;
274 ✔
1207
}
1208

1209
auto Pass::scopePath(const QString &path) const -> QString {
274 ✔
1210
  return QDir::cleanPath(QDir(m_settings.passStore).absoluteFilePath(path));
548 ✔
1211
}
1212

1213
auto Pass::autoPushHeld() const -> bool {
68 ✔
1214
  const QString store = scopePath(QString());
68 ✔
1215
  const QSet<QString> &scopes = heldScopes();
68 ✔
1216
  return std::any_of(scopes.cbegin(), scopes.cend(),
68 ✔
1217
                     [&store](const QString &s) {
199 ✔
1218
                       return isAtOrUnder(s, store, store + QLatin1Char('/'));
398 ✔
1219
                     });
68 ✔
1220
}
1221

1222
void Pass::GitPushAutomatic() {
15 ✔
1223
  m_pushIsAutomatic = true;
15 ✔
1224
  GitPush();
15 ✔
1225
  m_pushIsAutomatic = false;
15 ✔
1226
}
15 ✔
1227

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

1230
void Pass::holdAutoPush(const QString &scope) {
103 ✔
1231
  heldScopes().insert(scopePath(scope));
103 ✔
1232
}
103 ✔
1233

1234
void Pass::releaseAutoPush(const QString &folder) {
103 ✔
1235
  const QString root = scopePath(folder);
103 ✔
1236
  QSet<QString> &scopes = heldScopes();
103 ✔
1237
  for (auto it = scopes.begin(); it != scopes.end();) {
1238
    it = isAtOrUnder(*it, root, root + QLatin1Char('/')) ? scopes.erase(it)
1,252 ✔
1239
                                                         : std::next(it);
626 ✔
1240
  }
1241
}
103 ✔
1242

1243
auto Pass::refuseLinkedPath(const QString &path, LinkScope scope,
810 ✔
1244
                            PathSpelling spelling) -> bool {
1245
  const QString full = Util::joinPath(m_settings.passStore, path);
810 ✔
1246
  // The link check below walks only under the store as configured: a path
1247
  // spelled through the root's link target would get no more than the
1248
  // entry itself judged. No caller makes one; say so if one starts to.
1249
  if (spelling == PathSpelling::Configured &&
1,331 ✔
1250
      PathValidator::isTargetSpelled(m_settings.passStore, full)) {
521 ✔
1251
    qCWarning(lcQtPass)
4 ✔
1252
        << "Path spelled through the store root's link target, not as the "
1253
           "store is configured; Pass operations expect the configured "
1254
           "spelling:"
2 ✔
1255
        << full;
2 ✔
1256
  }
1257
  if (!Util::isUnderLink(full, m_settings.passStore,
810 ✔
1258
                         scope == LinkScope::EntryAndParents)) {
1259
    return false;
1260
  }
1261
  const QString why =
1262
      tr("%1 is, or lies behind, a symbolic link or junction. What that "
×
1263
         "points to is not part of the password store and is left alone.")
1264
          .arg(QDir::toNativeSeparators(QDir::cleanPath(full)));
62 ✔
1265
  refuseAsNotPartOfStore(why);
31 ✔
1266
  return true;
1267
}
1268

1269
auto Pass::refuseFolderOutsideStore(const QString &folder, QString *relative)
94 ✔
1270
    -> bool {
1271
  if (const std::optional<QString> inStore =
94 ✔
1272
          PathValidator::storeRelativePath(m_settings.passStore, folder)) {
94 ✔
1273
    if (relative != nullptr) {
89 ✔
1274
      *relative = *inStore;
89 ✔
1275
    }
1276
    return false;
1277
  }
1278
  refuseAsNotPartOfStore(
5 ✔
1279
      tr("%1 is not inside the password store. Recipients are set for the "
5 ✔
1280
         "store or a folder in it.")
1281
          .arg(QDir::toNativeSeparators(QDir::cleanPath(folder))));
10 ✔
1282
  return true;
5 ✔
1283
}
1284

1285
auto Pass::unfinishedGitOperationReason() -> QString {
813 ✔
1286
  if (!m_settings.useGit) {
813 ✔
1287
    return {};
600 ✔
1288
  }
1289
  // One git call names the path of each marker file or directory, whether or
1290
  // not it exists; the backend runs it in the store (ImitatePass with
1291
  // `-C <store>`, RealPass through `pass git`). The markers, paired with the
1292
  // operation each one means, in the order git prints them back.
1293
  // The names are Git's own commands, which the user then runs with --abort or
1294
  // --continue; the translator comments say so.
1295
  const std::array<std::pair<QLatin1String, QString>, 6> markers{{
1296
      //: The Git command `git rebase`, inserted into "in the middle of a %1".
1297
      //: Best kept as Git's command name.
1298
      {QLatin1String("rebase-merge"), tr("rebase")},
213 ✔
1299
      //: The Git command `git rebase`, inserted into "in the middle of a %1".
1300
      //: Best kept as Git's command name.
1301
      {QLatin1String("rebase-apply"), tr("rebase")},
213 ✔
1302
      //: The Git command `git merge`, inserted into "in the middle of a %1".
1303
      //: Best kept as Git's command name.
1304
      {QLatin1String("MERGE_HEAD"), tr("merge")},
213 ✔
1305
      //: The Git command `git cherry-pick`, inserted into "in the middle of a
1306
      //: %1". Best kept as Git's command name.
1307
      {QLatin1String("CHERRY_PICK_HEAD"), tr("cherry-pick")},
213 ✔
1308
      //: The Git command `git revert`, inserted into "in the middle of a %1".
1309
      //: Best kept as Git's command name.
1310
      {QLatin1String("REVERT_HEAD"), tr("revert")},
213 ✔
1311
      // A multi-commit cherry-pick or revert keeps its sequencer state after a
1312
      // conflict resolution is committed, when CHERRY_PICK_HEAD/REVERT_HEAD is
1313
      // already gone but `--continue` has more commits to apply. Checked last,
1314
      // so the specific head above names the operation when it is still there.
1315
      //: The Git commands `git cherry-pick` and `git revert`, inserted into
1316
      //: "in the middle of a %1". Best kept as Git's command names.
1317
      {QLatin1String("sequencer"), tr("cherry-pick or revert")},
213 ✔
1318
  }};
×
1319
  QStringList args{QStringLiteral("rev-parse")};
426 ✔
1320
  for (const auto &marker : markers) {
1,491 ✔
1321
    args << QStringLiteral("--git-path") << marker.first;
1,278 ✔
1322
  }
1323
  QString out;
213 ✔
1324
  if (!storeGit(args, &out)) {
213 ✔
1325
    // Git is off, the store is not a repository, or git could not be asked:
1326
    // nothing is refused, as the operation would run anyway.
1327
    return {};
14 ✔
1328
  }
1329
  const QStringList paths = out.split(QLatin1Char('\n'), Qt::SkipEmptyParts);
199 ✔
1330
  for (int i = 0; i < paths.size() && i < static_cast<int>(markers.size());
825 ✔
1331
       ++i) {
1332
    const QString path = paths.at(i).trimmed();
1333
    const QString full = QDir::isAbsolutePath(path)
1334
                             ? path
633 ✔
1335
                             : QDir(m_settings.passStore).filePath(path);
633 ✔
1336
    if (!QFileInfo::exists(full)) {
633 ✔
1337
      continue;
1338
    }
1339
    //: %1 is a Git command name: rebase, merge, cherry-pick, revert, or
1340
    //: "cherry-pick or revert".
1341
    return tr("The password store's Git repository is in the middle of a %1. "
7 ✔
1342
              "Finish or abort it with Git before changing the password store, "
1343
              "or what you change may be lost.")
1344
        .arg(markers.at(static_cast<size_t>(i)).second);
7 ✔
1345
  }
1346
  return {};
192 ✔
1347
}
1348

1349
auto Pass::refusePendingPull() -> bool {
203 ✔
1350
  if (!m_settings.useGit || !exec.hasQueued(Enums::GIT_PULL)) {
250 ✔
1351
    return false;
1352
  }
1353
  const QString why =
1354
      tr("The password store is being updated (a Git pull is in progress). "
1355
         "Wait until it has finished, then try again.");
1356
  // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
1357
  // and is released by processErrorExit(); a refusal starts nothing.
1358
  emit startingExecuteWrapper();
3 ✔
1359
  emit critical(tr("Update in progress"), why);
3 ✔
1360
  emit processErrorExit(1, why);
3 ✔
1361
  return true;
1362
}
1363

1364
auto Pass::initIfUnchanged(const QString &path, const QList<UserInfo> &users,
11 ✔
1365
                           const QString &dir, const QString &passStore,
1366
                           const RecipientsForEditing &read) -> bool {
1367
  m_expectedList = ExpectedList{dir, passStore, read.state, read.recipients};
11 ✔
1368
  m_expectedListRefused = false;
11 ✔
1369
  const auto done = qScopeGuard([this] { m_expectedList.reset(); });
1370
  Init(path, users);
11 ✔
1371
  return !m_expectedListRefused;
11 ✔
1372
}
1373

1374
auto Pass::refuseChangedList() -> bool {
80 ✔
1375
  if (!m_expectedList) {
80 ✔
1376
    return false;
1377
  }
1378
  const RecipientsForEditing now =
1379
      recipientsForEditing(m_expectedList->dir, m_expectedList->passStore);
5 ✔
1380
  if (now.state == m_expectedList->state &&
5 ✔
1381
      now.recipients == m_expectedList->recipients) {
5 ✔
1382
    return false;
1383
  }
1384
  const QString why =
1385
      tr("The recipient list of this folder changed after the users dialog "
1386
         "read it, for example through an update from Git. Nothing was "
1387
         "written. Open the dialog again to see the new list.");
1388
  m_expectedListRefused = true;
3 ✔
1389
  emit startingExecuteWrapper();
3 ✔
1390
  emit critical(tr("Recipients not changed"), why);
3 ✔
1391
  emit processErrorExit(1, why);
3 ✔
1392
  return true;
1393
}
1394

1395
auto Pass::refuseBusyForExpectedList() -> bool {
39 ✔
1396
  if (!m_expectedList || exec.isIdle()) {
39 ✔
1397
    return false;
1398
  }
1399
  const QString why =
1400
      tr("Another operation is still running. Wait until it has finished, "
1401
         "then save the recipients again.");
1402
  m_expectedListRefused = true;
1 ✔
1403
  emit startingExecuteWrapper();
1 ✔
1404
  emit critical(tr("Recipients not changed"), why);
1 ✔
1405
  emit processErrorExit(1, why);
1 ✔
1406
  return true;
1407
}
1408

1409
auto Pass::refuseUnfinishedGitOperation() -> bool {
587 ✔
1410
  const QString why = unfinishedGitOperationReason();
587 ✔
1411
  if (why.isEmpty()) {
587 ✔
1412
    return false;
1413
  }
1414
  // Like refuseAsNotPartOfStore(): the interface arms when an operation starts
1415
  // and is released by finished()/processErrorExit(); a refusal starts
1416
  // nothing, so it emits both ends.
1417
  emit startingExecuteWrapper();
5 ✔
1418
  emit critical(tr("Unfinished Git operation"), why);
5 ✔
1419
  emit processErrorExit(1, why);
5 ✔
1420
  return true;
1421
}
1422

1423
void Pass::refuseAsNotPartOfStore(const QString &why) {
36 ✔
1424
  // The interface arms itself when an operation starts and is released by
1425
  // finished or processErrorExit; a refusal starts nothing, so emits both.
1426
  emit startingExecuteWrapper();
36 ✔
1427
  emit critical(tr("Not part of the store"), why);
36 ✔
1428
  emit processErrorExit(1, why);
36 ✔
1429
}
36 ✔
1430

1431
auto Pass::getGpgIdPath(const QString &for_file, const QString &passStore)
761 ✔
1432
    -> QString {
1433
  return nearestGpgId(gpgIdLookup(for_file, passStore))
1,522 ✔
1434
      .value_or(
1435
          QDir(QDir::fromNativeSeparators(passStore)).filePath(".gpg-id"));
3,044 ✔
1436
}
1437

1438
auto Pass::refuseSkippedGpgId(const QString &file, bool signing,
232 ✔
1439
                              const QString &except, SkippedWalks *walks)
1440
    -> bool {
1441
  // Without a signing key the parent's list applies, as it does for pass.
1442
  if (!signing) {
232 ✔
1443
    return false;
1444
  }
1445
  QString recordError;
51 ✔
1446
  const std::optional<QString> skipped =
1447
      skippedGpgId(file, m_settings.passStore, &recordError, walks);
51 ✔
1448
  if (!skipped || (!except.isEmpty() &&
51 ✔
1449
                   QDir::cleanPath(*skipped) == QDir::cleanPath(except))) {
53 ✔
1450
    return false;
1451
  }
1452
  // The strings keep the context they were translated in.
1453
  if (!recordError.isEmpty()) {
4 ✔
1454
    emit critical(QCoreApplication::translate(
×
1455
                      "ImitatePass", "Cannot check the recipient list"),
1456
                  QCoreApplication::translate(
×
1457
                      "ImitatePass", "%1 Whether %2 was removed cannot be "
1458
                                     "told, so nothing was encrypted.")
1459
                      .arg(recordError, QDir::toNativeSeparators(*skipped)));
×
1460
    return true;
×
1461
  }
1462
  emit critical(
4 ✔
1463
      QCoreApplication::translate("ImitatePass", "Recipient list missing"),
8 ✔
1464
      QCoreApplication::translate(
4 ✔
1465
          "ImitatePass",
1466
          "The signed recipient list %1 is missing or is not a regular file. "
1467
          "QtPass does not fall back to a parent folder's list for it: that "
1468
          "list was not signed for this folder. If a link is under that name, "
1469
          "remove it. Then open Users for that folder and save its "
1470
          "recipients, which writes and signs a fresh list.")
1471
          .arg(QDir::toNativeSeparators(*skipped)));
8 ✔
1472
  return true;
4 ✔
1473
}
1474

1475
auto Pass::verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile,
68 ✔
1476
                            QByteArray *contents, QString *why) const -> bool {
1477
  if (!signer.verifyFile(gpgIdFile, contents)) {
68 ✔
1478
    return false;
1479
  }
1480
  // Authentic and unmodified is not the same as current: an older signed
1481
  // list put back into the store is refused once this device has seen a
1482
  // newer one, and one signed for another folder is refused here.
1483
  QString reason;
52 ✔
1484
  if (GpgIdGeneration::accept(gpgIdFile, *contents, m_settings.passStore,
52 ✔
1485
                              &reason) != GpgIdGeneration::Verdict::Accepted) {
1486
    if (why != nullptr) {
19 ✔
1487
      *why = reason;
14 ✔
1488
    }
1489
    return false;
19 ✔
1490
  }
1491
  return true;
1492
}
1493

1494
auto Pass::skippedGpgId(const QString &forFile, const QString &passStore,
284 ✔
1495
                        QString *recordError, SkippedWalks *walks)
1496
    -> std::optional<QString> {
1497
  const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
284 ✔
1498
  // A folder's answer depends only on it and the folders above it: kept
1499
  // for every folder climbed, a tree check asks each one record lookup,
1500
  // where climbing again from every folder cost depth squared.
1501
  QStringList climbed;
284 ✔
1502
  // By value: on a hit they come out of walks, which the inserts below
1503
  // may rehash.
1504
  const auto answer = [&climbed, walks, recordError](
284 ✔
1505
                          std::optional<QString> skipped, QString why) {
1506
    if (walks != nullptr) {
284 ✔
1507
      for (const QString &folder : std::as_const(climbed)) {
430 ✔
1508
        walks->insert(folder, {skipped, why});
430 ✔
1509
      }
1510
    }
1511
    if (recordError != nullptr && !why.isEmpty()) {
284 ✔
1512
      *recordError = why;
1 ✔
1513
    }
1514
    return skipped;
284 ✔
1515
  };
284 ✔
1516
  // The same walk as nearestGpgId(), stopping at the list it finds, and
1517
  // short of the store root: the root's own list has no parent to fall
1518
  // back to, and the signature check refuses it when it is missing. It
1519
  // starts at the folder asked for, not at its nearest existing one: a
1520
  // folder removed together with its list is asked of the record too.
1521
  QString dir = lookup.folder;
1522
  while (dir.startsWith(lookup.storePrefix, kPathCase)) {
707 ✔
1523
    if (walks != nullptr) {
655 ✔
1524
      if (const auto known = walks->constFind(dir);
413 ✔
1525
          known != walks->constEnd()) {
1526
        return answer(known->skipped, known->recordError);
396 ✔
1527
      }
1528
    }
1529
    climbed << dir;
1530
    const QFileInfo candidate(dir + QStringLiteral("/.gpg-id"));
914 ✔
1531
    if (isOwnGpgId(candidate)) {
457 ✔
1532
      return answer(std::nullopt, QString());
32 ✔
1533
    }
1534
    // A link under the name (dangling or not), or nothing under it where
1535
    // this device accepted a list before: both are the folder's list gone,
1536
    // not a folder that never had one.
1537
    if (candidate.isSymLink() || candidate.isJunction()) {
441 ✔
1538
      return answer(candidate.absoluteFilePath(), QString());
10 ✔
1539
    }
1540
    // An unreadable record is not "never seen": whether a list was accepted
1541
    // here cannot be told, so this folder is refused too (fail closed), with
1542
    // the record's own reason for the caller to show.
1543
    QString why;
436 ✔
1544
    const std::optional<bool> seen =
1545
        GpgIdGeneration::seen(candidate.absoluteFilePath(), &why);
872 ✔
1546
    if (!seen) {
436 ✔
1547
      return answer(candidate.absoluteFilePath(),
2 ✔
1548
                    why.isEmpty()
1549
                        ? tr("The generation record of the recipient lists "
2 ✔
1550
                             "cannot be read.")
1551
                        : why);
1 ✔
1552
    }
1553
    if (*seen) {
435 ✔
1554
      return answer(candidate.absoluteFilePath(), QString());
24 ✔
1555
    }
1556
    const QString parent = QDir::cleanPath(QFileInfo(dir).absolutePath());
846 ✔
1557
    if (parent == dir) {
423 ✔
1558
      break;
1559
    }
1560
    dir = parent;
423 ✔
1561
  }
457 ✔
1562
  return answer(std::nullopt, QString());
104 ✔
1563
}
284 ✔
1564

1565
auto Pass::linkedGpgId(const QString &forFile, const QString &passStore,
304 ✔
1566
                       LinkedWalks *walks) -> std::optional<QString> {
1567
  const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
304 ✔
1568
  // As in skippedGpgId(): a folder's answer depends only on it and the
1569
  // folders above it, so a tree check climbs each folder once instead of
1570
  // once per folder below it.
1571
  QStringList climbed;
304 ✔
1572
  const auto answer = [&climbed, walks](std::optional<QString> linked) {
304 ✔
1573
    if (walks != nullptr) {
304 ✔
1574
      for (const QString &folder : std::as_const(climbed)) {
381 ✔
1575
        walks->insert(folder, linked);
218 ✔
1576
      }
1577
    }
1578
    return linked;
304 ✔
1579
  };
304 ✔
1580
  // The walk of nearestGpgId(), root included, stopping at the list it
1581
  // finds.
1582
  QDir dir = lookup.start;
304 ✔
1583
  while (dir.exists()) {
1,142 ✔
1584
    const QString here = QDir::cleanPath(dir.absolutePath());
1,142 ✔
1585
    if (!isAtOrUnder(here, lookup.storeDir, lookup.storePrefix)) {
1,142 ✔
1586
      break;
1587
    }
1588
    if (walks != nullptr) {
1,062 ✔
1589
      // By value: the inserts in answer() may rehash walks.
1590
      if (const auto known = walks->constFind(here);
306 ✔
1591
          known != walks->constEnd()) {
1592
        return answer(std::optional<QString>(*known));
176 ✔
1593
      }
1594
    }
1595
    climbed << here;
1596
    const QFileInfo candidate(dir.absoluteFilePath(".gpg-id"));
974 ✔
1597
    if (isOwnGpgId(candidate)) {
974 ✔
1598
      return answer(std::nullopt);
174 ✔
1599
    }
1600
    if (candidate.isSymLink() || candidate.isJunction()) {
887 ✔
1601
      return answer(candidate.absoluteFilePath());
98 ✔
1602
    }
1603
    if (!dir.cdUp()) {
838 ✔
1604
      break;
1605
    }
1606
  }
974 ✔
1607
  return answer(std::nullopt);
160 ✔
1608
}
608 ✔
1609

1610
namespace {
1611

1612
/// What the Users dialog may preselect for a verified list, given what the
1613
/// generation record says about it.
1614
auto judgedRecipients(GpgIdGeneration::Verdict verdict,
7 ✔
1615
                      const QByteArray &contents, const QString &gpgIdPath,
1616
                      const QString &why) -> Pass::RecipientsForEditing {
1617
  using RecipientsForEditing = Pass::RecipientsForEditing;
1618
  RecipientsForEditing result;
7 ✔
1619
  switch (verdict) {
7 ✔
1620
  case GpgIdGeneration::Verdict::Accepted:
1 ✔
1621
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1622
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1623
    break;
1 ✔
1624
  case GpgIdGeneration::Verdict::Rollback:
1 ✔
1625
    // Authentic and this folder's, only older: the recovery goes through
1626
    // this dialog, so it is preselected, with the reason in view.
1627
    result.state = RecipientsForEditing::State::VerifiedRollback;
1 ✔
1628
    result.recipients = Pass::parseRecipients(contents, gpgIdPath);
1 ✔
1629
    result.warning = why;
1 ✔
1630
    break;
1 ✔
1631
  case GpgIdGeneration::Verdict::Unbound:
5 ✔
1632
  case GpgIdGeneration::Verdict::Conflict:
1633
  case GpgIdGeneration::Verdict::WrongFolder:
1634
  case GpgIdGeneration::Verdict::WrongStore:
1635
  case GpgIdGeneration::Verdict::Malformed:
1636
  case GpgIdGeneration::Verdict::RecordUnavailable:
1637
    // Signed, but not shown to be this folder's list, not a list to trust,
1638
    // or nothing to judge it by: preselecting it would sign it in.
1639
    result.state = RecipientsForEditing::State::Rejected;
5 ✔
1640
    result.warning =
1641
        Pass::tr("%1 Nothing is preselected: saving would sign whatever is "
5 ✔
1642
                 "in it. Select the recipients yourself.")
1643
            .arg(why);
10 ✔
1644
    break;
5 ✔
1645
  }
1646
  return result;
7 ✔
1647
}
1648

1649
} // namespace
1650

1651
auto Pass::recipientsForEditing(const QString &dir, const QString &passStore)
86 ✔
1652
    -> RecipientsForEditing {
1653
  RecipientsForEditing result;
86 ✔
1654
  const QString folder = dir.isEmpty() ? QString() : dir;
86 ✔
1655
  const QString gpgIdPath = getGpgIdPath(folder, passStore);
86 ✔
1656
  GpgIdSigner signer(m_settings.gpgExecutable,
1657
                     GpgIdSigner::keysFromSetting(m_settings.passSigningKey));
258 ✔
1658
  signer.setStoreRoot(passStore);
1659
  if (!signer.enabled()) {
86 ✔
1660
    // A list that is there but cannot be read as one (too large, not a
1661
    // regular file, unreadable) is not an empty list: preselecting nothing
1662
    // without a word would let OK write a new list over it, and later
1663
    // re-encryptions drop whoever it named.
1664
    // Read once and parsed from those bytes: a second read could find
1665
    // something else under the name. A link counts as there, dangling too.
1666
    const QFileInfo info(gpgIdPath);
76 ✔
1667
    if (!info.exists() && !info.isSymLink()) {
76 ✔
1668
      result.state = RecipientsForEditing::State::Unsigned;
1669
      return result;
18 ✔
1670
    }
1671
    const std::optional<QByteArray> bytes = Util::readRegularFileInStore(
1672
        passStore, gpgIdPath, Util::kMaxGpgIdBytes);
58 ✔
1673
    if (!bytes) {
58 ✔
1674
      result.state = RecipientsForEditing::State::Rejected;
2 ✔
1675
      result.warning =
1676
          tr("%1 cannot be read as a recipient list (a regular file of at "
2 ✔
1677
             "most %2), so nothing is preselected. Check it before choosing "
1678
             "recipients here: OK writes a new list over it.")
1679
              .arg(gpgIdPath,
2 ✔
1680
                   QLocale().formattedDataSize(Util::kMaxGpgIdBytes));
4 ✔
1681
      return result;
2 ✔
1682
    }
1683
    result.state = RecipientsForEditing::State::Unsigned;
1684
    result.recipients = parseRecipients(*bytes, gpgIdPath);
56 ✔
1685
    const QString misread = passReadsDifferently(*bytes);
56 ✔
1686
    if (!misread.isEmpty()) {
56 ✔
1687
      //: %1 is the list's path, %2 says what is wrong with it.
1688
      result.warning =
1689
          tr("pass reads %1 differently from this dialog (%2), so it may "
3 ✔
1690
             "encrypt to recipients not shown here. QtPass will not encrypt "
1691
             "with it through pass: check the recipients, then OK writes the "
1692
             "list anew.")
1693
              .arg(gpgIdPath, misread);
6 ✔
1694
    }
1695
    return result;
56 ✔
1696
  }
76 ✔
1697
  QString recordError;
10 ✔
1698
  if (const std::optional<QString> skipped =
10 ✔
1699
          skippedGpgId(folder, passStore, &recordError)) {
10 ✔
1700
    // The folder's own list was removed or replaced by a link (or the record
1701
    // that would tell cannot be read): the list the walk found further up
1702
    // was not signed for this folder, so preselecting it would sign it in
1703
    // here with one click.
1704
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1705
    result.warning =
1706
        recordError.isEmpty()
1707
            ? tr("The recipient list %1 is missing or is not a regular file, "
2 ✔
1708
                 "so nothing is preselected: the list of a parent folder was "
1709
                 "not signed for this one. Select this folder's recipients "
1710
                 "yourself; OK writes and signs a fresh list.")
1711
                  .arg(*skipped)
1712
            : tr("%1 Nothing is preselected: whether %2 was removed cannot "
1 ✔
1713
                 "be told.")
1714
                  .arg(recordError, *skipped);
1715
    return result;
1 ✔
1716
  }
1717
  if (!QFileInfo::exists(gpgIdPath)) {
9 ✔
1718
    // A folder without a list yet (new store, new profile): nothing to
1719
    // verify and nothing to preselect.
1720
    result.state = RecipientsForEditing::State::Verified;
1 ✔
1721
    return result;
1 ✔
1722
  }
1723
  QByteArray contents;
8 ✔
1724
  if (!signer.verifyFile(gpgIdPath, &contents)) {
8 ✔
1725
    result.state = RecipientsForEditing::State::Rejected;
1 ✔
1726
    result.warning =
1727
        tr("The recipient list %1 does not verify against the signing key, "
1 ✔
1728
           "so nothing is preselected: saving would sign whatever is in it. "
1729
           "Select the recipients yourself; OK writes and signs a fresh list.")
1730
            .arg(gpgIdPath);
2 ✔
1731
    return result;
1 ✔
1732
  }
1733
  QString why;
7 ✔
1734
  const GpgIdGeneration::Verdict verdict =
1735
      GpgIdGeneration::accept(gpgIdPath, contents, passStore, &why);
7 ✔
1736
  return judgedRecipients(verdict, contents, gpgIdPath, why);
7 ✔
1737
}
86 ✔
1738

1739
auto Pass::getRecipientList(const QString &for_file, const QString &passStore)
46 ✔
1740
    -> QStringList {
1741
  const QString gpgIdPath = getGpgIdPath(for_file, passStore);
46 ✔
1742
  // The root .gpg-id comes back whatever it is; a link is not a list.
1743
  if (Util::isLinkedFolder(gpgIdPath)) {
46 ✔
1744
    return {};
1 ✔
1745
  }
1746
  const std::optional<QByteArray> bytes =
1747
      Util::readRegularFileInStore(passStore, gpgIdPath, Util::kMaxGpgIdBytes);
45 ✔
1748
  if (!bytes) {
45 ✔
1749
    return {};
29 ✔
1750
  }
1751
  return parseRecipients(*bytes, gpgIdPath);
16 ✔
1752
}
1753

1754
auto Pass::parseRecipients(const QByteArray &contents,
292 ✔
1755
                           const QString &sourceName) -> QStringList {
1756
  QStringList recipients;
292 ✔
1757
  const QString text = QString::fromUtf8(contents);
1758
  for (const QString &line : text.split(QLatin1Char('\n'))) {
7,071 ✔
1759
    QString recipient = line.split(QLatin1Char('#')).first().trimmed();
13,558 ✔
1760
    if (recipient.isEmpty()) {
6,779 ✔
1761
      continue;
372 ✔
1762
    }
1763
    if (!Util::isValidKeyId(recipient)) {
6,407 ✔
1764
      // Never drop a recipient silently: the list is written back verbatim
1765
      // by UsersDialog, so a skipped line disappears from .gpg-id.
1766
      qCWarning(lcQtPass) << "Skipping unusable recipient in" << sourceName
4 ✔
1767
                          << ":" << recipient;
2 ✔
1768
      continue;
2 ✔
1769
    }
2 ✔
1770
    recipients += recipient;
1771
  }
1772
  return recipients;
292 ✔
1773
}
1774

1775
auto Pass::passReadsDifferently(const QByteArray &contents) -> QString {
103 ✔
1776
  if (contents.startsWith("\xEF\xBB\xBF")) {
103 ✔
1777
    return tr("it starts with a byte-order mark");
1778
  }
1779
  if (contents.contains('\0')) {
102 ✔
1780
    return tr("it holds a NUL byte");
1781
  }
1782
  if (contents.contains('\r')) {
100 ✔
1783
    return tr("it has Windows line ends (a carriage return)");
1784
  }
1785
  const QString text = QString::fromUtf8(contents);
1786
  if (text.toUtf8() != contents) {
99 ✔
1787
    return tr("it is not valid UTF-8");
1788
  }
1789
  const QStringList lines = text.split(QLatin1Char('\n'));
98 ✔
1790
  for (qsizetype i = 0; i < lines.size(); ++i) {
6,420 ✔
1791
    const QString &line = lines.at(i);
1792
    const QString recipient = line.left(line.indexOf(QLatin1Char('#')));
6,332 ✔
1793
    for (const QChar c : recipient) {
132,735 ✔
1794
      // read strips blanks and tabs; trimmed() strips every space.
1795
      if (c.isSpace() && c != QLatin1Char(' ') && c != QLatin1Char('\t')) {
126,410 ✔
1796
        return tr("line %1 holds whitespace other than blanks and tabs")
7 ✔
1797
            .arg(i + 1);
7 ✔
1798
      }
1799
    }
1800
    const QString trimmed = recipient.trimmed();
1801
    if (trimmed.startsWith(QLatin1Char('-'))) {
6,325 ✔
1802
      return tr("line %1 starts with a dash").arg(i + 1);
2 ✔
1803
    }
1804
    // The text after the last line feed: read hands it over but the loop
1805
    // ends without using it.
1806
    if (i == lines.size() - 1 && !trimmed.isEmpty()) {
6,323 ✔
1807
      return tr("its last line has no line end");
1808
    }
1809
  }
1810
  return {};
88 ✔
1811
}
1812

1813
/* Copyright (C) 2017 Jason A. Donenfeld <Jason@zx2c4.com>. All Rights Reserved.
1814
 */
1815

1816
auto Pass::boundedRandom(quint32 bound) -> quint32 {
7,620 ✔
1817
  if (bound < 2) {
7,620 ✔
1818
    return 0;
1819
  }
1820

1821
  quint32 randval;
1822
  // arc4random_uniform-style rejection against modulo bias: drop values
1823
  // below 2^32 % bound, which (1 + ~bound) % bound computes in quint32.
1824
  const quint32 rejectionThreshold = (1 + ~bound) % bound;
7,616 ✔
1825

1826
  do {
1827
    randval = QRandomGenerator::system()->generate();
1828
  } while (randval < rejectionThreshold);
7,616 ✔
1829

1830
  return randval % bound;
7,616 ✔
1831
}
1832

1833
auto Pass::generateRandomPassword(const QString &charset, unsigned int length)
1,209 ✔
1834
    -> QString {
1835
  if (charset.isEmpty() || length == 0U) {
1,209 ✔
1836
    return {};
2 ✔
1837
  }
1838
  QString out;
1,207 ✔
1839
  for (unsigned int i = 0; i < length; ++i) {
8,827 ✔
1840
    out.append(charset.at(static_cast<int>(
7,620 ✔
1841
        boundedRandom(static_cast<quint32>(charset.length())))));
7,620 ✔
1842
  }
1843
  return out;
1844
}
1845

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