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

IJHack / QtPass / 44269343813

18 Nov 2026 08:42AM UTC coverage: 96.308% (+0.03%) from 96.28%
44269343813

Pull #2261

github

web-flow
Merge 977f9cff7 into ba6b598d3
Pull Request #2261: Git set-up refuses a FIFO and times out; a half-done pull stops re-encryption

60 of 64 new or added lines in 3 files covered. (93.75%)

17 existing lines in 2 files now uncovered.

9157 of 9508 relevant lines covered (96.31%)

1286.78 hits per line

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

92.99
/src/imitatepass.cpp
1
// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
/**
4
 * @file
5
 * @brief Implements ImitatePass: the gpg and git command sequences behind each
6
 * operation, the transactions that group them, and the re-encryption worker
7
 * thread.
8
 */
9
#include "imitatepass.h"
10
#include "executor.h"
11
#include "gpgidgeneration.h"
12
#include "util.h"
13
#include <QDateTime>
14
#include <QDir>
15
#include <QFile>
16
#include <QFileInfo>
17
#include <QLocale>
18
#include <QPointer>
19
#include <QProcess>
20
#include <QRegularExpression>
21
#include <QThread>
22
#include <QTimer>
23
#include <utility>
24

25
#include "qtpasslogging.h"
26

27
using Enums::CLIPBOARD_ALWAYS;
28
using Enums::CLIPBOARD_NEVER;
29
using Enums::CLIPBOARD_ON_DEMAND;
30
using Enums::GIT_ADD;
31
using Enums::GIT_COMMIT;
32
using Enums::GIT_COPY;
33
using Enums::GIT_INIT;
34
using Enums::GIT_MOVE;
35
using Enums::GIT_PULL;
36
using Enums::GIT_PUSH;
37
using Enums::GIT_RM;
38
using Enums::GPG_GENKEYS;
39
using Enums::INVALID;
40
using Enums::PASS_COPY;
41
using Enums::PASS_GREP;
42
using Enums::PASS_INIT;
43
using Enums::PASS_INSERT;
44
using Enums::PASS_MOVE;
45
using Enums::PASS_REMOVE;
46
using Enums::PASS_SHOW;
47
using Enums::PROCESS_COUNT;
48

49
ImitatePass::ImitatePass() : m_grep(this) {
208 ✔
50
  connect(&m_grep, &NativeGrep::finished, this, &ImitatePass::finishedGrep);
208 ✔
51
}
208 ✔
52

53
ImitatePass::~ImitatePass() {
215 ✔
54
  // Grep workers wind down meanwhile; m_grep's destructor waits for them.
55
  m_grep.cancel();
208 ✔
56
  // The re-encryption worker calls members, so join it with no timeout; it
57
  // ends its own blocked process on the flag (see execBlocking()).
58
  if (m_reencryptThread && m_reencryptThread->isRunning()) {
208 ✔
59
    m_reencryptCancel.store(true);
60
    m_reencryptThread->wait();
3 ✔
61
  }
62
}
423 ✔
63

64
// The helpers are shared by the owning thread and the worker; thread affinity
65
// tells them apart. Only the worker touches its QProcess, so a cancel can
66
// never hit an exited process or a reused pid.
67
auto ImitatePass::prepareBlocking(QProcess &process)
743 ✔
68
    -> const std::atomic_bool * {
69
  // In the store's environment: the git ceiling QtPass's own does not
70
  // carry.
71
  if (QThread::currentThread() == thread()) {
743 ✔
72
    process.setProcessEnvironment(storeEnvironment());
276 ✔
73
    return nullptr;
276 ✔
74
  }
75
  process.setProcessEnvironment(withCurrentGitPin(m_reencryptEnv));
467 ✔
76
  return &m_reencryptCancel;
467 ✔
77
}
78

79
auto ImitatePass::execBlocking(const QString &app, const QStringList &args,
519 ✔
80
                               const QString &input, QString *process_out,
81
                               QString *process_err) -> int {
82
  QProcess process;
519 ✔
83
  const std::atomic_bool *cancel = prepareBlocking(process);
519 ✔
84
  return Executor::executeBlocking(process, app, args, input, process_out,
519 ✔
85
                                   process_err, cancel);
519 ✔
86
}
519 ✔
87

88
auto ImitatePass::execBlockingRaw(const QString &app, const QStringList &args,
224 ✔
89
                                  const QByteArray &input,
90
                                  QByteArray *process_out) -> int {
91
  QProcess process;
224 ✔
92
  const std::atomic_bool *cancel = prepareBlocking(process);
224 ✔
93
  return Executor::executeBlockingRaw(process, app, args, input, process_out,
224 ✔
94
                                      nullptr, cancel);
224 ✔
95
}
224 ✔
96

97
auto ImitatePass::execBlocking(const QString &app, const QStringList &args,
341 ✔
98
                               QString *process_out, QString *process_err)
99
    -> int {
100
  return execBlocking(app, args, QString(), process_out, process_err);
682 ✔
101
}
102

103
auto ImitatePass::translatePathForWsl(const QString &path,
767 ✔
104
                                      const QString &exe) const -> QString {
105
  return Executor::translatePathForWsl(path, exe);
767 ✔
106
}
107

108
auto ImitatePass::storeGit(const QStringList &args, QString *out) -> bool {
130 ✔
109
  if (!m_settings.useGit || m_settings.gitExecutable.isEmpty()) {
130 ✔
110
    return false;
111
  }
112
  // -C the store: executeBlocking sets no working directory, so git would
113
  // otherwise run in QtPass's launch directory.
114
  const QString store = pgit(m_settings.passStore);
118 ✔
115
  return execBlocking(m_settings.gitExecutable,
118 ✔
116
                      QStringList{QStringLiteral("-C"), store} + args, out,
472 ✔
117
                      nullptr) == 0;
118 ✔
118
}
119

120
auto ImitatePass::pgit(const QString &path) const -> QString {
313 ✔
121
  return translatePathForWsl(path, m_settings.gitExecutable);
313 ✔
122
}
123

124
auto ImitatePass::pgpg(const QString &path) const -> QString {
454 ✔
125
  return translatePathForWsl(path, m_settings.gpgExecutable);
454 ✔
126
}
127

128
void ImitatePass::GitInit() {
1 ✔
129
  executeGit(GIT_INIT, {"init", pgit(m_settings.passStore)});
4 ✔
130
}
2 ✔
131

132
void ImitatePass::GitPull() {
6 ✔
133
  if (gitReady()) {
6 ✔
134
    executeGit(GIT_PULL, {"pull"});
24 ✔
135
  }
136
}
6 ✔
137

138
// Blocks until git finishes.
139
void ImitatePass::GitPull_b() {
4 ✔
140
  if (!gitReady())
4 ✔
141
    return;
1 ✔
142
  // -C the store: executeBlocking sets no working directory, so without it
143
  // git would run in QtPass's launch directory and pull an unrelated
144
  // repository, or fail with "not a git repository".
145
  QString err;
3 ✔
146
  const int rc =
147
      execBlocking(m_settings.gitExecutable,
15 ✔
148
                   {"-C", pgit(m_settings.passStore), "pull"}, nullptr, &err);
3 ✔
149
  if (rc != 0) {
3 ✔
150
    emit statusMsg(tr("Git pull failed: %1").arg(err.trimmed()), 5000);
4 ✔
151
  }
152
}
3 ✔
153

154
void ImitatePass::GitPush() {
17 ✔
155
  // Now it would send the new .gpg-id with entries still encrypted to the
156
  // previous recipients, a key just removed among them, also when the run
157
  // then fails, and push a clean run twice.
158
  if (m_reencryptActive && !m_reencryptPushing) {
17 ✔
159
    m_pushAfterReencrypt = true;
2 ✔
160
    return;
2 ✔
161
  }
162
  if (gitReady()) {
15 ✔
163
    executeGit(GIT_PUSH, {"push"});
60 ✔
164
  }
165
}
166

167
void ImitatePass::Show(QString file) {
74 ✔
168
  if (refuseLinkedPath(file + ".gpg")) {
148 ✔
169
    return;
4 ✔
170
  }
171
  queueShow(file);
172
  file = m_settings.passStore + file + ".gpg";
70 ✔
173
  QStringList args = {"-d",      "--quiet",    "--yes", "--no-encrypt-to",
174
                      "--batch", "--use-agent"};
910 ✔
175
  args << maxOutputArgs() << QStringLiteral("--") << pgpg(file);
210 ✔
176
  executeGpg(PASS_SHOW, args);
140 ✔
177
}
178

179
namespace {
180

181
/**
182
 * @brief The arguments of every gpg encrypt call: @p leading, then encrypt
183
 * to exactly @p recipients from stdin into @p output. --no-encrypt-to keeps
184
 * an `encrypt-to` line in the user's gpg.conf from adding a recipient the
185
 * (possibly signed) .gpg-id does not list; --compress-algo=none mirrors
186
 * pass(1). --no-textmode keeps a `textmode` line from storing the entry as
187
 * text, which a decrypt hands back without its carriage returns: the entry
188
 * is stored as the bytes given.
189
 */
190
auto encryptArgs(QStringList leading, const QString &output,
131 ✔
191
                 const QStringList &recipients) -> QStringList {
192
  leading << "-eq" << "--compress-algo=none" << "--no-encrypt-to"
524 ✔
193
          << "--no-textmode" << "--output" << output;
393 ✔
194
  for (const QString &recipient : recipients) {
265 ✔
195
    leading << "-r" << recipient;
268 ✔
196
  }
197
  leading << "-";
262 ✔
198
  return leading;
131 ✔
199
}
200

201
} // namespace
202

203
auto ImitatePass::recipientsForEntry(const QString &file,
73 ✔
204
                                     QStringList *recipients) -> bool {
205
  recipients->clear();
73 ✔
206
  if (refuseSkippedGpgId(file, gpgIdSigner().enabled())) {
73 ✔
207
    return false;
208
  }
209
  QString why;
71 ✔
210
  if (!loadVerifiedRecipients(Pass::getGpgIdPath(file, m_settings.passStore),
142 ✔
211
                              recipients, &why)) {
212
    emit critical(tr("Check .gpg-id file signature!"), why);
5 ✔
213
    return false;
5 ✔
214
  }
215
  if (recipients->isEmpty()) {
66 ✔
216
    emit critical(tr("Can not edit"),
2 ✔
217
                  tr("Could not read encryption key to use, .gpg-id "
×
218
                     "file missing or invalid."));
219
    return false;
1 ✔
220
  }
221
  return true;
222
}
223

224
void ImitatePass::Insert(QString file, QString newValue, bool overwrite) {
78 ✔
225
  // The dialog names a new entry relative to the store; gpg used to resolve
226
  // that in its working directory. Everything below works on the one path.
227
  file =
228
      QDir::cleanPath(QDir::isAbsolutePath(file)
78 ✔
229
                          ? file + ".gpg"
135 ✔
230
                          : QDir(m_settings.passStore).filePath(file) + ".gpg");
192 ✔
231
  if (refuseLinkedPath(file)) {
78 ✔
232
    return;
73 ✔
233
  }
234
  if (refuseUnfinishedGitOperation()) {
76 ✔
235
    return;
236
  }
237
  // gpg used to refuse an existing output without --yes; it writes
238
  // elsewhere now, so the check is ours here, and again at the rename.
239
  const QFileInfo target(file);
74 ✔
240
  if (!overwrite && (target.exists() || target.isSymLink())) {
74 ✔
241
    emit critical(tr("Cannot add"), tr("%1 already exists.").arg(file));
3 ✔
242
    return;
1 ✔
243
  }
244
  QStringList recipients;
73 ✔
245
  if (!recipientsForEntry(file, &recipients)) {
73 ✔
246
    return;
247
  }
248
  // gpg never opens a store path for output: a co-writer could make it a link
249
  // after refuseLinkedPath(). gpg writes into a 0700 directory of our own and
250
  // placeEncryptedFile() brings the bytes in via an open handle and a rename.
251
  auto scratch = std::make_shared<QTemporaryDir>();
252
  if (!scratch->isValid()) {
65 ✔
253
    emit critical(tr("Cannot write"),
2 ✔
254
                  tr("Cannot create a temporary directory: %1")
1 ✔
255
                      .arg(scratch->errorString()));
2 ✔
256
    return;
1 ✔
257
  }
258
  const QString output = scratch->filePath(QStringLiteral("entry.gpg"));
128 ✔
259
  TransactionHelper trans(&m_transaction, PASS_INSERT);
64 ✔
260
  const QStringList args =
261
      encryptArgs({"--batch", "--status-fd", "2"}, pgpg(output), recipients);
512 ✔
262
  m_pendingInserts.enqueue({std::move(scratch), output, file, overwrite});
64 ✔
263
  // Past every refusal: this insert is now queued and will report once.
264
  queueInsert();
265
  executeGpg(PASS_INSERT, args, newValue);
64 ✔
266
  if (!gitReady()) {
64 ✔
267
    return;
268
  }
269
  if (!overwrite) {
5 ✔
270
    executeGit(GIT_ADD, {"add", "--", pgit(file)});
25 ✔
271
  }
272
  gitCommit(file, QString(overwrite ? "Edit" : "Add") + " for " +
20 ✔
273
                      commitName(file) + " using QtPass.");
15 ✔
274
}
143 ✔
275

276
auto ImitatePass::commitArgs() -> QStringList {
42 ✔
277
  // As pass's git_commit(): -S when the store (or the user's git config)
278
  // sets pass.signcommits. A commit that cannot be signed then fails, as
279
  // with pass, rather than going in unsigned.
280
  QString out;
42 ✔
281
  const bool sign = execBlocking(m_settings.gitExecutable,
336 ✔
282
                                 {"-C", pgit(m_settings.passStore), "config",
42 ✔
283
                                  "--bool", "--get", "pass.signcommits"},
284
                                 &out) == 0 &&
42 ✔
285
                    out.trimmed() == QLatin1String("true");
70 ✔
286
  return sign ? QStringList{"commit", "-S"} : QStringList{"commit"};
132 ✔
287
}
42 ✔
288

289
void ImitatePass::gitCommit(const QString &file, const QString &msg) {
9 ✔
290
  gitCommit(QStringList{file}, msg);
27 ✔
291
}
9 ✔
292

293
void ImitatePass::gitCommit(const QStringList &files, const QString &msg) {
12 ✔
294
  QStringList args = commitArgs() + QStringList{"-m", msg, "--"};
72 ✔
295
  for (const QString &file : files) {
27 ✔
296
    args << pgit(file);
30 ✔
297
  }
298
  executeGit(GIT_COMMIT, args);
24 ✔
299
}
36 ✔
300

301
void ImitatePass::Remove(QString file, bool isDir) {
18 ✔
302
  // No trailing separator: "link/" makes git look for what is behind the
303
  // link ("pathspec did not match") and rm follow it.
304
  file = QDir::cleanPath(m_settings.passStore + file);
18 ✔
305
  if (!isDir) {
18 ✔
306
    file += ".gpg";
8 ✔
307
  }
308
  // A link itself may go; anything behind one is not the store's to delete.
309
  if (refuseLinkedPath(file, LinkScope::ParentsOnly)) {
18 ✔
310
    return;
10 ✔
311
  }
312
  if (refuseUnfinishedGitOperation() || refusePendingPull()) {
16 ✔
313
    return;
1 ✔
314
  }
315
  TransactionHelper trans(&m_transaction, PASS_REMOVE);
15 ✔
316
  const QString path = commitName(file);
15 ✔
317
  if (Util::isLinkedFolder(file)) {
15 ✔
318
    // Unlink it here, never through a recursive rm: the link goes, what it
319
    // points to stays. Git then only has to forget it, if it knew it.
320
    if (!Util::removeTree(file)) {
7 ✔
321
      emit critical(tr("Delete failed"),
2 ✔
322
                    tr("Could not remove the link %1.").arg(file));
2 ✔
323
      return;
1 ✔
324
    }
325
    // Only when git knew it: a commit matching nothing (a link never
326
    // committed) exits 1 and reads as a failed removal. ls-files reads the
327
    // index, so it still answers now that the link is gone.
328
    if (gitReady() && gitTracks(file)) {
6 ✔
329
      executeGit(GIT_RM, {"rm", "-q", "--cached", "--", pgit(file)});
7 ✔
330
      gitCommit(file, "Remove for " + path + " using QtPass.");
2 ✔
331
    }
332
    return;
6 ✔
333
  }
334
  if (gitReady()) {
8 ✔
335
    executeGit(GIT_RM, {"rm", (isDir ? "-rf" : "-f"), "--", pgit(file)});
6 ✔
336
    gitCommit(file, "Remove for " + path + " using QtPass.");
2 ✔
337
  } else {
338
    // Without Git nothing else reports a failure: git rm would print its own.
339
    if (isDir) {
7 ✔
340
      // Never QDir::removeRecursively(): it follows a junction inside the
341
      // folder and empties whatever that points to.
342
      if (!Util::removeTree(file)) {
3 ✔
343
        // As rm -rf, it went on past what it could not remove: the folder
344
        // is still there, without the entries that could go.
345
        emit critical(tr("Delete failed"),
2 ✔
346
                      tr("Could not remove all of %1. What could be removed "
1 ✔
347
                         "is gone; check what is left in it.")
348
                          .arg(file));
2 ✔
349
      }
350
    } else {
351
      QFile entry(file);
4 ✔
352
      if (!entry.remove()) {
4 ✔
353
        emit critical(
1 ✔
354
            tr("Delete failed"),
1 ✔
355
            tr("Could not remove %1: %2").arg(file, entry.errorString()));
2 ✔
356
      }
357
    }
4 ✔
358
  }
359
}
3 ✔
360

361
auto ImitatePass::gpgIdSigner() -> GpgIdSigner {
374 ✔
362
  return {m_settings.gpgExecutable,
363
          GpgIdSigner::keysFromSetting(m_settings.passSigningKey),
748 ✔
364
          [this](const QString &app, const QStringList &args,
374 ✔
365
                 const QString &input, QString *out, QString *err) {
366
            return execBlocking(app, args, input, out, err);
121 ✔
367
          }};
748 ✔
368
}
369

370
auto ImitatePass::addGenerationHeader(const QString &gpgIdFile,
24 ✔
371
                                      const GpgIdSigner &signer,
372
                                      QByteArray *contents) -> bool {
373
  const std::optional<QString> folder =
374
      GpgIdGeneration::folderOf(gpgIdFile, m_settings.passStore);
24 ✔
375
  if (!folder) {
24 ✔
376
    emit critical(tr("Cannot update"),
×
377
                  tr("%1 is not inside the password store, or a folder "
×
378
                     "name on the way holds a line break or another control "
379
                     "character, which a signed list cannot record.")
380
                      .arg(gpgIdFile));
×
381
    return false;
×
382
  }
383
  // The list on disk counts only if it is this folder's own, verified list:
384
  // a signature vouches for the bytes, the folder line for the place.
385
  std::optional<qint64> verifiedOnDisk;
24 ✔
386
  std::optional<QString> storeOnDisk;
24 ✔
387
  QByteArray current;
24 ✔
388
  if (signer.verifyFile(gpgIdFile, &current)) {
24 ✔
389
    const auto header = GpgIdGeneration::parse(current);
7 ✔
390
    if (header && (!header->folder || *header->folder == *folder)) {
7 ✔
391
      verifiedOnDisk = header->generation;
6 ✔
392
      storeOnDisk = header->store;
393
    }
394
  }
395
  QString why;
24 ✔
396
  // The store's id: the one this device knows, else the one this store's
397
  // lists already carry (#2050).
398
  const std::optional<QString> store =
399
      GpgIdGeneration::storeIdFor(m_settings.passStore, storeOnDisk, &why);
24 ✔
400
  if (!store) {
24 ✔
401
    emit critical(tr("Cannot update"), why);
×
402
    return false;
×
403
  }
404
  const std::optional<qint64> generation =
405
      GpgIdGeneration::reserveNext(gpgIdFile, verifiedOnDisk, &why);
24 ✔
406
  if (!generation) {
24 ✔
407
    emit critical(tr("Cannot update"), why);
×
408
    return false;
×
409
  }
410
  *contents =
411
      GpgIdGeneration::withHeader(*generation, *folder, *contents, *store);
24 ✔
412
  return true;
24 ✔
413
}
414

415
auto ImitatePass::writeGpgIdFile(const QString &gpgIdFile,
39 ✔
416
                                 const QList<UserInfo> &users,
417
                                 QByteArray *written) -> bool {
418
  QByteArray contents;
39 ✔
419
  bool secret_selected = false;
420
  for (const UserInfo &user : users) {
82 ✔
421
    if (user.enabled) {
43 ✔
422
      contents += (user.key_id + "\n").toUtf8();
43 ✔
423
      secret_selected |= user.have_secret;
43 ✔
424
    }
425
  }
426
  // Without a signing key the plain list stays (GpgIdGeneration).
427
  const GpgIdSigner signer = gpgIdSigner();
39 ✔
428
  if (signer.enabled() && !addGenerationHeader(gpgIdFile, signer, &contents)) {
39 ✔
429
    return false;
430
  }
431
  // Whole or not at all, owner-only (it names the store's keys); a link
432
  // planted since Init's check is replaced, not written through.
433
  QString writeError;
39 ✔
434
  if (!Util::writeFileReplacing(gpgIdFile, contents, true, &writeError)) {
39 ✔
435
    emit critical(tr("Cannot update"), writeError);
1 ✔
436
    return false;
1 ✔
437
  }
438
  if (written != nullptr) {
38 ✔
439
    *written = contents;
34 ✔
440
  }
441
  if (signer.enabled()) {
38 ✔
442
    // From now on these bytes are this generation. The list is signed either
443
    // way (unsigned is refused everywhere); if the record could not take them
444
    // (another writer, record busy), the user is told to save once more.
445
    QString why;
24 ✔
446
    if (!GpgIdGeneration::recordWritten(gpgIdFile, contents, &why)) {
24 ✔
447
      qCWarning(lcQtPass) << "Could not record the written .gpg-id:" << why;
×
448
      emit critical(
×
449
          tr("Recipient list written, but not recorded"),
×
450
          tr("%1 Save the recipients once more to get through.").arg(why));
×
451
    }
452
  }
453
  if (!secret_selected) {
38 ✔
454
    emit critical(
4 ✔
455
        tr("Check selected users!"),
2 ✔
456
        tr("None of the selected keys have a secret key available.\n"
2 ✔
457
           "You will not be able to decrypt any newly added passwords!"));
458
  }
459
  return true;
460
}
39 ✔
461

462
auto ImitatePass::signGpgIdFile(const QString &gpgIdFile,
24 ✔
463
                                const QByteArray &contents) -> bool {
464
  const GpgIdSigner signer = gpgIdSigner();
24 ✔
465
  QString why;
24 ✔
466
  if (!signer.sign(gpgIdFile, contents, &why)) {
24 ✔
467
    emit critical(
6 ✔
468
        tr("GPG signing failed!"),
3 ✔
469
        why.trimmed().isEmpty()
3 ✔
470
            ? tr("Failed to sign %1.").arg(gpgIdFile)
9 ✔
471
            : tr("Failed to sign %1: %2").arg(gpgIdFile, why.trimmed()));
7 ✔
472
    return false;
3 ✔
473
  }
474
  QByteArray signedBytes;
21 ✔
475
  if (!signer.verifyFile(gpgIdFile, &signedBytes)) {
21 ✔
476
    emit critical(tr("Check .gpg-id file signature!"),
×
477
                  tr("Signature for %1 is invalid.").arg(gpgIdFile));
×
478
    return false;
×
479
  }
480
  return true;
481
}
24 ✔
482

483
// Synchronous on purpose: queued on the async executor, the add/commit raced
484
// reencryptPath()'s blocking backup commit for index.lock and either left the
485
// .gpg-id untracked or found nothing to commit.
486
auto ImitatePass::gitAddGpgId(const QString &gpgIdFile,
9 ✔
487
                              const QString &gpgIdSigFile, QString *out,
488
                              QString *err) -> int {
489
  const QString git = m_settings.gitExecutable;
490
  const QString store = pgit(m_settings.passStore);
9 ✔
491
  auto run = [&](const QStringList &args) -> int {
25 ✔
492
    QString runOut;
25 ✔
493
    QString runErr;
25 ✔
494
    const int rc =
495
        execBlocking(git, QStringList{"-C", store} + args, &runOut, &runErr);
100 ✔
496
    if (out != nullptr) {
25 ✔
497
      out->append(runOut);
25 ✔
498
    }
499
    if (err != nullptr) {
25 ✔
500
      err->append(runErr);
25 ✔
501
    }
502
    return rc;
25 ✔
503
  };
25 ✔
504
  QStringList paths{pgit(gpgIdFile)};
18 ✔
505
  if (!gpgIdSigFile.isEmpty()) {
9 ✔
506
    paths << pgit(gpgIdSigFile);
12 ✔
507
  }
508
  // add stages new and modified files alike; already-clean ones are a no-op.
509
  int rc = run(QStringList{"add", "--"} + paths);
54 ✔
510
  if (rc != 0) {
9 ✔
511
    return rc;
512
  }
513
  // Re-initialising with the same recipients changes nothing; that is not a
514
  // failure, and `git commit` would make it one. diff --quiet: 0 nothing
515
  // staged, 1 something staged, anything else is git failing.
516
  rc = run(QStringList{"diff", "--cached", "--quiet", "--"} + paths);
80 ✔
517
  if (rc == 0) {
8 ✔
518
    return 0;
519
  }
520
  if (rc != 1) {
8 ✔
521
    return rc;
522
  }
523
  return run(commitArgs() +
24 ✔
524
             QStringList{"-m",
8 ✔
525
                         "Added " + commitName(gpgIdFile) + " using QtPass.",
8 ✔
526
                         "--"} +
56 ✔
527
             paths);
8 ✔
528
}
25 ✔
529

530
auto ImitatePass::gitTracks(const QString &file) -> bool {
3 ✔
531
  return execBlocking(m_settings.gitExecutable,
24 ✔
532
                      {"-C", pgit(m_settings.passStore), "ls-files",
3 ✔
533
                       "--error-unmatch", "--", pgit(file)}) == 0;
6 ✔
534
}
3 ✔
535

536
auto ImitatePass::refuseLinkedGpgIdFolder(const QString &path) -> bool {
41 ✔
537
  // A link planted later is replaced, not written through: the writes stage
538
  // and rename.
539
  const QString folder = QDir::cleanPath(path);
41 ✔
540
  // Init() places a folder spelled through a linked root's target itself.
541
  const auto refusePlaced = [this](const QString &placed) {
542
    return refuseLinkedPath(placed, LinkScope::EntryAndParents,
120 ✔
543
                            PathSpelling::PlacedByCaller);
544
  };
545
  return refusePlaced(path) ||
40 ✔
546
         refusePlaced(folder + QStringLiteral("/.gpg-id")) ||
122 ✔
547
         refusePlaced(folder + QStringLiteral("/.gpg-id.sig"));
160 ✔
548
}
549

550
auto ImitatePass::settleSignature(const QString &gpgIdFile,
34 ✔
551
                                  const QByteArray &written,
552
                                  const GpgIdSigner &signer, bool useGit,
553
                                  QString *sigToCommit) -> bool {
554
  const QString gpgIdSigFile = gpgIdFile + ".sig";
34 ✔
555
  if (signer.enabled()) {
34 ✔
556
    if (!signGpgIdFile(gpgIdFile, written)) {
24 ✔
557
      return false;
558
    }
559
    *sigToCommit = gpgIdSigFile;
21 ✔
560
    return true;
21 ✔
561
  }
562
  if (!QFile::exists(gpgIdSigFile)) {
10 ✔
563
    return true;
564
  }
565
  // Signing was switched off; the removal goes into the same commit.
566
  const bool tracked = useGit && gitTracks(gpgIdSigFile);
3 ✔
567
  if (!QFile::remove(gpgIdSigFile)) {
3 ✔
568
    emit critical(
2 ✔
569
        tr("Cannot update"),
1 ✔
570
        tr("Failed to remove the old signature %1.").arg(gpgIdSigFile));
2 ✔
571
    return false;
1 ✔
572
  }
573
  if (tracked) {
2 ✔
574
    *sigToCommit = gpgIdSigFile;
1 ✔
575
  }
576
  return true;
577
}
578

579
void ImitatePass::Init(QString path, const QList<UserInfo> &users) {
41 ✔
580
  // The .gpg-id is written as path + ".gpg-id": without the trailing
581
  // separator (the context menu hands over a cleaned path) that would be a
582
  // file beside the folder, not the folder's own list. A relative path names
583
  // a folder in the store, as it does for pass, not one in the working
584
  // directory.
585
  if (!QDir::isAbsolutePath(path)) {
41 ✔
586
    path = QDir(m_settings.passStore).filePath(path);
4 ✔
587
  }
588
  // Cleaned before any check: the checks clean what they look at, and the
589
  // write must go to the same place. Left as /store/link/../team/, the
590
  // system resolves link first and writes beside wherever it points.
591
  path = Util::normalizeFolderPath(QDir::cleanPath(path));
41 ✔
592
  QString inStore;
41 ✔
593
  if (refuseLinkedGpgIdFolder(path) ||
80 ✔
594
      refuseFolderOutsideStore(path, &inStore)) {
39 ✔
595
    return;
5 ✔
596
  }
597
  if (refuseUnfinishedGitOperation()) {
36 ✔
598
    return;
599
  }
600
  // From here on in the store's own spelling, the same folder: one spelled
601
  // through the target of a linked store root is not under the store as
602
  // named, so each entry's nearest list was looked up past the new one and
603
  // the entries were encrypted to the store root's.
604
  path = Util::normalizeFolderPath(
36 ✔
605
      QDir::cleanPath(QDir(m_settings.passStore).filePath(inStore)));
72 ✔
606
  // A running re-encryption cannot take a second folder: the new list would
607
  // be written and its entries left encrypted to the old recipients, which
608
  // for a removed person means they can still read them. Nothing is written.
609
  if (m_reencryptActive) {
36 ✔
610
    emit critical(tr("Recipients not changed"),
2 ✔
611
                  tr("A re-encryption is still running. Wait until it has "
×
612
                     "finished, then save the recipients again."));
613
    return;
1 ✔
614
  }
615
  const GpgIdSigner signer = gpgIdSigner();
35 ✔
616
  if (signer.enabled() && !signer.haveSecretKey()) {
35 ✔
617
    emit critical(tr("No signing key!"),
2 ✔
618
                  tr("None of the secret signing keys is available.\n"
1 ✔
619
                     "You will not be able to change the user list!"));
620
    return;
1 ✔
621
  }
622

623
  const bool useGit = gitReady();
34 ✔
624
  const QString gpgIdFile = path + ".gpg-id";
34 ✔
625
  QByteArray written;
34 ✔
626
  QString sigToCommit;
34 ✔
627
  if (!writeGpgIdFile(gpgIdFile, users, &written)) {
34 ✔
628
    return;
629
  }
630
  // The new list is on disk: held from here, so a stop before the run (a
631
  // signature that fails, a refused start) leaves it out of a later backup
632
  // commit's push; a clean run of this folder releases it.
633
  holdAutoPush(path);
34 ✔
634
  if (!settleSignature(gpgIdFile, written, signer, useGit, &sigToCommit)) {
34 ✔
635
    return;
636
  }
637

638
  QString gitOut;
30 ✔
639
  QString gitErr;
30 ✔
640
  if (useGit && m_settings.addGPGId) {
30 ✔
641
    // Commit the .gpg-id (and .sig) before re-encrypting to it: the backup
642
    // commit only takes tracked files (#1685) and addFolder does not stage
643
    // it, so entries were pushed without their recipients file (#1682).
644
    const int gitExit = gitAddGpgId(gpgIdFile, sigToCommit, &gitOut, &gitErr);
9 ✔
645
    if (gitExit != 0) {
9 ✔
646
      Pass::finished(PASS_INIT, gitExit, gitOut, gitErr);
3 ✔
647
      // The new list is on disk either way. Stopping here left every entry
648
      // readable by whoever was just removed from it, so re-encrypt without
649
      // Git and say the change is not committed. Putting the old list back
650
      // is no way out: with signing the generation record has moved on and
651
      // would refuse it as a rollback.
652
      const QString why = gitErr.trimmed();
653
      reencryptWithoutGit(
3 ✔
654
          path,
655
          why.isEmpty() ? tr("Git exited with code %1.").arg(gitExit) : why);
10 ✔
656
      return;
657
    }
658
  }
659
  m_writtenGpgId = WrittenGpgId{gpgIdFile, written};
27 ✔
660
  reencryptPath(path);
27 ✔
661
  if (!m_reencryptActive) {
27 ✔
662
    // Refused before it started; reencryptPath() said why.
663
    m_writtenGpgId.reset();
664
  }
665
  // finishedInit once the .gpg-id landed in git, as the async path did.
666
  if (useGit) {
27 ✔
667
    Pass::finished(PASS_INIT, 0, gitOut, gitErr);
7 ✔
668
  }
669
}
35 ✔
670

671
auto ImitatePass::loadVerifiedRecipients(const QString &gpgIdFile,
136 ✔
672
                                         QStringList *recipients, QString *why)
673
    -> bool {
674
  recipients->clear();
136 ✔
675
  if (why != nullptr) {
136 ✔
676
    *why = tr("Signature for %1 is invalid.").arg(gpgIdFile);
270 ✔
677
  }
678
  // A link under the .gpg-id name is not the store's list: with signing
679
  // off it reads as missing, with signing on verifyFile() refuses it.
680
  if (Util::isLinkedFolder(gpgIdFile)) {
136 ✔
681
    return !gpgIdSigner().enabled();
1 ✔
682
  }
683
  QByteArray contents;
135 ✔
684
  const GpgIdSigner signer = gpgIdSigner();
135 ✔
685
  if (signer.enabled()) {
135 ✔
686
    if (!verifySignedList(signer, gpgIdFile, &contents, why)) {
22 ✔
687
      return false;
688
    }
689
  } else {
690
    if (const QFileInfo info(gpgIdFile); !info.exists() && !info.isSymLink()) {
113 ✔
691
      // No file is not a bad signature; the empty list says it all.
692
      return true;
693
    }
113 ✔
694
    // Bounded, and only a regular file: see Util::readRegularFile().
695
    std::optional<QByteArray> bytes =
696
        Util::readRegularFile(gpgIdFile, Util::kMaxGpgIdBytes);
111 ✔
697
    if (!bytes) {
111 ✔
698
      if (why != nullptr) {
×
699
        *why = tr("%1 cannot be read as a recipient list (a regular file "
×
700
                  "of at most %2).")
701
                   .arg(gpgIdFile,
×
702
                        QLocale().formattedDataSize(Util::kMaxGpgIdBytes));
×
703
      }
704
      return false;
705
    }
706
    contents = *std::move(bytes);
707
  }
708
  *recipients = Pass::parseRecipients(contents, gpgIdFile);
127 ✔
709
  return true;
127 ✔
710
}
135 ✔
711

712
void ImitatePass::reportUnrestorable(const QString &path) {
2 ✔
713
  emit critical(tr("Leftover from an earlier re-encryption"),
6 ✔
714
                tr("%1 is not a regular file and was not restored. Look "
2 ✔
715
                   "at it and remove it, then re-encrypt again.")
716
                    .arg(path));
4 ✔
717
}
2 ✔
718

719
void ImitatePass::dropStaleTemporary(const QString &path) {
4 ✔
720
  // A crash's temporary is picked up by a run an hour later.
721
  if (QFileInfo(path).lastModified() >
8 ✔
722
      QDateTime::currentDateTime().addSecs(-3600)) {
8 ✔
723
    qCDebug(lcQtPass) << "Leaving a recent temporary alone:" << path;
1 ✔
724
    return;
1 ✔
725
  }
726
  if (!QFile::remove(path)) {
3 ✔
727
    qCWarning(lcQtPass) << "Could not remove stale temporary" << path;
×
728
  }
729
}
730

731
auto ImitatePass::restoreBackup(const QString &path) -> bool {
2 ✔
732
  // Belt and braces: the walker only lists regular files.
733
  const QFileInfo backup(path);
2 ✔
734
  if (backup.isSymLink() || !backup.isFile()) {
2 ✔
735
    reportUnrestorable(path);
×
736
    return false;
737
  }
738
  const QString original =
739
      path.chopped(QStringLiteral(".reencrypt.bak").size());
2 ✔
740
  if (QFileInfo::exists(original)) {
2 ✔
741
    emit critical(tr("Leftover from an earlier re-encryption"),
3 ✔
742
                  tr("%1 exists next to %2. Both are encrypted copies of the "
1 ✔
743
                     "entry; check which one you want and delete the other, "
744
                     "then re-encrypt again.")
745
                      .arg(path, original));
1 ✔
746
    return false;
1 ✔
747
  }
748
  if (!QFile::rename(path, original)) {
1 ✔
749
    emit critical(tr("Leftover from an earlier re-encryption"),
×
750
                  tr("%1 is missing and its backup %2 could not be renamed "
×
751
                     "back. Rename it by hand, then re-encrypt again.")
752
                      .arg(original, path));
×
753
    return false;
×
754
  }
755
  qCWarning(lcQtPass) << "Restored" << original << "from" << path;
2 ✔
756
  emit statusMsg(tr("Restored %1 from the backup an interrupted "
2 ✔
757
                    "re-encryption left behind.")
758
                     .arg(original),
2 ✔
759
                 5000);
760
  return true;
1 ✔
761
}
2 ✔
762

763
auto ImitatePass::recoverReencryptLeftovers(const QString &dir) -> bool {
93 ✔
764
  // .qtpass-XXXXXX.tmp is today's staging name; 1.8.x replaced entries via
765
  // X.gpg.reencrypt.tmp and .bak in two renames, builds up to 2.0 wrote
766
  // X.gpg.XXXXXX.tmp. A .tmp is never a source of truth; a .bak is the only
767
  // copy when X.gpg is missing, and one of two valid ones when it is not.
768
  //
769
  // Regular files only: renaming a link under a leftover name into an entry's
770
  // place would re-encrypt whatever it points to. Links come back in
771
  // `skipped`; linked directories are left to reencryptFiles() to mention.
772
  const QStringList leftoverNames{QStringLiteral(".qtpass-??????.tmp"),
186 ✔
773
                                  QStringLiteral("*.gpg.reencrypt.tmp"),
93 ✔
774
                                  QStringLiteral("*.gpg.??????.tmp"),
93 ✔
775
                                  QStringLiteral("*.gpg.reencrypt.bak")};
465 ✔
776
  const auto isTemporary = [](const QString &path) {
10 ✔
777
    return path.endsWith(QStringLiteral(".tmp"));
20 ✔
778
  };
779
  QStringList skipped;
93 ✔
780
  // Hidden files included: the staged name starts with a dot.
781
  const QStringList leftovers = Util::regularFilesUnder(
782
      QDir::cleanPath(dir), leftoverNames, &skipped, true);
186 ✔
783
  bool clean = true;
784
  for (const QString &path : skipped) {
98 ✔
785
    if (!QDir::match(leftoverNames, QFileInfo(path).fileName())) {
10 ✔
786
      continue;
1 ✔
787
    }
788
    // Removing a link removes the link, never what it points to; a junction
789
    // or a directory symlink on Windows is a directory entry and goes with
790
    // rmdir.
791
    if (isTemporary(path)) {
4 ✔
792
      if (!QFile::remove(path) && !QDir().rmdir(path)) {
2 ✔
793
        qCWarning(lcQtPass) << "Could not remove stale temporary" << path;
×
794
      }
795
      continue;
2 ✔
796
    }
2 ✔
797
    reportUnrestorable(path);
2 ✔
798
    clean = false;
799
  }
800
  for (const QString &path : leftovers) {
99 ✔
801
    if (isTemporary(path)) {
6 ✔
802
      dropStaleTemporary(path);
4 ✔
803
    } else {
804
      clean = restoreBackup(path) && clean;
2 ✔
805
    }
806
  }
807
  return clean;
93 ✔
808
}
809

810
auto ImitatePass::verifyGpgIdForDir(const QString &file,
67 ✔
811
                                    QHash<QString, QStringList> &verified,
812
                                    QStringList &gpgId) -> bool {
813
  // Before the cache: two folders can resolve to the same list, and only
814
  // one of them may have had its own.
815
  if (refuseSkippedGpgId(file, gpgIdSigner().enabled())) {
67 ✔
816
    return false;
817
  }
818
  const QString gpgIdPath = Pass::getGpgIdPath(file, m_settings.passStore);
65 ✔
819
  // Keyed by .gpg-id, so every file under it gets exactly the list its
820
  // signature covered.
821
  const auto cached = verified.constFind(gpgIdPath);
65 ✔
822
  if (cached != verified.constEnd()) {
823
    gpgId = cached.value();
824
    return true;
1 ✔
825
  }
826
  QStringList recipients;
64 ✔
827
  QString why;
64 ✔
828
  if (!loadVerifiedRecipients(gpgIdPath, &recipients, &why)) {
64 ✔
829
    // An interrupted gpg is a cancel, not a bad signature.
830
    if (!m_reencryptCancel.load())
1 ✔
831
      emit critical(tr("Check .gpg-id file signature!"), why);
2 ✔
832
    return false;
1 ✔
833
  }
834
  recipients.sort();
835
  verified.insert(gpgIdPath, recipients);
836
  gpgId = recipients;
837
  return true;
63 ✔
838
}
839

840
auto ImitatePass::getKeysFromFile(const QString &fileName) -> QStringList {
96 ✔
841
  QStringList args = {
842
      "-v",          "--no-secmem-warning", "--no-permission-warning",
843
      "--list-only", "--keyid-format=long", "--",
844
      pgpg(fileName)};
768 ✔
845
  QString keys;
96 ✔
846
  QString err;
96 ✔
847
  const int result = execBlocking(m_settings.gpgExecutable, args, &keys, &err);
96 ✔
848
  if (result != 0) {
96 ✔
849
    return {};
29 ✔
850
  }
851
  QStringList actualKeys;
67 ✔
852
  keys += err;
853
  QStringList key = keys.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
67 ✔
854
  QListIterator<QString> itr(key);
855
  while (itr.hasNext()) {
115 ✔
856
    QString current = itr.next();
857
    QStringList cur = current.split(" ");
96 ✔
858
    if (cur.length() > 4) {
48 ✔
859
      QString actualKey = cur.takeAt(4);
34 ✔
860
      if (actualKey.length() == 16) {
34 ✔
861
        actualKeys << actualKey;
862
      }
863
    }
864
  }
865
  actualKeys.sort();
866
  return actualKeys;
867
}
96 ✔
868

869
auto ImitatePass::decryptEntry(const QString &fileName, QByteArray *plaintext)
96 ✔
870
    -> bool {
871
  const QStringList args =
872
      QStringList{"-d",      "--quiet",    "--yes", "--no-encrypt-to",
96 ✔
873
                  "--batch", "--use-agent"} +
1,344 ✔
874
      maxOutputArgs() + QStringList{QStringLiteral("--"), pgpg(fileName)};
576 ✔
875
  if (execBlockingRaw(m_settings.gpgExecutable, args, QByteArray(),
192 ✔
876
                      plaintext) != 0 ||
96 ✔
877
      plaintext->isEmpty()) {
878
    qCDebug(lcQtPass) << "Decrypt error on re-encrypt for:" << fileName;
29 ✔
879
    return false;
29 ✔
880
  }
881
  // No newline added: an entry is re-encrypted as it was, as pass(1) does
882
  // (gpg -d | gpg -e); a binary key without one would have grown a byte.
883
  return true;
884
}
96 ✔
885

886
auto ImitatePass::encryptFor(const QString &output,
67 ✔
887
                             const QStringList &recipients,
888
                             const QByteArray &plaintext) -> bool {
889
  const QStringList args =
890
      encryptArgs({"--yes", "--batch"}, pgpg(output), recipients);
402 ✔
891
  if (execBlockingRaw(m_settings.gpgExecutable, args, plaintext, nullptr) !=
67 ✔
892
      0) {
893
    qCDebug(lcQtPass) << "Encrypt error on re-encrypt, output:" << output;
6 ✔
894
    return false;
6 ✔
895
  }
896
  return true;
897
}
898

899
auto ImitatePass::ciphertextHolds(const QString &ciphertext,
61 ✔
900
                                  const QByteArray &plaintext) -> bool {
901
  QByteArray decrypted;
61 ✔
902
  const QStringList args =
903
      QStringList{"-d", "--quiet", "--batch", "--use-agent"} + maxOutputArgs() +
610 ✔
904
      QStringList{QStringLiteral("--"), pgpg(ciphertext)};
305 ✔
905
  if (execBlockingRaw(m_settings.gpgExecutable, args, QByteArray(),
122 ✔
906
                      &decrypted) != 0 ||
61 ✔
907
      decrypted.isEmpty()) {
908
    qCDebug(lcQtPass) << "Verification failed for:" << ciphertext;
1 ✔
909
    return false;
1 ✔
910
  }
911
  // Defence in depth: gpg said it encrypted, and this is what comes back.
912
  // Exact: gpg returns the bytes it was given. Compared as text, the check
913
  // passed for an entry that had lost bytes, as both sides lost the same.
914
  if (decrypted != plaintext) {
60 ✔
915
    qCDebug(lcQtPass) << "Verification content mismatch for:" << ciphertext;
2 ✔
916
    return false;
2 ✔
917
  }
918
  return true;
919
}
61 ✔
920

921
auto ImitatePass::commitReencrypted(const QString &fileName) -> bool {
50 ✔
922
  if (!reencryptUsesGit()) {
50 ✔
923
    return true;
924
  }
925
  // -C the store so git runs there rather than in QtPass's launch directory
926
  // (executeBlocking sets no working directory).
927
  const QString store = pgit(m_settings.passStore);
17 ✔
928
  if (execBlocking(m_settings.gitExecutable,
119 ✔
929
                   {"-C", store, "add", "--", pgit(fileName)}) != 0) {
930
    // The file on disk is re-encrypted correctly; only the repository is
931
    // now behind. Report it so the caller counts this file as failed and
932
    // the run is not pushed.
933
    qCDebug(lcQtPass) << "git add failed after re-encrypting:" << fileName;
1 ✔
934
    return false;
1 ✔
935
  }
936
  const QString path = commitName(fileName);
16 ✔
937
  if (execBlocking(m_settings.gitExecutable,
32 ✔
938
                   QStringList{"-C", store} + commitArgs() +
80 ✔
939
                       QStringList{"-m",
16 ✔
940
                                   "Re-encrypt for " + path + " using QtPass.",
16 ✔
941
                                   "--", pgit(fileName)}) != 0) {
128 ✔
942
    qCDebug(lcQtPass) << "git commit failed after re-encrypting:" << fileName;
1 ✔
943
    return false;
1 ✔
944
  }
945
  return true;
946
}
82 ✔
947

948
auto ImitatePass::reencryptSingleFile(const QString &fileName,
96 ✔
949
                                      const QStringList &recipients,
950
                                      QString *why) -> bool {
951
  qCDebug(lcQtPass) << "reencrypt" << fileName << "for" << recipients.size()
96 ✔
952
                    << "recipients";
×
953
  if (recipients.isEmpty()) {
96 ✔
954
    emit critical(tr("Can not edit"),
×
955
                  tr("Could not read encryption key to use, .gpg-id "
×
956
                     "file missing or invalid."));
957
    return false;
×
958
  }
959
  QByteArray plaintext;
96 ✔
960
  if (!decryptEntry(fileName, &plaintext)) {
96 ✔
961
    return false;
962
  }
963

964
  // gpg writes outside the store, into a 0700 directory with an unguessable
965
  // name no co-writer can pre-create or link; placeEncryptedFile() then
966
  // replaces the entry in one rename, as in Insert().
967
  QTemporaryDir scratch;
67 ✔
968
  if (!scratch.isValid()) {
67 ✔
969
    qCDebug(lcQtPass) << "Cannot create a scratch directory for re-encrypting"
×
970
                      << fileName;
×
971
    return false;
×
972
  }
973
  const QString tempPath = scratch.filePath(QStringLiteral("reencrypted.tmp"));
134 ✔
974
  if (!encryptFor(tempPath, recipients, plaintext) ||
128 ✔
975
      !ciphertextHolds(tempPath, plaintext)) {
61 ✔
976
    return false;
9 ✔
977
  }
978

979
  // Another client may have removed the entry while gpg ran; the rename
980
  // would bring it back under its old name. Best effort: the check and the
981
  // replace are two steps, as pass's own write is.
982
  const QFileInfo still(fileName);
58 ✔
983
  if (!still.exists() && !still.isSymLink()) {
58 ✔
984
    qCDebug(lcQtPass) << "Entry vanished before it could be replaced:"
1 ✔
985
                      << fileName;
×
986
    return false;
1 ✔
987
  }
988
  if (!placeEncryptedFile(tempPath, fileName, true, why)) {
57 ✔
989
    // Reported once, in the run's summary: an unwritable folder fails every
990
    // entry alike. The old ciphertext stays unless the post-rename check
991
    // failed, and then `why` says so.
992
    if (why != nullptr && !why->contains(fileName)) {
14 ✔
993
      // Every reason but the copy's names the entry; that one names the
994
      // file gpg wrote, in a scratch directory the user never sees.
995
      *why = tr("%1 could not be re-encrypted: %2").arg(fileName, *why);
2 ✔
996
    }
997
    return false;
7 ✔
998
  }
999
  return commitReencrypted(fileName);
50 ✔
1000
}
125 ✔
1001

1002
namespace {
1003
/**
1004
 * @brief Whether `git status --porcelain` output lists an unmerged path.
1005
 *
1006
 * Porcelain v1 marks one with the status letters DD, AU, UD, UA, DU, AA or
1007
 * UU: a conflict that a merge, rebase, cherry-pick or `git stash pop` left
1008
 * unresolved.
1009
 * @param porcelain The output of `git status --porcelain`.
1010
 * @return true when at least one path is unmerged.
1011
 */
1012
auto listsUnmergedPath(const QString &porcelain) -> bool {
26 ✔
1013
  const QStringList lines = porcelain.split(u'\n', Qt::SkipEmptyParts);
26 ✔
1014
  for (const QString &line : lines) {
33 ✔
1015
    if (line.size() < 2) {
8 ✔
1016
      continue;
1017
    }
1018
    const QChar x = line.at(0);
1019
    const QChar y = line.at(1);
1020
    if (x == u'U' || y == u'U' || (x == y && (x == u'A' || x == u'D'))) {
8 ✔
1021
      return true;
1022
    }
1023
  }
1024
  return false;
1025
}
1026
} // namespace
1027

1028
auto ImitatePass::createBackupCommit() -> bool {
95 ✔
1029
  if (!reencryptUsesGit()) {
95 ✔
1030
    return true;
1031
  }
1032
  emit statusMsg(tr("Creating backup commit"), 2000);
54 ✔
1033
  const QString git = m_settings.gitExecutable;
1034
  // -C the store: executeBlocking sets no working directory, so git would
1035
  // run in QtPass's launch directory, possibly an unrelated repository.
1036
  const QString store = pgit(m_settings.passStore);
27 ✔
1037
  // Tracked files only: an untracked plaintext export or swap file must not
1038
  // be swept into a commit that autoPush sends to the shared remote.
1039
  QString statusOut;
27 ✔
1040
  if (execBlocking(
189 ✔
1041
          git, {"-C", store, "status", "--porcelain", "--untracked-files=no"},
1042
          &statusOut) != 0) {
1043
    // An interrupted git is a cancel, not a failure worth a dialog.
1044
    if (!m_reencryptCancel.load())
1 ✔
1045
      emit critical(
1 ✔
1046
          tr("Backup commit failed"),
1 ✔
1047
          tr("Could not inspect git status. Re-encryption was aborted."));
1 ✔
1048
    return false;
1 ✔
1049
  }
1050
  // An unresolved conflict needs no merge or rebase in progress: a
1051
  // `git stash pop` that conflicted leaves none of the markers the earlier
1052
  // checks look for. `add -u` would record the work tree, conflict markers
1053
  // and all, as the resolution, and the backup commit would be pushed.
1054
  // The repository-wide status, not `ls-files` (which stops at the store's
1055
  // folder): `add -u` stages a repository above the store as a whole.
1056
  if (listsUnmergedPath(statusOut)) {
26 ✔
1057
    if (!m_reencryptCancel.load())
1 ✔
1058
      emit critical(tr("Unfinished Git operation"),
2 ✔
1059
                    tr("The password store's Git repository has unmerged "
1 ✔
1060
                       "files. Resolve the conflict with Git before "
1061
                       "re-encrypting."));
1062
    return false;
1 ✔
1063
  }
1064
  // The store only: in a repository above it, a modified tracked file
1065
  // outside the store is not the store's to back up, and autoPush would
1066
  // publish it. `.` is the store, as git runs with -C the store.
1067
  QString storeStatus;
25 ✔
1068
  if (execBlocking(git,
225 ✔
1069
                   {"-C", store, "status", "--porcelain",
1070
                    "--untracked-files=no", "--", "."},
1071
                   &storeStatus) != 0) {
1072
    if (!m_reencryptCancel.load())
×
1073
      emit critical(
×
1074
          tr("Backup commit failed"),
×
1075
          tr("Could not inspect git status. Re-encryption was aborted."));
×
1076
    return false;
×
1077
  }
1078
  if (!storeStatus.trimmed().isEmpty()) {
25 ✔
1079
    if (execBlocking(git, {"-C", store, "add", "-u", "--", "."}) != 0 ||
54 ✔
1080
        execBlocking(git, QStringList{"-C", store} + commitArgs() +
54 ✔
1081
                              QStringList{"-m", "Backup before re-encryption",
6 ✔
1082
                                          "--", "."}) != 0) {
66 ✔
1083
      if (!m_reencryptCancel.load())
2 ✔
1084
        emit critical(tr("Backup commit failed"),
4 ✔
1085
                      tr("Re-encryption was aborted because a git backup "
2 ✔
1086
                         "could not be created."));
1087
      return false;
2 ✔
1088
    }
1089
  }
1090
  return true;
1091
}
122 ✔
1092

1093
/**
1094
 * @brief Outcome of one reencryptPath() run; filled on the worker thread
1095
 * and consumed by finishReencrypt() on the owning thread.
1096
 */
1097
struct ImitatePass::ReencryptResult {
194 ✔
1098
  int total = 0;          ///< `.gpg` files found under the directory.
1099
  int checked = 0;        ///< Files whose recipients were inspected.
1100
  int reencrypted = 0;    ///< Files rewritten for the current recipients.
1101
  QStringList failed;     ///< One line per file that could not be
1102
                          ///< re-encrypted: its path, or the reason (which
1103
                          ///< names the path) when there is one to give.
1104
  bool cancelled = false; ///< Stopped early by cancelReencryptPath(); the
1105
                          ///< interrupted file, if any, is not in `failed`.
1106
  bool aborted = false;   ///< Stopped early on an error already reported.
1107
};
1108

1109
namespace {
1110
/// Poll interval while waiting for queued git commands to drain.
1111
constexpr int kReencryptRetryMs = 100;
1112
/// Cap on the file names listed in the aggregated failure dialog.
1113
constexpr int kReencryptMaxListedFailures = 15;
1114
} // namespace
1115

1116
void ImitatePass::reencryptPath(const QString &dir,
1 ✔
1117
                                const AppSettings &settings) {
1118
  if (!m_reencryptActive) {
1 ✔
1119
    init(settings);
1 ✔
1120
    updateEnv();
1 ✔
1121
  }
1122
  reencryptPath(dir);
1 ✔
1123
}
1 ✔
1124

1125
void ImitatePass::reencryptPath(const QString &dir) {
103 ✔
1126
  if (m_reencryptActive) {
103 ✔
1127
    emit statusMsg(tr("A re-encryption is already running"), 3000);
1 ✔
1128
    return;
1 ✔
1129
  }
1130
  // The store root may be a link; a folder inside that is, or lies behind,
1131
  // one is not part of the store. MainWindow refuses it too; this covers
1132
  // Init().
1133
  if (Util::isUnderLink(dir, m_settings.passStore)) {
102 ✔
1134
    emit critical(tr("Not a folder of the store"),
6 ✔
1135
                  tr("%1 is, or lies behind, a symbolic link or junction. What "
2 ✔
1136
                     "that points to is not part of the password store and "
1137
                     "was not re-encrypted.")
1138
                      .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
4 ✔
1139
    emit endReencryptPath();
2 ✔
1140
    return;
2 ✔
1141
  }
1142
  if (refuseUnfinishedGitOperation()) {
100 ✔
1143
    // Re-encrypting now would run createBackupCommit()'s `git add -u` and
1144
    // conclude the stopped merge; refuse before the worker starts.
1145
    emit endReencryptPath();
1 ✔
1146
    return;
1 ✔
1147
  }
1148
  m_reencryptActive = true;
99 ✔
1149
  m_reencryptScope = dir;
99 ✔
1150
  m_reencryptCancel.store(false);
1151
  emit statusMsg(tr("Re-encrypting from folder %1").arg(dir), 3000);
198 ✔
1152
  emit startReencryptPath();
99 ✔
1153
  startReencryptWorker(dir);
99 ✔
1154
}
1155

1156
// The worker's kill() after the grace period is needed: terminate() is only
1157
// SIGTERM, or WM_CLOSE on Windows, which a console gpg ignores.
1158
void ImitatePass::cancelReencryptPath() {
5 ✔
1159
  if (!m_reencryptActive)
5 ✔
1160
    return;
1161
  m_reencryptCancel.store(true);
1162
}
1163

1164
// Init(), Move() and Copy() queue async git commands right before
1165
// reencryptPath(); the worker's blocking git would fight them for the index
1166
// lock, so wait for the queue to drain.
1167
void ImitatePass::startReencryptWorker(const QString &dir) {
100 ✔
1168
  if (m_reencryptCancel.load()) {
100 ✔
1169
    ReencryptResult result;
1 ✔
1170
    result.cancelled = true;
1 ✔
1171
    finishReencrypt(result);
1 ✔
1172
    return;
1173
  }
1174
  if (!exec.isIdle()) {
1175
    QTimer::singleShot(kReencryptRetryMs, this,
2 ✔
1176
                       [this, dir]() { startReencryptWorker(dir); });
5 ✔
1177
    return;
2 ✔
1178
  }
1179
  // Re-check now the queue is idle: a pull queued earlier through the
1180
  // asynchronous GitPull() may have finished during the wait and left a
1181
  // conflict. reencryptPath() checked before scheduling, but that was before
1182
  // such a pull could run; starting the worker now would let its backup commit
1183
  // conclude the stopped operation. The refusal already reported it, so finish
1184
  // as an aborted run (clears m_reencryptActive, emits endReencryptPath).
1185
  if (refuseUnfinishedGitOperation()) {
97 ✔
1186
    ReencryptResult result;
×
1187
    result.aborted = true;
×
1188
    finishReencrypt(result);
×
1189
    return;
1190
  }
1191

1192
  // The worker calls member functions, so `this` must outlive it: the
1193
  // destructor cancels and joins m_reencryptThread. `self` only guards the
1194
  // queued completion, which may run after the thread object is gone.
1195
  QPointer<ImitatePass> self(this);
1196
  // The worker's own copy: env is the owning thread's to change meanwhile.
1197
  updateEnv();
97 ✔
1198
  m_reencryptEnv = storeEnvironment();
97 ✔
1199
  QThread *thread = QThread::create([this, self, dir]() {
194 ✔
1200
    ReencryptResult result = reencryptFiles(dir);
97 ✔
1201
    QMetaObject::invokeMethod(
97 ✔
1202
        self,
1203
        [self, result = std::move(result)]() {
384 ✔
1204
          if (self)
93 ✔
1205
            self->finishReencrypt(result);
93 ✔
1206
        },
93 ✔
1207
        Qt::QueuedConnection);
1208
  });
97 ✔
1209
  m_reencryptThread = thread;
97 ✔
1210
  connect(thread, &QThread::finished, this, [this, thread]() {
97 ✔
1211
    if (m_reencryptThread == thread)
93 ✔
1212
      m_reencryptThread = nullptr;
93 ✔
1213
  });
1214
  connect(thread, &QThread::finished, thread, &QObject::deleteLater);
97 ✔
1215
  thread->start();
97 ✔
1216
}
1217

1218
/**
1219
 * @brief Pull before re-encryption when automatic pulling is configured.
1220
 * @return true if no pull is needed, the pull succeeds, or a failed pull leaves
1221
 * no unmerged files and HEAD not behind its upstream; false otherwise.
1222
 */
1223
auto ImitatePass::pullBeforeReencrypt() -> bool {
97 ✔
1224
  if (!m_settings.autoPull || !reencryptUsesGit()) {
97 ✔
1225
    return true;
89 ✔
1226
  }
1227
  emit statusMsg(tr("Updating password-store"), 2000);
8 ✔
1228
  if (execBlocking(m_settings.gitExecutable,
40 ✔
1229
                   {"-C", pgit(m_settings.passStore), "pull"}) == 0) {
8 ✔
1230
    return true;
1231
  }
1232
  // A pull that could not reach the remote leaves the store as it was; one
1233
  // that stopped in a merge leaves conflict markers and an unmerged index,
1234
  // and re-encrypting on top of that would commit the mess.
1235
  QString unmerged;
3 ✔
1236
  if (execBlocking(m_settings.gitExecutable,
18 ✔
1237
                   {"-C", pgit(m_settings.passStore), "ls-files", "--unmerged"},
1238
                   &unmerged) != 0) {
1239
    // Unknown is not clean: the pull may have stopped in a merge.
1240
    emit critical(tr("Git pull failed"),
×
1241
                  tr("Could not check the store for unmerged files after the "
×
1242
                     "pull. Check it with git before re-encrypting."));
1243
    return false;
×
1244
  }
1245
  if (!unmerged.trimmed().isEmpty()) {
3 ✔
1246
    emit critical(tr("Git pull failed"),
2 ✔
UNCOV
1247
                  tr("The pull left the store with unmerged files. Resolve "
×
1248
                     "the conflict before re-encrypting."));
1249
    return false;
1 ✔
1250
  }
1251
  // A third kind: the fetch got the commits and the checkout then failed at
1252
  // one path (a link git could not create, say). Git leaves HEAD and the
1253
  // index where they were, but the pulled versions of the other files are
1254
  // already in the work tree, and the backup commit would take them as the
1255
  // user's own, signed with the user's key. HEAD still behind the upstream
1256
  // after a failed pull means the pull may have got that far. No upstream
1257
  // (rev-list fails) means there was nothing to merge.
1258
  QString behind;
2 ✔
1259
  if (execBlocking(m_settings.gitExecutable,
14 ✔
1260
                   {"-C", pgit(m_settings.passStore), "rev-list", "--count",
1261
                    "HEAD..@{upstream}"},
1262
                   &behind) == 0 &&
4 ✔
1263
      behind.trimmed().toInt() > 0) {
2 ✔
1264
    emit critical(tr("Git pull failed"),
2 ✔
1265
                  tr("The pull stopped before the store was up to date with "
1 ✔
1266
                     "its remote, and may have left files of the pulled "
1267
                     "commits in it. Check the store with git before "
1268
                     "re-encrypting."));
1269
    return false;
1 ✔
1270
  }
1271
  emit statusMsg(tr("Git pull failed, re-encrypting the store as it is"), 5000);
1 ✔
1272
  return true;
1 ✔
1273
}
13 ✔
1274

1275
auto ImitatePass::entriesToReencrypt(const QString &dir, QStringList *failed)
87 ✔
1276
    -> QStringList {
1277
  // Regular files only: a symlink or junction is not a password entry, and
1278
  // following one would decrypt and rewrite something outside the store.
1279
  QStringList skipped;
87 ✔
1280
  QStringList unlisted;
87 ✔
1281
  const QStringList files = Util::regularFilesUnder(
1282
      dir, QStringList() << "*.gpg", &skipped, false, &unlisted);
261 ✔
1283
  // A folder that cannot be read looked empty, and the run reported success
1284
  // over it with its entries still encrypted to the old recipients (a key
1285
  // just removed among them). Each is a failure: the dialog names it and
1286
  // nothing is pushed.
1287
  for (const QString &folder : std::as_const(unlisted)) {
89 ✔
1288
    *failed << tr("%1 could not be read: its entries were not re-encrypted")
2 ✔
1289
                   .arg(QDir::toNativeSeparators(folder));
4 ✔
1290
  }
1291
  if (!skipped.isEmpty()) {
87 ✔
1292
    emit statusMsg(tr("%n entr(y/ies) skipped: a symlink, junction or special "
2 ✔
1293
                      "file is not part of the store.",
1294
                      "", static_cast<int>(skipped.size())),
1295
                   5000);
1296
  }
1297
  return files;
87 ✔
1298
}
1299

1300
auto ImitatePass::recipientsForDir(const QString &fileName,
67 ✔
1301
                                   QHash<QString, QStringList> &verified,
1302
                                   QStringList &gpgId, ReencryptResult &result)
1303
    -> bool {
1304
  if (!verifyGpgIdForDir(fileName, verified, gpgId)) {
67 ✔
1305
    if (m_reencryptCancel.load()) {
3 ✔
1306
      result.cancelled = true;
×
1307
    } else {
1308
      result.aborted = true;
3 ✔
1309
    }
1310
    return false;
3 ✔
1311
  }
1312
  if (gpgId.isEmpty() && !verified.isEmpty()) {
64 ✔
1313
    emit critical(tr("GPG ID verification failed"),
3 ✔
1314
                  tr("Could not verify .gpg-id for directory."));
1 ✔
1315
    result.aborted = true;
1 ✔
1316
    return false;
1 ✔
1317
  }
1318
  return true;
1319
}
1320

1321
// Worker thread: only blocking helpers, nothing touching `exec` or the
1322
// transaction state; signals reach the GUI queued. A helper failing while the
1323
// cancel flag is set was interrupted: its file is neither checked nor failed.
1324
auto ImitatePass::reencryptFiles(const QString &dir) -> ReencryptResult {
97 ✔
1325
  ReencryptResult result;
97 ✔
1326
  if (!pullBeforeReencrypt()) {
97 ✔
1327
    result.aborted = true;
2 ✔
1328
    return result;
2 ✔
1329
  }
1330
  // The GUI-thread checks ran before this worker's own pull.
1331
  // pullBeforeReencrypt refuses an unmerged index, but a pull that stopped in a
1332
  // rebase can leave a rebase-merge/rebase-apply state with no unmerged entry
1333
  // yet; the backup commit's `git add -u` would then conclude it. Re-check
1334
  // here, before any write, with the non-emitting detection (the refusal is
1335
  // reported once, as an aborted run).
1336
  if (const QString midOp = unfinishedGitOperationReason(); !midOp.isEmpty()) {
95 ✔
1337
    if (!m_reencryptCancel.load()) {
1 ✔
1338
      emit critical(tr("Unfinished Git operation"), midOp);
2 ✔
1339
    }
1340
    result.aborted = true;
1 ✔
1341
    return result;
1342
  }
1343
  // reencryptPath() checked the folder before the pull; a pulled commit can
1344
  // have made it, or a folder above it, a link since. Recovery and the walk
1345
  // below would then rename and remove files beyond the store.
1346
  if (Util::isUnderLink(dir, m_settings.passStore)) {
94 ✔
1347
    emit critical(tr("Not part of the store"),
×
1348
                  tr("%1 is, or lies behind, a symbolic link or junction "
×
1349
                     "after pulling. What that points to is not part of the "
1350
                     "password store and is left alone.")
1351
                      .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
×
1352
    result.aborted = true;
×
1353
    return result;
×
1354
  }
1355

1356
  // Init() wrote the recipients the user ticked and committed them. A pull
1357
  // that merged another change to the same list cleanly (a line removed
1358
  // here, one added there) would have the run encrypt to keys nobody chose
1359
  // in the dialog, and without a signing key nothing else notices.
1360
  if (m_writtenGpgId) {
94 ✔
1361
    const std::optional<QByteArray> now =
1362
        Util::readRegularFile(m_writtenGpgId->file, Util::kMaxGpgIdBytes);
27 ✔
1363
    if (!now || *now != m_writtenGpgId->bytes) {
27 ✔
1364
      if (!m_reencryptCancel.load()) {
1 ✔
1365
        emit critical(
1 ✔
1366
            tr("Recipients changed by the pull"),
1 ✔
1367
            tr("The pull changed the recipients of %1 after you saved "
1 ✔
1368
               "them, so nothing was re-encrypted: entries in it may still "
1369
               "be encrypted to the previous recipients, and anyone you "
1370
               "just removed may still be able to read them. Open the users "
1371
               "dialog for that folder again, check the recipients, and "
1372
               "save.")
1373
                .arg(QDir::toNativeSeparators(
2 ✔
1374
                    QFileInfo(m_writtenGpgId->file).path())));
2 ✔
1375
      }
1376
      result.aborted = true;
1 ✔
1377
      return result;
1378
    }
1379
  }
1380

1381
  // Leftovers of an interrupted run first: a restored entry then goes into
1382
  // the backup commit like everything else, and a stale temporary does not.
1383
  if (!recoverReencryptLeftovers(dir)) {
93 ✔
1384
    result.aborted = true;
3 ✔
1385
    return result;
3 ✔
1386
  }
1387

1388
  if (!createBackupCommit()) {
90 ✔
1389
    if (m_reencryptCancel.load()) {
3 ✔
1390
      result.cancelled = true;
×
1391
    } else {
1392
      result.aborted = true;
3 ✔
1393
    }
1394
    return result;
1395
  }
1396

1397
  const QStringList files = entriesToReencrypt(dir, &result.failed);
87 ✔
1398
  result.total = files.size();
87 ✔
1399
  emit reencryptProgress(0, result.total);
87 ✔
1400

1401
  QString currentDir;
87 ✔
1402
  QHash<QString, QStringList> gpgIdFilesVerified;
87 ✔
1403
  QStringList gpgId;
87 ✔
1404
  for (const QString &fileName : std::as_const(files)) {
177 ✔
1405
    if (m_reencryptCancel.load()) {
100 ✔
1406
      result.cancelled = true;
×
1407
      break;
6 ✔
1408
    }
1409
    const QString fileDir = QFileInfo(fileName).path();
100 ✔
1410
    if (fileDir != currentDir) {
100 ✔
1411
      if (!recipientsForDir(fileName, gpgIdFilesVerified, gpgId, result)) {
67 ✔
1412
        return result;
1413
      }
1414
      currentDir = fileDir;
63 ✔
1415
    }
1416
    if (getKeysFromFile(fileName) != gpgId) {
192 ✔
1417
      QString why;
96 ✔
1418
      if (reencryptSingleFile(fileName, gpgId, &why)) {
96 ✔
1419
        result.reencrypted++;
48 ✔
1420
      } else if (m_reencryptCancel.load()) {
48 ✔
1421
        // Interrupted by the cancel: the file is untouched, not failed.
1422
        result.cancelled = true;
6 ✔
1423
        break;
1424
      } else {
1425
        // The reason names the entry itself when there is one to give.
1426
        result.failed << (why.isEmpty() ? fileName : why);
42 ✔
1427
      }
1428
    }
1429
    result.checked++;
90 ✔
1430
    emit reencryptProgress(result.checked, result.total);
90 ✔
1431
  }
1432
  return result;
1433
}
87 ✔
1434

1435
// No push after a cancel, abort or per-file failure: a partially re-encrypted
1436
// store must not reach the remote before the user inspects it.
1437
void ImitatePass::finishReencrypt(const ReencryptResult &result) {
94 ✔
1438
  if (!result.failed.isEmpty()) {
94 ✔
1439
    QStringList listed = result.failed.mid(0, kReencryptMaxListedFailures);
22 ✔
1440
    const int more = result.failed.size() - listed.size();
22 ✔
1441
    if (more > 0) {
22 ✔
1442
      listed << tr("... and %n more", nullptr, more);
1 ✔
1443
    }
1444
    emit critical(tr("Re-encryption failed"),
66 ✔
1445
                  tr("%n file(s) could not be re-encrypted:", nullptr,
22 ✔
1446
                     result.failed.size()) +
22 ✔
1447
                      "\n\n" + listed.join('\n'));
44 ✔
1448
  }
1449

1450
  // The recipients change is committed already: a run that did not finish
1451
  // leaves entries for the previous recipients, which the next automatic
1452
  // push (after any edit) would publish with it. A clean run releases only
1453
  // the holds of what it covered. Also without Git: a recipients change
1454
  // left uncommitted now is swept into a later commit (the next run's
1455
  // backup commit) once Git is on, and pushed with it.
1456
  if (result.cancelled || result.aborted || !result.failed.isEmpty()) {
94 ✔
1457
    holdAutoPush(m_reencryptScope);
39 ✔
1458
  } else {
1459
    releaseAutoPush(m_reencryptScope);
55 ✔
1460
  }
1461

1462
  if (result.cancelled) {
94 ✔
1463
    emit statusMsg(tr("Re-encryption cancelled: %1 of %2 files checked, "
8 ✔
1464
                      "%3 re-encrypted, %4 failed")
1465
                       .arg(result.checked)
4 ✔
1466
                       .arg(result.total)
4 ✔
1467
                       .arg(result.reencrypted)
4 ✔
1468
                       .arg(result.failed.size()),
12 ✔
1469
                   5000);
1470
  } else if (!result.aborted) {
90 ✔
1471
    if (!result.failed.isEmpty()) {
76 ✔
1472
      emit statusMsg(tr("Re-encryption completed: %1 succeeded, %2 failed")
42 ✔
1473
                         .arg(result.reencrypted)
21 ✔
1474
                         .arg(result.failed.size()),
63 ✔
1475
                     5000);
1476
    } else {
1477
      emit statusMsg(tr("Re-encryption completed: %1 files re-encrypted")
55 ✔
1478
                         .arg(result.reencrypted),
110 ✔
1479
                     3000);
1480
    }
1481
    if ((m_settings.autoPush || m_pushAfterReencrypt) && reencryptUsesGit()) {
76 ✔
1482
      if (result.failed.isEmpty() && autoPushHeld()) {
11 ✔
1483
        // Clean here, but another folder's run did not finish.
1484
        emit statusMsg(tr("Not pushing: an earlier re-encryption in this "
2 ✔
1485
                          "store did not finish"),
1486
                       5000);
1487
      } else if (result.failed.isEmpty()) {
10 ✔
1488
        emit statusMsg(tr("Updating password-store"), 2000);
5 ✔
1489
        m_reencryptPushing = true;
5 ✔
1490
        GitPush();
5 ✔
1491
        m_reencryptPushing = false;
5 ✔
1492
      } else {
1493
        emit statusMsg(tr("Not pushing: %n file(s) failed to re-encrypt",
10 ✔
1494
                          nullptr, result.failed.size()),
1495
                       5000);
1496
      }
1497
    }
1498
  }
1499
  if (m_uncommittedGpgId) {
94 ✔
1500
    const UncommittedGpgId uncommitted = *m_uncommittedGpgId;
3 ✔
1501
    m_uncommittedGpgId.reset();
1502
    reportUncommittedGpgId(uncommitted.folder, uncommitted.gitError,
3 ✔
1503
                           !result.cancelled && !result.aborted &&
3 ✔
1504
                               result.failed.isEmpty());
1505
  }
1506
  m_writtenGpgId.reset();
1507
  m_pushAfterReencrypt = false;
94 ✔
1508
  m_reencryptActive = false;
94 ✔
1509
  emit endReencryptPath();
94 ✔
1510
}
94 ✔
1511

1512
auto ImitatePass::reencryptUsesGit() const -> bool {
168 ✔
1513
  return gitConfigured() && !m_uncommittedGpgId;
168 ✔
1514
}
1515

1516
void ImitatePass::reencryptWithoutGit(const QString &dir,
3 ✔
1517
                                      const QString &gitError) {
1518
  if (m_reencryptActive) {
3 ✔
1519
    // The run in flight was started with its own Git mode; this folder is
1520
    // not part of it.
1521
    reportUncommittedGpgId(dir, gitError, false);
×
1522
    return;
×
1523
  }
1524
  m_uncommittedGpgId = UncommittedGpgId{dir, gitError};
3 ✔
1525
  reencryptPath(dir);
3 ✔
1526
  if (m_uncommittedGpgId && !m_reencryptActive) {
3 ✔
1527
    // Refused before it started; reencryptPath() said why.
1528
    m_uncommittedGpgId.reset();
1529
    reportUncommittedGpgId(dir, gitError, false);
×
1530
  }
1531
}
1532

1533
void ImitatePass::reportUncommittedGpgId(const QString &dir,
3 ✔
1534
                                         const QString &gitError,
1535
                                         bool reencrypted) {
1536
  const QString folder = QDir::toNativeSeparators(QDir::cleanPath(dir));
3 ✔
1537
  if (reencrypted) {
3 ✔
1538
    emit critical(
4 ✔
1539
        tr("Recipients not committed"),
2 ✔
1540
        tr("The recipients of %1 were changed and its entries were "
2 ✔
1541
           "re-encrypted to them, but the Git commit failed:\n\n%2\n\n"
1542
           "The change is not committed or pushed yet. Fix the Git problem, "
1543
           "then commit the changes, or save the recipients again.")
1544
            .arg(folder, gitError));
4 ✔
1545
    return;
1546
  }
1547
  emit critical(
2 ✔
1548
      tr("Recipients not committed"),
1 ✔
1549
      tr("The recipients of %1 were changed, but the Git commit "
1 ✔
1550
         "failed:\n\n%2\n\nRe-encryption did not complete, so some or all "
1551
         "entries are still encrypted to the previous recipients, who can "
1552
         "still read them. Nothing was committed or pushed. Fix the Git "
1553
         "problem, then save the recipients again.")
1554
          .arg(folder, gitError));
2 ✔
1555
}
1556

1557
auto ImitatePass::resolveMoveDestination(const QString &src,
34 ✔
1558
                                         const QString &dest, bool force)
1559
    -> QString {
1560
  QFileInfo srcFileInfo(src);
34 ✔
1561
  QFileInfo destFileInfo(dest);
34 ✔
1562
  QString destFile;
34 ✔
1563
  QString srcFileBaseName = srcFileInfo.fileName();
34 ✔
1564

1565
  if (srcFileInfo.isFile()) {
34 ✔
1566
    if (destFileInfo.isFile()) {
29 ✔
1567
      if (!force) {
11 ✔
1568
        qCDebug(lcQtPass) << "Destination file already exists";
4 ✔
1569
        return {};
4 ✔
1570
      }
1571
      destFile = dest;
7 ✔
1572
    } else if (destFileInfo.isDir()) {
18 ✔
1573
      destFile = QDir(dest).filePath(srcFileBaseName);
12 ✔
1574
    } else {
1575
      destFile = dest;
12 ✔
1576
    }
1577

1578
    // Case-sensitive: only an actual ".gpg" entry already carries the suffix.
1579
    // A neighbouring file like "login.GPG" is a different name, so it must not
1580
    // be chopped to "login" and re-suffixed to the real "login.gpg" entry,
1581
    // which the forced move would then overwrite.
1582
    if (destFile.endsWith(QLatin1String(".gpg"))) {
25 ✔
1583
      destFile.chop(4);
22 ✔
1584
    }
1585
    destFile.append(".gpg");
25 ✔
1586
  } else if (srcFileInfo.isDir()) {
5 ✔
1587
    if (destFileInfo.isDir()) {
4 ✔
1588
      destFile = QDir(dest).filePath(srcFileBaseName);
2 ✔
1589
    } else if (destFileInfo.isFile()) {
3 ✔
1590
      qCDebug(lcQtPass) << "Destination is a file";
1 ✔
1591
      return {};
1 ✔
1592
    } else {
1593
      destFile = dest;
2 ✔
1594
    }
1595
  } else {
1596
    qCDebug(lcQtPass) << "Source file does not exist";
1 ✔
1597
    return {};
1 ✔
1598
  }
1599
  return destFile;
1600
}
34 ✔
1601

1602
void ImitatePass::executeMoveGit(const QString &src, const QString &destFile,
3 ✔
1603
                                 bool force) {
1604
  QStringList args;
3 ✔
1605
  args << "mv";
3 ✔
1606
  if (force) {
3 ✔
1607
    args << "-f";
2 ✔
1608
  }
1609
  args << "--" << pgit(src) << pgit(destFile);
12 ✔
1610
  executeGit(GIT_MOVE, args);
3 ✔
1611

1612
  // The move alone: with no path, the commit took whatever else was
1613
  // staged.
1614
  gitCommit(QStringList{src, destFile},
12 ✔
1615
            QString("Moved for %1 to %2 using QtPass.")
3 ✔
1616
                .arg(commitName(src), commitName(destFile)));
6 ✔
1617
}
3 ✔
1618

1619
auto ImitatePass::commitName(const QString &path) const -> QString {
56 ✔
1620
  QString name = QDir(m_settings.passStore).relativeFilePath(path);
56 ✔
1621
  // Not under the store as spelled (a copy from elsewhere, the store's
1622
  // other spelling through a link, another drive): "../.." or an absolute
1623
  // path would carry the local layout too, so the file name alone.
1624
  if (name == QLatin1String("..") || name.startsWith(QLatin1String("../")) ||
111 ✔
1625
      QDir::isAbsolutePath(name)) {
1626
    name = QFileInfo(path).fileName();
2 ✔
1627
  }
1628
  name.replace(Util::endsWithGpg(), "");
56 ✔
1629
  return name;
56 ✔
1630
}
1631

1632
void ImitatePass::Move(const QString src, const QString dest,
17 ✔
1633
                       const bool force) {
1634
  if (refuseLinkedPath(src) || refuseLinkedPath(dest)) {
17 ✔
1635
    return;
4 ✔
1636
  }
1637
  if (refuseUnfinishedGitOperation() || refusePendingPull()) {
15 ✔
1638
    return;
×
1639
  }
1640
  TransactionHelper trans(&m_transaction, PASS_MOVE);
15 ✔
1641
  QString destFile = resolveMoveDestination(src, dest, force);
15 ✔
1642
  if (destFile.isEmpty()) {
15 ✔
1643
    return;
1644
  }
1645
  if (refuseLinkedPath(destFile)) {
13 ✔
1646
    return;
1647
  }
1648

1649
  qCDebug(lcQtPass) << "Move Source: " << src;
13 ✔
1650
  qCDebug(lcQtPass) << "Move Destination: " << destFile;
13 ✔
1651

1652
  if (gitReady()) {
13 ✔
1653
    executeMoveGit(src, destFile, force);
3 ✔
1654
  } else {
1655
    // A forced move replaces the destination entry in the one rename, as
1656
    // git mv -f does: removing it first lost it when the rename then failed
1657
    // (and lost the entry itself, moved onto its own name). A folder is never
1658
    // replaced, forced or not. Without Git nothing else reports a failure.
1659
    const bool moved = force && QFileInfo(src).isFile()
6 ✔
1660
                           ? Util::replaceFile(src, destFile, true)
13 ✔
1661
                           : QDir().rename(src, destFile);
17 ✔
1662
    if (!moved) {
10 ✔
1663
      emit critical(tr("Move failed"),
4 ✔
1664
                    tr("Could not move %1 to %2.").arg(src, destFile));
4 ✔
1665
    }
1666
  }
1667
}
1668

1669
auto ImitatePass::copyDestination(const QString &src, const QString &dest,
13 ✔
1670
                                  bool force) -> QString {
1671
  const auto refuse = [this, &src](const QString &to) {
4 ✔
1672
    emit critical(tr("Copy failed"),
12 ✔
1673
                  tr("Could not copy %1 to %2.").arg(src, to));
4 ✔
1674
    return QString();
4 ✔
1675
  };
13 ✔
1676
  // Like `pass cp`, dest may be an existing folder (a drag-and-drop copy hands
1677
  // over the folder, not the new file name). Resolve the real target the same
1678
  // way Move does: into the folder, .gpg appended, no clobbering without force.
1679
  const QString destFile = resolveMoveDestination(src, dest, force);
13 ✔
1680
  if (destFile.isEmpty()) {
13 ✔
1681
    return refuse(dest);
2 ✔
1682
  }
1683
  // A link planted under that name (dangling ones pass exists()) is not an
1684
  // entry to write.
1685
  if (refuseLinkedPath(destFile)) {
11 ✔
1686
    return {};
1 ✔
1687
  }
1688
  const QFileInfo destFileInfo(destFile);
10 ✔
1689
  // A folder destination that is the source's own folder resolves to the
1690
  // source itself; with force that would replace the only copy with itself.
1691
  // And resolveMoveDestination only sees a clash when dest names the file.
1692
  if (QFileInfo(src) == destFileInfo || (!force && destFileInfo.exists())) {
30 ✔
1693
    return refuse(destFile);
2 ✔
1694
  }
1695
  return destFile;
1696
}
10 ✔
1697

1698
void ImitatePass::Copy(const QString src, const QString dest,
15 ✔
1699
                       const bool force) {
1700
  // QFile::copy reads through a link: the target's bytes would become an
1701
  // entry of the store.
1702
  if (refuseLinkedPath(src) || refuseLinkedPath(dest)) {
15 ✔
1703
    return;
8 ✔
1704
  }
1705
  if (refuseUnfinishedGitOperation() || refusePendingPull()) {
13 ✔
1706
    return;
×
1707
  }
1708
  TransactionHelper trans(&m_transaction, PASS_COPY);
13 ✔
1709
  const QString destFile = copyDestination(src, dest, force);
13 ✔
1710
  if (destFile.isEmpty()) {
13 ✔
1711
    return;
1712
  }
1713
  // git has no "cp": copy on disk in both modes, then stage. Synchronous and
1714
  // atomic (Util::copyFileReplacing follows no link), so it exists before the
1715
  // re-encryption below and a forced overwrite survives a half-way failure;
1716
  // without force nothing is replaced, not even what appeared since the check.
1717
  QString why;
8 ✔
1718
  if (!Util::copyFileReplacing(src, destFile, force, &why)) {
8 ✔
1719
    emit critical(tr("Copy failed"),
2 ✔
1720
                  tr("Could not copy %1 to %2.").arg(src, destFile) + "\n" +
2 ✔
1721
                      why);
1 ✔
1722
    return;
1723
  }
1724
  if (gitReady()) {
7 ✔
1725
    executeGit(GIT_COPY, {"add", "--", pgit(destFile)});
5 ✔
1726
    gitCommit(destFile, QString("Copied from %1 to %2 using QtPass.")
2 ✔
1727
                            .arg(commitName(src), commitName(destFile)));
2 ✔
1728
  }
1729
  const QFileInfo written(destFile);
7 ✔
1730
  if (written.isDir()) {
7 ✔
1731
    reencryptPath(written.absoluteFilePath());
×
1732
  } else if (written.isFile()) {
7 ✔
1733
    reencryptPath(written.dir().path());
14 ✔
1734
  }
1735
}
8 ✔
1736

1737
void ImitatePass::executeGpg(PROCESS id, const QStringList &args, QString input,
134 ✔
1738
                             bool readStdout, bool readStderr) {
1739
  executeWrapper(id, m_settings.gpgExecutable, args, std::move(input),
134 ✔
1740
                 readStdout, readStderr);
1741
}
134 ✔
1742

1743
// useGit can be on with no gitExecutable (fresh setup, git removed later);
1744
// handing that to the Executor used to wedge the queue (#1682).
1745
auto ImitatePass::gitConfigured() const -> bool {
168 ✔
1746
  return m_settings.useGit && !m_settings.gitExecutable.isEmpty();
168 ✔
1747
}
1748

1749
// Tells the user once per operation why git was skipped, so the store
1750
// silently drifting from git does not go unnoticed.
1751
auto ImitatePass::gitReady() -> bool {
157 ✔
1752
  if (m_settings.useGit && m_settings.gitExecutable.isEmpty()) {
157 ✔
1753
    emit statusMsg(tr("Git executable not configured, skipping git"), 3000);
8 ✔
1754
    return false;
8 ✔
1755
  }
1756
  return m_settings.useGit;
1757
}
1758

1759
void ImitatePass::executeGit(PROCESS id, const QStringList &args, QString input,
45 ✔
1760
                             bool readStdout, bool readStderr) {
1761
  // Callers check gitReady() first; an empty executable that still gets here
1762
  // is reported by the Executor instead of wedging the queue (#1682).
1763
  executeWrapper(id, m_settings.gitExecutable, args, std::move(input),
45 ✔
1764
                 readStdout, readStderr);
1765
}
45 ✔
1766

1767
// Only PASS_* processes reach Pass::finished, so to the interface this looks
1768
// the same as RealPass.
1769
void ImitatePass::finished(int id, int exitCode, const QString &out,
175 ✔
1770
                           const QString &err) {
1771
  qCDebug(lcQtPass) << "Imitate Pass";
175 ✔
1772
  QString error = err;
1773
  if (id == PASS_INSERT && !m_pendingInserts.isEmpty()) {
175 ✔
1774
    // Insert()'s gpg step: place the ciphertext before the queued git steps
1775
    // run (the executor starts the next item only after this returns). On
1776
    // failure it fails like a gpg error: git steps cancelled below.
1777
    // No dialog here: it would spin the event loop and run git steps first.
1778
    const PendingInsert pending = m_pendingInserts.dequeue();
1779
    // The flag answers for this insert, the one whose gpg step just ended, not
1780
    // for whichever Insert() was called last: with two inserts queued, a gpg
1781
    // failure of the second must report written=false even though the first
1782
    // was placed. Cleared here, before placement, and set only on success.
1783
    m_insertPlaced = false;
64 ✔
1784
    if (exitCode == 0) {
64 ✔
1785
      // Insert() checked the repository when the save was requested, but a
1786
      // pull queued before it (the asynchronous Update button) may have run
1787
      // and stopped in a conflict while this gpg step encrypted. Placing the
1788
      // entry and committing it now would land it in the unfinished operation,
1789
      // where `git rebase --abort` would drop it. Re-check and, if so, fail the
1790
      // save instead of placing it; the queued git steps are cancelled below.
1791
      const QString midOp = unfinishedGitOperationReason();
62 ✔
1792
      if (!midOp.isEmpty()) {
62 ✔
1793
        error = midOp;
1 ✔
1794
        exitCode = 1;
1795
      } else {
1796
        m_insertPlaced = placeEncryptedFile(pending.output, pending.file,
122 ✔
1797
                                            pending.overwrite, &error);
61 ✔
1798
        if (!m_insertPlaced) {
61 ✔
1799
          exitCode = 1;
1800
        }
1801
      }
1802
    }
1803
  }
64 ✔
1804
  PROCESS pid = m_transaction.transactionIsOver(static_cast<PROCESS>(id));
175 ✔
1805
  m_transactionOutput.append(out);
175 ✔
1806

1807
  if (exitCode == 0) {
175 ✔
1808
    if (pid == INVALID) {
137 ✔
1809
      return;
1810
    }
1811
  } else {
1812
    while (pid == INVALID) {
43 ✔
1813
      id = exec.cancelNext();
5 ✔
1814
      if (id == -1) {
5 ✔
1815
        //  this is probably irrecoverable and shall not happen
1816
        qCDebug(lcQtPass) << "No such transaction!";
×
1817
        return;
×
1818
      }
1819
      pid = m_transaction.transactionIsOver(static_cast<PROCESS>(id));
5 ✔
1820
    }
1821
  }
1822
  Pass::finished(pid, exitCode, m_transactionOutput, error);
164 ✔
1823
  m_transactionOutput.clear();
164 ✔
1824
}
1825

1826
auto ImitatePass::placeEncryptedFile(const QString &output, const QString &file,
118 ✔
1827
                                     bool overwrite, QString *error) -> bool {
1828
  if (QFileInfo(output).size() <= 0) {
118 ✔
1829
    // gpg reported success and wrote nothing: not an entry.
1830
    *error = tr("gpg wrote no ciphertext for %1.").arg(file);
4 ✔
1831
    return false;
2 ✔
1832
  }
1833
  // A link planted since the check is replaced as an entry; without
1834
  // overwrite, anything new under the name fails the add.
1835
  return Util::copyFileReplacing(output, file, overwrite, error);
116 ✔
1836
}
1837

1838
void ImitatePass::beforeExecute(PROCESS id) {
183 ✔
1839
  m_transaction.transactionAdd(id);
183 ✔
1840
}
183 ✔
1841

1842
// PCRE, as for RealPass (see Pass::Grep). Runs on a NativeGrep thread; the
1843
// result arrives on this thread as finishedGrep.
1844
void ImitatePass::Grep(QString pattern, bool caseInsensitive) {
14 ✔
1845
  m_grep.search(pattern, caseInsensitive, m_settings.gpgExecutable,
28 ✔
1846
                m_settings.passStore, exec.environment());
14 ✔
1847
}
14 ✔
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