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

IJHack / QtPass / 44310498951

18 Nov 2026 01:07PM UTC coverage: 95.055% (-1.3%) from 96.31%
44310498951

Pull #2262

github

web-flow
Merge d0ee05222 into 4e6499c0e
Pull Request #2262: pass backend: refuse unrecorded changes, report unrecorded entries

52 of 182 new or added lines in 1 file covered. (28.57%)

9208 of 9687 relevant lines covered (95.06%)

1263.77 hits per line

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

72.67
/src/realpass.cpp
1
// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
/**
4
 * @file
5
 * @brief Implements RealPass: builds the `pass` command lines and does itself
6
 * the few things `pass` must not be trusted with, such as removing a linked
7
 * folder without following it.
8
 */
9
#include "realpass.h"
10
#include "executor.h"
11
#include "gpgidsigner.h"
12
#include "pathvalidator.h"
13
#include "qtpasslogging.h"
14
#include "util.h"
15

16
#include <QCoreApplication>
17
#include <QCryptographicHash>
18
#include <QDir>
19
#include <QFile>
20
#include <QFileInfo>
21
#include <QMap>
22
#include <QProcess>
23
#include <QRegularExpression>
24
#include <algorithm>
25
#include <utility>
26

27
using Enums::GIT_COMMIT;
28
using Enums::GIT_INIT;
29
using Enums::GIT_PULL;
30
using Enums::GIT_PUSH;
31
using Enums::PASS_COPY;
32
using Enums::PASS_INIT;
33
using Enums::PASS_INSERT;
34
using Enums::PASS_MOVE;
35
using Enums::PASS_REMOVE;
36
using Enums::PASS_SHOW;
37

38
RealPass::RealPass() : m_grep(this) {
37 ✔
39
  connect(&m_grep, &NativeGrep::finished, this, &RealPass::finishedGrep);
37 ✔
40
  connect(&exec, &Executor::dequeuing, this, &RealPass::onDequeuing);
37 ✔
41
}
37 ✔
42

43
RealPass::~RealPass() { m_grep.cancel(); }
94 ✔
44

45
void RealPass::GitInit() { executePass(GIT_INIT, {"git", "init"}); }
6 ✔
46

47
void RealPass::GitPull_b() {
2 ✔
48
  // In the store's environment, as every queued pass call: pass picks its
49
  // store from PASSWORD_STORE_DIR alone, so without it the pull before an
50
  // edit went to ~/.password-store instead of the configured store.
51
  QProcess process;
2 ✔
52
  process.setProcessEnvironment(storeEnvironment());
2 ✔
53
  QString err;
2 ✔
54
  const int result =
55
      Executor::executeBlocking(process, m_settings.passExecutable,
12 ✔
56
                                {"git", "pull"}, QString(), nullptr, &err);
2 ✔
57
  if (result != 0) {
2 ✔
58
    qCDebug(lcQtPass) << "Git pull failed with code:" << result;
2 ✔
59
    // As the native backend does: the entry about to be edited is not up to
60
    // date with the remote.
61
    emit statusMsg(tr("Git pull failed: %1").arg(err.trimmed()), 5000);
2 ✔
62
  }
63
}
2 ✔
64

65
void RealPass::GitPull() { executePass(GIT_PULL, {"git", "pull"}); }
12 ✔
66

67
void RealPass::GitPush() {
5 ✔
68
  // Queued behind an init, move or copy, the push would run before its
69
  // outcome is known and send its commit even when the re-encryption then
70
  // fails (the hold is set only then): it waits for them.
71
  if (!m_reencryptScopes.isEmpty() || !m_reencryptPending.isEmpty()) {
5 ✔
72
    m_pushAfterReencrypt = true;
4 ✔
73
    m_deferredPushByHand = m_deferredPushByHand || !pushIsAutomatic();
4 ✔
74
    return;
4 ✔
75
  }
76
  executePass(GIT_PUSH, {"git", "push"});
6 ✔
77
}
78

79
void RealPass::sendDeferredPush() {
38 ✔
80
  if (!m_pushAfterReencrypt || !m_reencryptScopes.isEmpty() ||
38 ✔
81
      !m_reencryptPending.isEmpty()) {
82
    return;
83
  }
84
  const bool byHand = m_deferredPushByHand;
4 ✔
85
  m_pushAfterReencrypt = false;
4 ✔
86
  m_deferredPushByHand = false;
4 ✔
87
  if (!byHand && autoPushHeld()) {
4 ✔
88
    emit statusMsg(tr("Not pushing: an earlier re-encryption in this "
2 ✔
89
                      "store did not finish"),
90
                   5000);
91
    return;
2 ✔
92
  }
93
  executePass(GIT_PUSH, {"git", "push"});
12 ✔
94
}
95

96
void RealPass::Show(QString file) {
5 ✔
97
  // pass follows links as readily as gpg does.
98
  if (refuseLinkedPath(file + ".gpg")) {
10 ✔
99
    return;
100
  }
101
  queueShow(file);
102
  executePass(PASS_SHOW, {"show", file}, "", true);
15 ✔
103
}
3 ✔
104

105
auto RealPass::listSigner() -> GpgIdSigner {
85 ✔
106
  return {m_settings.gpgExecutable,
107
          GpgIdSigner::keysFromSetting(m_settings.passSigningKey),
170 ✔
108
          [this](const QString &app, const QStringList &args,
85 ✔
109
                 const QString &input, QString *out, QString *err) {
110
            QProcess gpg;
25 ✔
111
            gpg.setProcessEnvironment(exec.environment());
25 ✔
112
            return Executor::executeBlocking(gpg, app, args, input, out, err);
50 ✔
113
          }};
195 ✔
114
}
115

116
auto RealPass::refuseList(const QString &file, const GpgIdSigner &signer,
34 ✔
117
                          QSet<QString> &verified, const QString &within,
118
                          const QString &except) -> bool {
119
  if (refuseSkippedGpgId(file, true, except)) {
34 ✔
120
    return true;
121
  }
122
  const QString gpgIdFile = Pass::getGpgIdPath(file, m_settings.passStore);
33 ✔
123
  const QString absolute =
124
      QDir::cleanPath(QFileInfo(gpgIdFile).absoluteFilePath());
66 ✔
125
  if (verified.contains(gpgIdFile) ||
32 ✔
126
      (!except.isEmpty() &&
7 ✔
127
       absolute == QDir::cleanPath(QFileInfo(except).absoluteFilePath())) ||
118 ✔
128
      (!within.isEmpty() && !absolute.startsWith(within))) {
14 ✔
129
    return false;
130
  }
131
  QString why =
132
      QCoreApplication::translate("ImitatePass", "Signature for %1 is invalid.")
25 ✔
133
          .arg(gpgIdFile);
25 ✔
134
  QByteArray contents;
25 ✔
135
  if (!verifySignedList(signer, gpgIdFile, &contents, &why)) {
25 ✔
136
    emit critical(QCoreApplication::translate("ImitatePass",
11 ✔
137
                                              "Check .gpg-id file signature!"),
138
                  why);
139
    return true;
11 ✔
140
  }
141
  verified.insert(gpgIdFile);
14 ✔
142
  return false;
14 ✔
143
}
144

145
auto RealPass::refuseUnverifiedList(const QString &file) -> bool {
34 ✔
146
  // pass verifies the signature itself, but knows nothing of the generation
147
  // and folder lines: an older authentic list put back, or one signed for
148
  // another folder, would get the secret (#2077). The same checks as the
149
  // native backend, with gpg in the store's environment. pass reads the list
150
  // again afterwards; a swap in between is a concurrent writer, out of
151
  // scope (SECURITY.md).
152
  const GpgIdSigner signer = listSigner();
34 ✔
153
  if (!signer.enabled()) {
34 ✔
154
    return false;
155
  }
156
  QSet<QString> verified;
157
  return refuseList(file, signer, verified);
26 ✔
158
}
34 ✔
159

160
namespace {
161
/// @p dir and every folder under it as pass's reencrypt_path() walks them
162
/// (find without -L): hidden ones included, .git left out, no link
163
/// followed. Each entry pass re-encrypts lies in one of them, and its list
164
/// is that folder's nearest. A folder holding a name Qt cannot read
165
/// (Util::hasUnreadableName()) goes to @p unreadable instead of being
166
/// walked: find sees what Qt leaves out, a folder with its own list
167
/// included.
168
auto passFoldersUnder(const QString &dir, QStringList &unreadable)
22 ✔
169
    -> QStringList {
170
  QStringList folders{QDir::cleanPath(dir)};
44 ✔
171
  if (Util::hasUnreadableName(dir)) {
22 ✔
172
    unreadable << QDir::cleanPath(dir);
1 ✔
173
    return folders;
1 ✔
174
  }
175
  const QFileInfoList children = QDir(dir).entryInfoList(
42 ✔
176
      QDir::Dirs | QDir::Hidden | QDir::System | QDir::NoDotAndDotDot);
21 ✔
177
  for (const QFileInfo &child : children) {
28 ✔
178
    if (child.isSymLink() || child.isJunction() ||
7 ✔
179
        child.fileName() == QLatin1String(".git")) {
14 ✔
180
      continue;
×
181
    }
182
    folders << passFoldersUnder(child.absoluteFilePath(), unreadable);
14 ✔
183
  }
184
  return folders;
185
}
22 ✔
186
} // namespace
187

188
auto RealPass::refuseUnverifiedTree(const QString &dir, bool onlyListsWithin,
51 ✔
189
                                    const QString &except) -> bool {
190
  const GpgIdSigner signer = listSigner();
51 ✔
191
  if (!signer.enabled()) {
51 ✔
192
    return false;
193
  }
194
  // One gpg call per list, before pass runs: a store with many lists makes
195
  // that a noticeable pause, so say what it is.
196
  emit statusMsg(tr("Checking the recipient lists under %1…")
30 ✔
197
                     .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))),
30 ✔
198
                 3000);
199
  // pass mv and cp re-encrypt every entry of the folder they write to, each
200
  // to its nearest list, walking as passFoldersUnder() does. For the folder
201
  // that moves, the lists inside it go along: checked where they lie now
202
  // (after the move their folder line names the old place until the
203
  // recipients are saved there again), while a list above it is replaced
204
  // by the destination's, which the caller checks. For entries already in
205
  // the destination, their lists stay where they are: all of them count.
206
  // Absolute, as getGpgIdPath() hands lists back: a relative or other
207
  // spelling would match nothing and check nothing.
208
  const QString within =
209
      onlyListsWithin ? QDir::cleanPath(QFileInfo(dir).absoluteFilePath()) +
52 ✔
210
                            QLatin1Char('/')
211
                      : QString();
41 ✔
212
  QSet<QString> verified;
213
  // Every folder's list counts, also where no entry uses it yet: cp -r
214
  // merges an incoming folder into one of the same name, so the entries it
215
  // brings get a list already there, and a list it brings replaces the one
216
  // there for the entries already in it.
217
  QStringList unreadable;
15 ✔
218
  const QStringList folders = passFoldersUnder(dir, unreadable);
15 ✔
219
  if (!unreadable.isEmpty()) {
15 ✔
220
    const QString title = tr("Cannot check the recipient lists");
221
    //: %1 is a folder. "UTF-8" is the text encoding; keep it as is.
222
    const QString text =
223
        tr("%1 holds a file or folder whose name is not valid UTF-8. QtPass "
×
224
           "cannot see what is behind that name, while pass would re-encrypt "
225
           "it, so nothing was changed. Rename it, then try again.")
226
            .arg(QDir::toNativeSeparators(unreadable.first()));
2 ✔
227
    emit critical(title, text);
1 ✔
228
    return true;
229
  }
230
  for (const QString &folder : folders) {
27 ✔
231
    if (refuseList(folder, signer, verified, within, except)) {
21 ✔
232
      return true;
233
    }
234
  }
235
  return false;
236
}
51 ✔
237

238
auto RealPass::storeGit(const QStringList &args, QString *out) -> bool {
7 ✔
239
  if (!m_settings.useGit) {
7 ✔
240
    return false;
241
  }
242
  // `pass git` runs git in the store with PASSWORD_STORE_DIR set, as the
243
  // store's other quick lookups do; its exit code is git's own.
244
  QString err;
7 ✔
245
  return Executor::executeBlocking(
7 ✔
246
             exec.environment(), m_settings.passExecutable,
14 ✔
247
             QStringList{QStringLiteral("git")} + args, out, &err) == 0;
28 ✔
248
}
249

250
namespace {
251
/**
252
 * @brief @p args for `pass git`, run in @p repository.
253
 * @param repository A folder relative to the store; empty for the store.
254
 * @param args The git arguments.
255
 * @return `-C <repository>` and @p args.
256
 */
NEW
257
auto inRepository(const QString &repository, const QStringList &args)
×
258
    -> QStringList {
NEW
259
  if (repository.isEmpty()) {
×
260
    return args;
261
  }
NEW
262
  return QStringList{QStringLiteral("-C"), repository} + args;
×
263
}
264
} // namespace
265

266
auto RealPass::repositoryOf(const QString &path) -> QString {
134 ✔
267
  if (!m_settings.useGit) {
134 ✔
268
    return {};
134 ✔
269
  }
NEW
270
  const QString root = QDir::cleanPath(m_settings.passStore);
×
271
  // From the nearest folder that exists, as pass looks for it.
NEW
272
  QString folder = QDir::cleanPath(path);
×
NEW
273
  while (!QFileInfo(folder).isDir() &&
×
NEW
274
         folder.startsWith(root + QLatin1Char('/'))) {
×
NEW
275
    folder = QFileInfo(folder).path();
×
276
  }
NEW
277
  const QString relative = QDir(root).relativeFilePath(folder);
×
NEW
278
  if (relative == QLatin1String(".") || relative == QLatin1String("..") ||
×
NEW
279
      relative.startsWith(QLatin1String("../"))) {
×
NEW
280
    return {};
×
281
  }
282
  // The folder's place in its repository ("team/" in the store's own,
283
  // "" at the top of the one it holds itself).
NEW
284
  QString prefix;
×
NEW
285
  storeGit({QStringLiteral("-C"), relative, QStringLiteral("rev-parse"),
×
NEW
286
            QStringLiteral("--show-prefix")},
×
287
           &prefix);
NEW
288
  if (prefix.endsWith(QLatin1Char('\n'))) {
×
NEW
289
    prefix.chop(1);
×
290
  }
NEW
291
  const QString withSlash = relative + QLatin1Char('/');
×
NEW
292
  if (!withSlash.endsWith(prefix)) {
×
NEW
293
    return {};
×
294
  }
295
  QString repository = withSlash.chopped(prefix.size());
NEW
296
  if (repository.endsWith(QLatin1Char('/'))) {
×
NEW
297
    repository.chop(1);
×
298
  }
299
  return repository;
300
}
301

302
auto RealPass::statusEntries(const QStringList &args, const QString &repository)
122 ✔
303
    -> QStringList {
304
  if (!m_settings.useGit) {
122 ✔
305
    return {};
122 ✔
306
  }
NEW
307
  QString out;
×
308
  // -z: names as they are, not quoted when they hold a non-ASCII letter.
309
  // `pass git` exits 0 whatever git did: the output decides, and a git
310
  // that cannot say (no repository) prints nothing to it.
NEW
311
  storeGit(inRepository(repository, QStringList{QStringLiteral("status"),
×
NEW
312
                                                QStringLiteral("--porcelain"),
×
NEW
313
                                                QStringLiteral("-z")} +
×
NEW
314
                                        args),
×
315
           &out);
316
  const QString place =
NEW
317
      repository.isEmpty() ? QString() : repository + QLatin1Char('/');
×
NEW
318
  QStringList entries;
×
NEW
319
  const QStringList fields = out.split(QChar(0), Qt::SkipEmptyParts);
×
NEW
320
  for (qsizetype i = 0; i < fields.size(); ++i) {
×
321
    const QString &field = fields.at(i);
NEW
322
    if (field.size() < 4 || field.at(2) != QLatin1Char(' ')) {
×
NEW
323
      continue;
×
324
    }
NEW
325
    entries << field.left(3) + place + field.mid(3);
×
326
    // A rename or copy, in the index or in the work tree (an intent-to-add
327
    // file), is followed by its old name.
NEW
328
    if (field.at(0) == QLatin1Char('R') || field.at(0) == QLatin1Char('C') ||
×
NEW
329
        field.at(1) == QLatin1Char('R') || field.at(1) == QLatin1Char('C')) {
×
NEW
330
      ++i;
×
331
    }
332
  }
333
  return entries;
334
}
335

336
auto RealPass::unrecorded(const QStringList &paths, bool ignored)
83 ✔
337
    -> QStringList {
338
  if (paths.isEmpty()) {
83 ✔
339
    return {};
13 ✔
340
  }
341
  const QDir store(QDir::cleanPath(m_settings.passStore));
70 ✔
342
  // Each path in the repository pass commits it in: a folder may hold one
343
  // of its own, which the store's status does not look into.
344
  QMap<QString, QStringList> byRepository;
70 ✔
345
  for (const QString &path : paths) {
149 ✔
346
    const QString repository = repositoryOf(path);
79 ✔
347
    const QDir top(repository.isEmpty() ? store.path()
79 ✔
348
                                        : store.filePath(repository));
79 ✔
349
    byRepository[repository] << top.relativeFilePath(QDir::cleanPath(path));
79 ✔
350
  }
79 ✔
351
  QStringList entries;
70 ✔
352
  for (auto it = byRepository.cbegin(); it != byRepository.cend(); ++it) {
140 ✔
353
    QStringList args{QStringLiteral("--untracked-files=all")};
140 ✔
354
    if (ignored) {
70 ✔
355
      args << QStringLiteral("--ignored");
31 ✔
356
    }
357
    args << QStringLiteral("--");
70 ✔
358
    entries += statusEntries(args + it.value(), it.key());
140 ✔
359
  }
360
  return entries;
361
}
70 ✔
362

363
namespace {
364
/**
365
 * @brief Whether @p name is one pass writes: an entry or a recipient list.
366
 * @param name A file name.
367
 * @return true for `*.gpg`, `.gpg-id` and `.gpg-id.sig`.
368
 */
NEW
369
auto isStoreFileName(const QString &name) -> bool {
×
NEW
370
  return name.endsWith(QLatin1String(".gpg")) ||
×
NEW
371
         name == QLatin1String(".gpg-id") ||
×
NEW
372
         name == QLatin1String(".gpg-id.sig");
×
373
}
374

375
/// At most this many status lines are named in a message.
376
constexpr qsizetype kMaxNamedChanges = 10;
377

378
/**
379
 * @brief @p lines for a message: the first kMaxNamedChanges, and how many
380
 * more there are.
381
 * @param lines `git status --porcelain` lines.
382
 * @return One per line.
383
 */
NEW
384
auto namedChanges(const QStringList &lines) -> QString {
×
NEW
385
  QString named = lines.mid(0, kMaxNamedChanges).join(QLatin1Char('\n'));
×
NEW
386
  if (lines.size() > kMaxNamedChanges) {
×
NEW
387
    named += QLatin1Char('\n') +
×
NEW
388
             RealPass::tr("and %n more", nullptr,
×
NEW
389
                          static_cast<int>(lines.size() - kMaxNamedChanges));
×
390
  }
NEW
391
  return named;
×
392
}
393
} // namespace
394

395
auto RealPass::refuseUnrecordedChanges(const QStringList &paths,
52 ✔
396
                                       const QStringList &committing) -> bool {
397
  QStringList changes = unrecorded(paths, false);
52 ✔
398
  QStringList repositories;
52 ✔
399
  for (const QString &path : committing) {
107 ✔
400
    const QString repository = repositoryOf(path);
55 ✔
401
    if (!repositories.contains(repository)) {
55 ✔
402
      repositories << repository;
403
    }
404
  }
405
  // pass commits the whole index, not only what it staged: anything staged
406
  // elsewhere goes along.
407
  for (const QString &repository : std::as_const(repositories)) {
104 ✔
408
    for (const QString &entry :
409
         statusEntries({QStringLiteral("--untracked-files=no")}, repository)) {
156 ✔
NEW
410
      if (entry.at(0) != QLatin1Char(' ') && !changes.contains(entry)) {
×
411
        changes << entry;
412
      }
413
    }
414
  }
415
  if (changes.isEmpty()) {
52 ✔
416
    return false;
417
  }
418
  const QString why =
NEW
419
      tr("The folder holds changes Git has not recorded, and pass would "
×
420
         "commit and push them along with this one:\n\n%1\n\nCommit, "
421
         "remove or ignore them with Git first, then try again.")
NEW
422
          .arg(namedChanges(changes));
×
423
  // As the other refusals: the interface arms when an operation starts and
424
  // is released by processErrorExit(); a refusal starts nothing.
NEW
425
  emit startingExecuteWrapper();
×
NEW
426
  emit critical(tr("Changes Git has not recorded"), why);
×
NEW
427
  emit processErrorExit(1, why);
×
428
  return true;
429
}
430

431
void RealPass::reportUnrecorded(const QStringList &paths) {
31 ✔
432
  QStringList changes;
31 ✔
433
  for (const QString &line : unrecorded(paths, true)) {
62 ✔
434
    // What pass writes: entries and recipient lists. Other ignored files in
435
    // a folder are the user's own business.
NEW
436
    if (isStoreFileName(QFileInfo(line.mid(3)).fileName())) {
×
437
      changes << line;
438
    }
439
  }
440
  if (changes.isEmpty()) {
31 ✔
441
    return;
442
  }
NEW
443
  emit critical(tr("Saved, not committed"),
×
NEW
444
                tr("The change is in the store, but Git did not record it, "
×
445
                   "so it is not pushed, and a pull may overwrite it "
446
                   "(\"!!\" marks a file Git ignores):\n\n%1")
NEW
447
                    .arg(namedChanges(changes)));
×
448
}
449

450
auto RealPass::refuseIgnoredThatMoves(const QString &src, const QString &dest)
9 ✔
451
    -> bool {
452
  if (!m_settings.useGit || !QFileInfo(src).isDir()) {
9 ✔
453
    return false;
454
  }
NEW
455
  const QDir store(QDir::cleanPath(m_settings.passStore));
×
456
  // pass moves a folder into an existing one, as mv does.
NEW
457
  const QString landing = QFileInfo(dest).isDir()
×
NEW
458
                              ? QDir(dest).filePath(QFileInfo(src).fileName())
×
NEW
459
                              : dest;
×
460
  // Each side in its own repository: where the files lie now, and the one
461
  // pass commits them in.
NEW
462
  const QString fromRepository = repositoryOf(src);
×
NEW
463
  const QString toRepository = repositoryOf(landing);
×
464
  const QString from =
NEW
465
      QDir(fromRepository.isEmpty() ? store.path()
×
NEW
466
                                    : store.filePath(fromRepository))
×
NEW
467
          .relativeFilePath(QDir::cleanPath(src));
×
468
  const QString to =
NEW
469
      QDir(toRepository.isEmpty() ? store.path() : store.filePath(toRepository))
×
NEW
470
          .relativeFilePath(QDir::cleanPath(landing));
×
471
  // ls-files names files relative to where git runs, where status names
472
  // them from the repository's root; both are that repository here.
NEW
473
  QString out;
×
NEW
474
  storeGit(
×
NEW
475
      inRepository(fromRepository,
×
NEW
476
                   {QStringLiteral("ls-files"), QStringLiteral("-z"),
×
NEW
477
                    QStringLiteral("--others"), QStringLiteral("--ignored"),
×
NEW
478
                    QStringLiteral("--exclude-standard"), QStringLiteral("--"),
×
479
                    from}),
480
      &out);
NEW
481
  QStringList moving;
×
NEW
482
  QStringList landed;
×
NEW
483
  for (const QString &file : out.split(QChar(0), Qt::SkipEmptyParts)) {
×
NEW
484
    if (!file.startsWith(from + QLatin1Char('/')) ||
×
NEW
485
        isStoreFileName(QFileInfo(file).fileName())) {
×
NEW
486
      continue;
×
487
    }
488
    moving << file;
NEW
489
    landed << to + file.mid(from.size());
×
490
  }
NEW
491
  if (landed.isEmpty()) {
×
492
    return false;
493
  }
494
  // A rule in a .gitignore inside the folder goes with it, so what it
495
  // ignores stays ignored where it lands, and decides there: deeper rules
496
  // win. Into a folder that is already there, a rule waiting deeper in it
497
  // could undo that, so only the lookup there counts.
NEW
498
  QStringList travelling;
×
NEW
499
  QStringList rules;
×
NEW
500
  if (!QFileInfo::exists(landing) &&
×
NEW
501
      checkIgnore(fromRepository, moving, true, &rules)) {
×
NEW
502
    for (qsizetype i = 0; i + 3 < rules.size(); i += 4) {
×
NEW
503
      if (rules.at(i).startsWith(from + QLatin1Char('/'))) {
×
504
        travelling << rules.at(i + 3);
505
      }
506
    }
507
  }
508
  // A lookup that failed counts nothing as ignored: the move is refused.
NEW
509
  QStringList ignoredThere;
×
NEW
510
  if (!checkIgnore(toRepository, landed, false, &ignoredThere)) {
×
NEW
511
    ignoredThere.clear();
×
512
  }
NEW
513
  QStringList exposed;
×
NEW
514
  for (qsizetype i = 0; i < landed.size(); ++i) {
×
NEW
515
    if (!travelling.contains(moving.at(i)) &&
×
516
        !ignoredThere.contains(landed.at(i))) {
NEW
517
      exposed << moving.at(i) + QStringLiteral(" > ") + landed.at(i);
×
518
    }
519
  }
NEW
520
  if (exposed.isEmpty()) {
×
521
    return false;
522
  }
523
  const QString why =
NEW
524
      tr("Git ignores these files only where they are now, and pass would "
×
525
         "commit and push them where they land:\n\n%1\n\nMove them out of "
526
         "the folder, or have Git ignore them there too, then try again.")
NEW
527
          .arg(namedChanges(exposed));
×
NEW
528
  emit startingExecuteWrapper();
×
NEW
529
  emit critical(tr("Ignored files would be committed"), why);
×
NEW
530
  emit processErrorExit(1, why);
×
531
  return true;
NEW
532
}
×
533

NEW
534
auto RealPass::checkIgnore(const QString &repository, const QStringList &paths,
×
535
                           bool verbose, QStringList *fields) -> bool {
536
  // check-ignore takes -z only with --stdin. Without
537
  // GIT_LITERAL_PATHSPECS (below) a name starting with ':' reads as
538
  // pathspec magic: "./" keeps every name a name. Git answers with the
539
  // name as given.
NEW
540
  const QString here = QStringLiteral("./");
×
NEW
541
  QString input;
×
NEW
542
  for (const QString &path : paths) {
×
NEW
543
    input += here + path + QChar(0);
×
544
  }
NEW
545
  QStringList args{QStringLiteral("check-ignore"), QStringLiteral("--stdin"),
×
NEW
546
                   QStringLiteral("-z")};
×
NEW
547
  if (verbose) {
×
NEW
548
    args << QStringLiteral("-v");
×
549
  }
550
  // check-ignore refuses every path under GIT_LITERAL_PATHSPECS, which
551
  // the store's environment sets; it takes its paths as names anyway.
NEW
552
  QProcessEnvironment environment = storeEnvironment();
×
NEW
553
  environment.remove(QStringLiteral("GIT_LITERAL_PATHSPECS"));
×
NEW
554
  QProcess lookup;
×
NEW
555
  lookup.setProcessEnvironment(environment);
×
NEW
556
  QString out;
×
NEW
557
  QString err;
×
NEW
558
  (void)Executor::executeBlocking(lookup, m_settings.passExecutable,
×
NEW
559
                                  QStringList{QStringLiteral("git")} +
×
NEW
560
                                      inRepository(repository, args),
×
561
                                  input, &out, &err);
562
  // pass git exits 0 whatever git did: a lookup that failed shows only on
563
  // stderr.
NEW
564
  if (!err.trimmed().isEmpty()) {
×
565
    return false;
566
  }
NEW
567
  *fields = out.split(QChar(0));
×
NEW
568
  if (!fields->isEmpty() && fields->constLast().isEmpty()) {
×
NEW
569
    fields->removeLast();
×
570
  }
571
  // The path is every field, or every fourth with -v.
NEW
572
  const qsizetype step = verbose ? 4 : 1;
×
NEW
573
  for (qsizetype i = step - 1; i < fields->size(); i += step) {
×
NEW
574
    if ((*fields)[i].startsWith(here)) {
×
NEW
575
      (*fields)[i].remove(0, here.size());
×
576
    }
577
  }
578
  return true;
NEW
579
}
×
580

581
void RealPass::Insert(QString file, QString newValue, bool overwrite) {
19 ✔
582
  if (refuseLinkedPath(file + ".gpg")) {
38 ✔
583
    return;
6 ✔
584
  }
585
  const QString entry =
586
      QDir::cleanPath(QDir::isAbsolutePath(file)
587
                          ? file + ".gpg"
34 ✔
588
                          : QDir(m_settings.passStore).filePath(file) + ".gpg");
68 ✔
589
  if (refuseUnverifiedList(entry)) {
17 ✔
590
    return;
591
  }
592
  if (refuseUnfinishedGitOperation() || refusePendingPull() ||
15 ✔
593
      refuseUnrecordedChanges({}, {entry})) {
54 ✔
594
    return;
595
  }
596
  m_insertQueue.enqueue(entry);
597
  // Past every refusal: this insert is now queued and will report once.
598
  queueInsert();
599
  QStringList args = {"insert", "-m"};
65 ✔
600
  if (overwrite) {
13 ✔
601
    args.append("-f");
12 ✔
602
  }
603
  args.append(file);
604
  executePass(PASS_INSERT, args, newValue);
26 ✔
605
}
606

607
void RealPass::onDequeuing(int id, bool completes) {
66 ✔
608
  if (id == PASS_INIT || id == PASS_MOVE || id == PASS_COPY) {
66 ✔
609
    // Leaves the queue with its command: a dropped one's scope must not
610
    // pair with the next completion.
611
    const QString scope =
612
        m_reencryptScopes.isEmpty() ? QString() : m_reencryptScopes.dequeue();
39 ✔
613
    if (!completes) {
39 ✔
614
      return;
615
    }
616
    m_reencryptPending.enqueue(scope);
617
    // pass exits 0 when it could not re-encrypt an entry (reencrypt_path
618
    // drops the temporary and carries on), so its exit code says nothing.
619
    // gpg's status lines do, in every locale: on stderr (fd 1 is the
620
    // `gpg -d | gpg -e` pipe), for this one process (Pass resets the
621
    // environment before each start), the last --status-fd winning over a
622
    // user's own; pass's own `--status-fd=1` for verifying a signed
623
    // .gpg-id comes later on its command line and still wins. WSLENV
624
    // already forwards PASSWORD_STORE_GPG_OPTS.
625
    QProcessEnvironment environment = exec.environment();
38 ✔
626
    const QString key = QStringLiteral("PASSWORD_STORE_GPG_OPTS");
38 ✔
627
    environment.insert(
38 ✔
628
        key,
629
        (environment.value(key) + QStringLiteral(" --status-fd 2")).trimmed());
76 ✔
630
    exec.setEnvironment(environment);
38 ✔
631
    return;
632
  }
38 ✔
633
  if (id != PASS_INSERT || m_insertQueue.isEmpty()) {
27 ✔
634
    return;
635
  }
636
  const QString target = m_insertQueue.dequeue();
637
  if (completes) {
13 ✔
638
    m_insertPending.enqueue({target, entryFingerprint(target)});
13 ✔
639
  }
640
}
13 ✔
641

642
auto RealPass::insertWritten(const QString &err) const -> bool {
6 ✔
643
  if (m_insertDone.target.isEmpty()) {
6 ✔
644
    return false;
645
  }
646
  // gpg broke off (a full disk, killed): pass says so, and what gpg left
647
  // at the entry's name, if anything, is no entry. The line is pass's own
648
  // (`die "Password encryption aborted."` after gpg in cmd_insert and
649
  // cmd_edit of password-store.sh), which pass does not translate.
650
  if (err.contains(QLatin1String("Password encryption aborted."))) {
6 ✔
651
    return false;
652
  }
653
  // pass writes the new ciphertext to the entry's name before it commits,
654
  // and an encryption never gives the same bytes twice (a fresh session
655
  // key), so an edited entry has changed as surely as a new one appeared.
656
  const QByteArray after = entryFingerprint(m_insertDone.target);
5 ✔
657
  return !after.isEmpty() && after != m_insertDone.before;
5 ✔
658
}
659

660
auto RealPass::entryFingerprint(const QString &path) -> QByteArray {
18 ✔
661
  QFile file;
18 ✔
662
  if (!Util::openRegularFile(path, file)) {
18 ✔
663
    return {};
9 ✔
664
  }
665
  QCryptographicHash hash(QCryptographicHash::Sha256);
9 ✔
666
  if (!hash.addData(&file)) {
9 ✔
667
    return {};
×
668
  }
669
  return hash.result();
9 ✔
670
}
18 ✔
671

672
void RealPass::Remove(QString file, bool isDir) {
9 ✔
673
  // Nothing behind a link is the store's to delete.
674
  if (refuseLinkedPath(isDir ? file : file + ".gpg", LinkScope::ParentsOnly)) {
24 ✔
675
    return;
6 ✔
676
  }
677
  if (refuseUnfinishedGitOperation() || refusePendingPull()) {
8 ✔
678
    return;
×
679
  }
680
  // pass rm turns a folder into "<folder>/" and rm -rf then follows a link
681
  // and empties its target, so a linked folder is unlinked here and pass's
682
  // git is only asked to forget it. pass rm -f on a linked .gpg unlinks.
683
  const QString full = QDir::cleanPath(m_settings.passStore + file);
8 ✔
684
  if (isDir && Util::isLinkedFolder(full)) {
8 ✔
685
    if (!Util::removeTree(full)) {
5 ✔
686
      const QString why = tr("Could not remove the link %1.").arg(full);
1 ✔
687
      emit critical(tr("Delete failed"), why);
1 ✔
688
      emit processErrorExit(1, why);
1 ✔
689
      return;
690
    }
691
    if (m_settings.useGit) {
4 ✔
692
      // `pass git` exits 0 whatever git did, so ask by output whether git
693
      // knew the link (these quick lookups block; the commit is queued).
694
      const QString rel = QDir(m_settings.passStore).relativeFilePath(full);
4 ✔
695
      // With the store's environment (PASSWORD_STORE_DIR), as executePass.
696
      QString known;
4 ✔
697
      QString err;
4 ✔
698
      // The link is gone from disk either way. A failed lookup or rm leaves
699
      // git tracking it: say so rather than report a clean removal.
700
      bool recorded = Executor::executeBlocking(
28 ✔
701
                          exec.environment(), m_settings.passExecutable,
8 ✔
702
                          {"git", "ls-files", "--", rel}, &known, &err) == 0;
4 ✔
703
      if (recorded && !known.trimmed().isEmpty()) {
12 ✔
704
        recorded =
705
            Executor::executeBlocking(
27 ✔
706
                exec.environment(), m_settings.passExecutable,
6 ✔
707
                {"git", "rm", "-q", "--cached", "--", rel}, &known, &err) == 0;
708
        if (recorded) {
3 ✔
709
          // `pass git commit` is git's commit as it is: pass adds -S only
710
          // to the commits it makes itself, so ask as its git_commit() does.
711
          QString signs;
2 ✔
712
          const bool sign =
713
              Executor::executeBlocking(
26 ✔
714
                  exec.environment(), m_settings.passExecutable,
4 ✔
715
                  {"git", "config", "--bool", "--get", "pass.signcommits"},
716
                  &signs, nullptr) == 0 &&
2 ✔
717
              signs.trimmed() == QLatin1String("true");
4 ✔
718
          QStringList commit{"git", "commit", "-q"};
14 ✔
719
          if (sign) {
2 ✔
720
            commit << "-S";
2 ✔
721
          }
722
          // Queued, as every other commit, so a signer or hook that waits
723
          // (a pinentry, an agent) does not freeze the window; finished()
724
          // judges it by what is left staged, since `pass git` exits 0
725
          // whatever git did.
726
          m_linkCommits.enqueue(
2 ✔
727
              {rel, m_settings.passExecutable, exec.environment()});
728
          executePass(
4 ✔
729
              GIT_COMMIT,
730
              commit + QStringList{"-m", "Remove for " + rel + " using QtPass.",
2 ✔
731
                                   "--", rel});
14 ✔
732
          return;
733
        }
734
      }
735
      if (!recorded) {
2 ✔
736
        const QString why =
737
            tr("The link %1 was removed, but git could not record it: %2")
1 ✔
738
                .arg(rel, err.trimmed());
2 ✔
739
        emit critical(tr("Delete incomplete"), why);
1 ✔
740
        emit processErrorExit(1, why);
1 ✔
741
      }
742
    }
743
    // Nothing ran for pass to finish: the removal is done here, and the
744
    // store changed.
745
    emit finishedRemove(QString(), QString());
4 ✔
746
    return;
2 ✔
747
  }
748
  executePass(PASS_REMOVE, {"rm", (isDir ? "-rf" : "-f"), file});
15 ✔
749
}
18 ✔
750

751
void RealPass::finished(int id, int exitCode, const QString &out,
72 ✔
752
                        const QString &err) {
753
  if (static_cast<PROCESS>(id) == GIT_COMMIT && !m_linkCommits.isEmpty()) {
72 ✔
754
    // Whatever the exit code (pass itself failing, or 0 whatever git
755
    // did), what is left staged decides.
756
    finishLinkCommit(m_linkCommits.dequeue(), out, err);
2 ✔
757
    return;
2 ✔
758
  }
759
  if (static_cast<PROCESS>(id) == PASS_INSERT) {
70 ✔
760
    // This completion's own insert, not whichever left the queue last.
761
    m_insertDone =
762
        m_insertPending.isEmpty() ? InsertRecord{} : m_insertPending.dequeue();
41 ✔
763
  }
764
  const auto pid = static_cast<PROCESS>(id);
70 ✔
765
  if (pid == PASS_INIT || pid == PASS_MOVE || pid == PASS_COPY) {
70 ✔
766
    // Without a recorded scope (not queued through Init/Move/Copy), the
767
    // whole store: held as a whole, released by nothing short of it.
768
    const QString scope =
769
        m_reencryptPending.isEmpty() ? QString() : m_reencryptPending.dequeue();
38 ✔
770
    if (exitCode == 0 && reencryptFailed(out, err)) {
38 ✔
771
      holdAutoPush(scope);
10 ✔
772
      sendDeferredPush();
10 ✔
773
      reportReencryptFailure(pid, out, err);
10 ✔
774
      return;
775
    }
776
    // A run that failed may have stopped after its commit (pass init commits
777
    // the new .gpg-id before re-encrypting; signing it may fail, the process
778
    // may be killed): held as well, until a clean init covers it. A move or
779
    // copy that failed before re-encrypting anything (the destination
780
    // exists, a mistyped name) changed no recipients: not held.
781
    if (exitCode != 0 && (pid == PASS_INIT ||
28 ✔
782
                          out.contains(QLatin1String(": reencrypting to ")))) {
2 ✔
783
      holdAutoPush(scope);
3 ✔
784
    }
785
    // pass init re-encrypts everything under its folder: a clean run
786
    // releases the holds there. A move or copy covers only its entries.
787
    if (pid == PASS_INIT && exitCode == 0 && !scope.isEmpty()) {
28 ✔
788
      releaseAutoPush(scope);
18 ✔
789
    }
790
    if (exitCode == 0 && !scope.isEmpty()) {
28 ✔
791
      reportUnrecorded({scope});
72 ✔
792
    }
793
    sendDeferredPush();
28 ✔
794
    // The status lines are for this check, not for the output panel.
795
    Pass::finished(id, exitCode, out, withoutStatusLines(err));
28 ✔
796
    return;
28 ✔
797
  }
798
  if (pid == PASS_INSERT && exitCode == 0 && !m_insertDone.target.isEmpty()) {
32 ✔
799
    reportUnrecorded({m_insertDone.target});
21 ✔
800
  }
801
  Pass::finished(id, exitCode, out, err);
32 ✔
802
}
803

804
auto RealPass::reencryptFailed(const QString &out, const QString &err) -> bool {
42 ✔
805
  // pass's own line for each entry it re-encrypts ("name: reencrypting to
806
  // KEY..."), which it does not translate; one per line, counted once
807
  // even when the entry's own name holds the words.
808
  const QStringList outLines = out.split(QLatin1Char('\n'));
42 ✔
809
  const auto attempts = std::count_if(
42 ✔
810
      outLines.cbegin(), outLines.cend(), [](const QString &line) {
79 ✔
811
        return line.contains(QLatin1String(": reencrypting to "));
79 ✔
812
      });
813
  qsizetype encrypted = 0;
814
  bool status = false;
815
  for (QString line : err.split(QLatin1Char('\n'))) {
98 ✔
816
    line.remove(QLatin1Char('\r'));
68 ✔
817
    if (!line.startsWith(QLatin1String("[GNUPG:] "))) {
68 ✔
818
      continue;
819
    }
820
    status = true;
821
    // A recipient gpg cannot encrypt to, or a decrypt that failed (no
822
    // secret key, pinentry cancelled, no smartcard): that entry was left
823
    // as it was. KEYEXPIRED and NO_SECKEY alone are not failures.
824
    if (line.startsWith(QLatin1String("[GNUPG:] INV_RECP ")) ||
57 ✔
825
        line.startsWith(QLatin1String("[GNUPG:] FAILURE ")) ||
57 ✔
826
        line.startsWith(QLatin1String("[GNUPG:] DECRYPTION_FAILED"))) {
35 ✔
827
      return true;
828
    }
829
    if (line.startsWith(QLatin1String("[GNUPG:] END_ENCRYPTION"))) {
22 ✔
830
      ++encrypted;
20 ✔
831
    }
832
  }
833
  // Without any status line the option did not reach gpg (a pass that does
834
  // not pass PASSWORD_STORE_GPG_OPTS on): nothing to judge by.
835
  return status && encrypted < attempts;
30 ✔
836
}
837

838
void RealPass::reportReencryptFailure(PROCESS pid, const QString &out,
10 ✔
839
                                      const QString &err) {
840
  QStringList failures;
10 ✔
841
  for (QString line : err.split(QLatin1Char('\n'))) {
52 ✔
842
    line.remove(QLatin1Char('\r'));
32 ✔
843
    // Encrypt-side only: gpgErrorMessage() reads any FAILURE as a key that
844
    // cannot encrypt, wrong advice for a decrypt that failed (no secret
845
    // key, pinentry cancelled), whose reason gpg's own text gives.
846
    if (line.startsWith(QLatin1String("[GNUPG:] INV_RECP ")) ||
54 ✔
847
        line.startsWith(QLatin1String("[GNUPG:] FAILURE encrypt"))) {
54 ✔
848
      failures << line;
849
    }
850
  }
851
  const QString human = withoutStatusLines(err).trimmed();
20 ✔
852
  const QString reason = gpgErrorMessage(failures.join(QLatin1Char('\n')));
20 ✔
853
  QString body =
854
      tr("The recipients were changed, but some entries could not be "
855
         "re-encrypted for them: those are still encrypted to the previous "
856
         "recipients, who can still read them. With Git the change is "
857
         "committed locally and not pushed: QtPass does not push this store "
858
         "automatically until a re-encryption succeeds, and a push by hand "
859
         "sends it.");
860
  for (const QString &part : {reason, human}) {
50 ✔
861
    if (!part.isEmpty()) {
20 ✔
862
      body += QStringLiteral("\n\n") + part;
24 ✔
863
    }
864
  }
30 ✔
865
  // pass's "reencrypting to" lines and gpg's own text, for the output panel.
866
  emit finishedAnyWithPid(out, human, pid);
10 ✔
867
  emit critical(
10 ✔
868
      QCoreApplication::translate("ImitatePass", "Re-encryption failed"), body);
10 ✔
869
  // Not finishedInit/Move/Copy: that would push the store as it now is.
870
  emit processErrorExit(1, body);
10 ✔
871
}
10 ✔
872

873
void RealPass::finishLinkCommit(const LinkCommit &commit, const QString &out,
2 ✔
874
                                const QString &err) {
875
  // In the store the commit ran in, which a profile switch meanwhile does
876
  // not change.
877
  const QString &rel = commit.rel;
2 ✔
878
  QString staged;
2 ✔
879
  const bool committed =
880
      Executor::executeBlocking(
16 ✔
881
          commit.environment, commit.passExecutable,
2 ✔
882
          {"git", "diff", "--cached", "--name-only", "--", rel}, &staged,
883
          nullptr) == 0 &&
4 ✔
884
      staged.trimmed().isEmpty();
2 ✔
885
  if (committed) {
2 ✔
886
    // As Pass::finished() would: git's output (a hook's warning, say) for
887
    // the output panel, then the removal.
888
    emit finishedAnyWithPid(out, err, GIT_COMMIT);
1 ✔
889
    emit finishedRemove(out, err);
1 ✔
890
    return;
891
  }
892
  const QString why = tr("The link %1 was removed and git no longer tracks "
×
893
                         "it, but the commit failed: %2")
894
                          .arg(rel, err.trimmed());
2 ✔
895
  emit critical(tr("Delete incomplete"), why);
1 ✔
896
  emit processErrorExit(1, why);
1 ✔
897
  emit finishedRemove(QString(), QString());
2 ✔
898
}
2 ✔
899

900
void RealPass::Init(QString path, const QList<UserInfo> &users) {
37 ✔
901
  // A relative path names a folder in the store, as --path does for pass:
902
  // resolved once, so the checks below look where pass writes, not in the
903
  // working directory.
904
  const QString folder = QDir::cleanPath(
905
      QDir::isAbsolutePath(path) ? path
61 ✔
906
                                 : QDir(m_settings.passStore).filePath(path));
98 ✔
907
  // pass init writes .gpg-id with a shell redirection and gpg writes the
908
  // signature with --output; both follow a link planted under those names.
909
  // --path is store-relative, or pass creates passStore/passStore/dir: the
910
  // store check hands it over as it judged it, so a store root reached
911
  // through a link and a folder spelled through its target agree (a lexical
912
  // relativeFilePath() made that ../../target/dir, which pass refuses).
913
  QString dirWithoutPassdir;
37 ✔
914
  const auto refusePlaced = [this](const QString &placed) {
915
    return refuseLinkedPath(placed, LinkScope::EntryAndParents,
108 ✔
916
                            PathSpelling::PlacedByCaller);
917
  };
918
  if (refusePlaced(folder) ||
36 ✔
919
      refusePlaced(folder + QStringLiteral("/.gpg-id")) ||
144 ✔
920
      refusePlaced(folder + QStringLiteral("/.gpg-id.sig")) ||
178 ✔
921
      refuseFolderOutsideStore(folder, &dirWithoutPassdir)) {
35 ✔
922
    return;
923
  }
924
  // pass init writes this folder's list and then re-encrypts everything
925
  // under it to each entry's nearest list, a deeper folder's own included:
926
  // those are checked as for a move. This folder's list is the one being
927
  // written, so it is neither verified nor missed. Walked in the store's
928
  // own spelling: a folder spelled through the target of a linked store
929
  // root is not under the store as named, and the lookup of each nearest
930
  // list would stop at once and miss the deeper ones.
931
  const QString inStore =
932
      QDir::cleanPath(QDir(m_settings.passStore).filePath(dirWithoutPassdir));
66 ✔
933
  if (refuseUnverifiedTree(inStore, true,
33 ✔
934
                           QDir(inStore).filePath(QStringLiteral(".gpg-id")))) {
66 ✔
935
    return;
936
  }
937
  if (refuseUnfinishedGitOperation() || refusePendingPull() ||
30 ✔
938
      refuseUnrecordedChanges({inStore}, {inStore})) {
180 ✔
939
    return;
940
  }
941
  QStringList args = {"init", "--path=" + dirWithoutPassdir};
90 ✔
942
  for (const UserInfo &user : users) {
62 ✔
943
    if (user.enabled) {
32 ✔
944
      args.append(user.key_id);
31 ✔
945
    }
946
  }
947
  m_reencryptScopes.enqueue(inStore);
948
  executePass(PASS_INIT, args);
60 ✔
949
}
30 ✔
950

951
void RealPass::Move(const QString src, const QString dest, const bool force) {
12 ✔
952
  passMoveOrCopy(PASS_MOVE, QStringLiteral("mv"), src, dest, force);
24 ✔
953
}
12 ✔
954

955
void RealPass::Copy(const QString src, const QString dest, const bool force) {
10 ✔
956
  passMoveOrCopy(PASS_COPY, QStringLiteral("cp"), src, dest, force);
20 ✔
957
}
10 ✔
958

959
auto RealPass::passName(const QString &path, bool stripGpg) const -> QString {
18 ✔
960
  QString name =
961
      QDir(QDir::cleanPath(m_settings.passStore))
18 ✔
962
          .relativeFilePath(QDir::cleanPath(QDir(path).absolutePath()));
36 ✔
963
  if (stripGpg) {
18 ✔
964
    name.replace(Util::endsWithGpg(), "");
12 ✔
965
  }
966
  return name;
18 ✔
967
}
968

969
void RealPass::passMoveOrCopy(PROCESS id, const QString &subcommand,
22 ✔
970
                              const QString &src, const QString &dest,
971
                              const bool force) {
972
  if (refuseLinkedPath(src) || refuseLinkedPath(dest)) {
22 ✔
973
    return;
13 ✔
974
  }
975
  QFileInfo srcFileInfo = QFileInfo(src);
19 ✔
976
  QFileInfo destFileInfo = QFileInfo(dest);
19 ✔
977
  // A drop hands over the folder; pass then writes <folder>/<name>, and cp
978
  // writes through a link planted under that name.
979
  if (destFileInfo.isDir() &&
19 ✔
980
      refuseLinkedPath(QDir(dest).filePath(srcFileInfo.fileName()))) {
45 ✔
981
    return;
982
  }
983

984
  // pass always forces when called from QtPass, so refuse file-onto-file.
985
  if (!force && srcFileInfo.isFile() && destFileInfo.isFile()) {
18 ✔
986
    return;
987
  }
988

989
  // pass re-encrypts what it moves or copies to the destination's list, a
990
  // folder's entries also to the lists that go along with it, and, when it
991
  // writes into an existing folder, everything already in that folder too
992
  // (reencrypt_path on the whole destination).
993
  if (refuseUnverifiedList(destFileInfo.isDir()
34 ✔
994
                               ? QDir(dest).filePath(srcFileInfo.fileName())
46 ✔
995
                               : dest) ||
15 ✔
996
      (srcFileInfo.isDir() && refuseUnverifiedTree(src, true)) ||
56 ✔
997
      (destFileInfo.isDir() && refuseUnverifiedTree(dest, false))) {
35 ✔
998
    return;
999
  }
1000
  // pass stages what it moved or copied with `git add` on the new path,
1001
  // and a folder brings whatever lies in it along. It commits there, and a
1002
  // move commits the removal where the original was as well.
1003
  const QStringList committing =
1004
      id == PASS_MOVE ? QStringList{src, dest} : QStringList{dest};
30 ✔
1005
  if (refuseUnfinishedGitOperation() || refusePendingPull() ||
27 ✔
1006
      refuseUnrecordedChanges({src, dest}, committing) ||
54 ✔
1007
      refuseIgnoredThatMoves(src, dest)) {
9 ✔
1008
    return;
1009
  }
1010

1011
  // pass appends .gpg itself, so an entry named with it would come out as
1012
  // "name.gpg.gpg"; the destination usually does not exist yet.
1013
  const QString passSrc =
1014
      passName(src, srcFileInfo.isFile() &&
9 ✔
1015
                        srcFileInfo.suffix() == QLatin1String("gpg"));
12 ✔
1016
  const QString passDest =
1017
      passName(dest, !destFileInfo.isDir() &&
9 ✔
1018
                         destFileInfo.suffix() == QLatin1String("gpg"));
13 ✔
1019

1020
  QStringList args;
9 ✔
1021
  args << subcommand;
1022
  if (force) {
9 ✔
1023
    args << "-f";
6 ✔
1024
  }
1025
  args << passSrc;
1026
  args << passDest;
1027
  m_reencryptScopes.enqueue(QDir::cleanPath(QDir(dest).absolutePath()));
18 ✔
1028
  executePass(id, args);
18 ✔
1029
}
19 ✔
1030

1031
// Not `pass grep` (find -L follows links out of the store): the native
1032
// search walks real files only (Util::regularFilesUnder), so it needs gpg.
1033
void RealPass::Grep(QString pattern, bool caseInsensitive) {
2 ✔
1034
  if (m_settings.gpgExecutable.isEmpty()) {
2 ✔
1035
    emit statusMsg(tr("Search needs the GPG executable to be configured."),
1 ✔
1036
                   5000);
1037
    emit finishedGrep({});
1 ✔
1038
    return;
1 ✔
1039
  }
1040
  m_grep.search(pattern, caseInsensitive, m_settings.gpgExecutable,
2 ✔
1041
                m_settings.passStore, exec.environment());
1 ✔
1042
}
1043

1044
void RealPass::executePass(PROCESS id, const QStringList &args, QString input,
66 ✔
1045
                           bool readStdout, bool readStderr) {
1046
  executeWrapper(id, m_settings.passExecutable, args, std::move(input),
66 ✔
1047
                 readStdout, readStderr);
1048
}
66 ✔
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