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

IJHack / QtPass / 44890039246

21 Nov 2026 09:32AM UTC coverage: 94.653% (+0.02%) from 94.638%
44890039246

push

github

web-flow
pass backend: refuse a linked .gpg-id without a signing key too (#2284)

* pass backend: refuse a linked .gpg-id without a signing key too

QtPass's lookup skips a .gpg-id that is a link and shows the parent
folder's list, while pass follows the link and encrypts to the recipients
it points to. With a signing key the pass backend already refused that;
without one it ran pass, which encrypted to people the Users dialog did
not show (scan finding ANT-2026-BSUT09L8).

Pass::linkedGpgId() names the first link or junction the walk to a
folder's list meets, root included. RealPass::refuseUnverifiedList() and
refuseUnverifiedTree() refuse on it before the signing-key check. The FAQ
names the convenience this costs: a shared list linked into folders.

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

* FAQ: name the linked list at the top of the store

A store whose root .gpg-id is a link, as GNU Stow or chezmoi may set it
up, is refused as a whole with the pass backend. Say so.

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

* pass backend: pass over a folder named .gpg-id; refuse an unread walk

A folder under the name .gpg-id counted as the folder's own list and
stopped the walk, while pass (test -f) passes over it and follows a
linked list further up. isOwnGpgId() now asks for a regular file.

refuseUnverifiedTree() refused a folder holding a name that is not
valid UTF-8 only with a signing key. Without one, a linked list behind
that name went unseen. The incomplete walk is now refused first, signing
key or not.

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

* tst_realpass: keep the POSIX mkdir case off Windows

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

* pass backend: bound the link check to the fold... (continued)

36 of 37 new or added lines in 2 files covered. (97.3%)

9418 of 9950 relevant lines covered (94.65%)

1246.76 hits per line

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

68.86
/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) {
39 ✔
39
  connect(&m_grep, &NativeGrep::finished, this, &RealPass::finishedGrep);
39 ✔
40
  connect(&exec, &Executor::dequeuing, this, &RealPass::onDequeuing);
39 ✔
41
}
39 ✔
42

43
RealPass::~RealPass() { m_grep.cancel(); }
100 ✔
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"}); }
18 ✔
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() {
39 ✔
80
  if (!m_pushAfterReencrypt || !m_reencryptScopes.isEmpty() ||
39 ✔
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 {
90 ✔
106
  return {m_settings.gpgExecutable,
107
          GpgIdSigner::keysFromSetting(m_settings.passSigningKey),
180 ✔
108
          [this](const QString &app, const QStringList &args,
90 ✔
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
          }};
205 ✔
114
}
115

116
auto RealPass::refuseList(const QString &file, const GpgIdSigner &signer,
33 ✔
117
                          QSet<QString> &verified, const QString &within,
118
                          const QString &except) -> bool {
119
  if (refuseSkippedGpgId(file, true, except)) {
33 ✔
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::refuseLinkedList(const QString &file, const QString &within,
111 ✔
146
                                const QString &except) -> bool {
147
  const std::optional<QString> linked =
148
      Pass::linkedGpgId(file, m_settings.passStore);
111 ✔
149
  if (!linked) {
111 ✔
150
    return false;
151
  }
152
  const QString absolute =
153
      QDir::cleanPath(QFileInfo(*linked).absoluteFilePath());
14 ✔
154
  if ((!except.isEmpty() &&
1 ✔
155
       absolute == QDir::cleanPath(QFileInfo(except).absoluteFilePath())) ||
17 ✔
156
      (!within.isEmpty() && !absolute.startsWith(within))) {
2 ✔
157
    return false;
158
  }
159
  emit critical(
12 ✔
160
      tr("Recipient list is a link"),
6 ✔
161
      tr("%1 is a link. pass would encrypt to the recipients in the file it "
6 ✔
162
         "points to, while QtPass shows the list of a folder above it, so "
163
         "nothing was encrypted. Replace the link with a copy of the list, or "
164
         "remove it.")
165
          .arg(QDir::toNativeSeparators(*linked)));
12 ✔
166
  return true;
6 ✔
167
}
168

169
auto RealPass::refuseUnverifiedList(const QString &file) -> bool {
44 ✔
170
  // pass verifies the signature itself, but knows nothing of the generation
171
  // and folder lines: an older authentic list put back, or one signed for
172
  // another folder, would get the secret (#2077). The same checks as the
173
  // native backend, with gpg in the store's environment. pass reads the list
174
  // again afterwards; a swap in between is a concurrent writer, out of
175
  // scope (SECURITY.md). A linked list differs from what QtPass shows,
176
  // signing key or not.
177
  if (refuseLinkedList(file)) {
88 ✔
178
    return true;
179
  }
180
  const GpgIdSigner signer = listSigner();
39 ✔
181
  if (!signer.enabled()) {
39 ✔
182
    return false;
183
  }
184
  QSet<QString> verified;
185
  return refuseList(file, signer, verified);
24 ✔
186
}
39 ✔
187

188
namespace {
189
/// @p dir and every folder under it as pass's reencrypt_path() walks them
190
/// (find without -L): hidden ones included, .git left out, no link
191
/// followed. Each entry pass re-encrypts lies in one of them, and its list
192
/// is that folder's nearest. A folder holding a name Qt cannot read
193
/// (Util::hasUnreadableName()) goes to @p unreadable instead of being
194
/// walked: find sees what Qt leaves out, a folder with its own list
195
/// included.
196
auto passFoldersUnder(const QString &dir, QStringList &unreadable)
70 ✔
197
    -> QStringList {
198
  QStringList folders{QDir::cleanPath(dir)};
140 ✔
199
  if (Util::hasUnreadableName(dir)) {
70 ✔
200
    unreadable << QDir::cleanPath(dir);
2 ✔
201
    return folders;
2 ✔
202
  }
203
  const QFileInfoList children = QDir(dir).entryInfoList(
136 ✔
204
      QDir::Dirs | QDir::Hidden | QDir::System | QDir::NoDotAndDotDot);
68 ✔
205
  for (const QFileInfo &child : children) {
84 ✔
206
    if (child.isSymLink() || child.isJunction() ||
16 ✔
207
        child.fileName() == QLatin1String(".git")) {
32 ✔
208
      continue;
×
209
    }
210
    folders << passFoldersUnder(child.absoluteFilePath(), unreadable);
32 ✔
211
  }
212
  return folders;
213
}
70 ✔
214
} // namespace
215

216
auto RealPass::refuseUnverifiedTree(const QString &dir, bool onlyListsWithin,
54 ✔
217
                                    const QString &except) -> bool {
218
  // Every folder pass's walk takes. A name Qt cannot read hides what is
219
  // behind it, a linked list included, so the walk must be complete first,
220
  // signing key or not.
221
  QStringList unreadable;
54 ✔
222
  const QStringList folders = passFoldersUnder(dir, unreadable);
54 ✔
223
  if (!unreadable.isEmpty()) {
54 ✔
224
    const QString title = tr("Cannot check the recipient lists");
225
    //: %1 is a folder. "UTF-8" is the text encoding; keep it as is.
226
    const QString text =
NEW
227
        tr("%1 holds a file or folder whose name is not valid UTF-8. QtPass "
×
228
           "cannot see what is behind that name, while pass would re-encrypt "
229
           "it, so nothing was changed. Rename it, then try again.")
230
            .arg(QDir::toNativeSeparators(unreadable.first()));
4 ✔
231
    emit critical(title, text);
2 ✔
232
    return true;
233
  }
234
  // Absolute, as getGpgIdPath() hands lists back: a relative or other
235
  // spelling would match nothing and check nothing.
236
  const QString within =
237
      onlyListsWithin ? QDir::cleanPath(QFileInfo(dir).absoluteFilePath()) +
194 ✔
238
                            QLatin1Char('/')
239
                      : QString();
149 ✔
240
  // A linked list differs from what QtPass shows, signing key or not: in
241
  // every folder of the walk, and above them unless only the lists within
242
  // count (the folder that moves gets the destination's list, the folder
243
  // pass init writes its own).
244
  for (const QString &folder : folders) {
118 ✔
245
    if (refuseLinkedList(folder + QLatin1Char('/'), within, except)) {
134 ✔
246
      return true;
247
    }
248
  }
249
  const GpgIdSigner signer = listSigner();
51 ✔
250
  if (!signer.enabled()) {
51 ✔
251
    return false;
252
  }
253
  // One gpg call per list, before pass runs: a store with many lists makes
254
  // that a noticeable pause, so say what it is.
255
  emit statusMsg(tr("Checking the recipient lists under %1…")
28 ✔
256
                     .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))),
28 ✔
257
                 3000);
258
  // pass mv and cp re-encrypt every entry of the folder they write to, each
259
  // to its nearest list, walking as passFoldersUnder() does. For the folder
260
  // that moves, the lists inside it go along: checked where they lie now
261
  // (after the move their folder line names the old place until the
262
  // recipients are saved there again), while a list above it is replaced
263
  // by the destination's, which the caller checks. For entries already in
264
  // the destination, their lists stay where they are: all of them count.
265
  QSet<QString> verified;
266
  // Every folder's list counts, also where no entry uses it yet: cp -r
267
  // merges an incoming folder into one of the same name, so the entries it
268
  // brings get a list already there, and a list it brings replaces the one
269
  // there for the entries already in it.
270
  for (const QString &folder : folders) {
27 ✔
271
    if (refuseList(folder, signer, verified, within, except)) {
21 ✔
272
      return true;
273
    }
274
  }
275
  return false;
276
}
51 ✔
277

278
auto RealPass::storeGit(const QStringList &args, QString *out) -> bool {
7 ✔
279
  if (!m_settings.useGit) {
7 ✔
280
    return false;
281
  }
282
  // `pass git` runs git in the store with PASSWORD_STORE_DIR set, as the
283
  // store's other quick lookups do; its exit code is git's own.
284
  QString err;
7 ✔
285
  return Executor::executeBlocking(
7 ✔
286
             exec.environment(), m_settings.passExecutable,
14 ✔
287
             QStringList{QStringLiteral("git")} + args, out, &err) == 0;
28 ✔
288
}
289

290
namespace {
291
/**
292
 * @brief @p args for `pass git`, run in @p repository.
293
 * @param repository A folder relative to the store; empty for the store.
294
 * @param args The git arguments.
295
 * @return `-C <repository>` and @p args.
296
 */
297
auto inRepository(const QString &repository, const QStringList &args)
×
298
    -> QStringList {
299
  if (repository.isEmpty()) {
×
300
    return args;
301
  }
302
  return QStringList{QStringLiteral("-C"), repository} + args;
×
303
}
304
} // namespace
305

306
auto RealPass::repositoryOf(const QString &path) -> QString {
145 ✔
307
  if (!m_settings.useGit) {
145 ✔
308
    return {};
145 ✔
309
  }
310
  const QString root = QDir::cleanPath(m_settings.passStore);
×
311
  // From the nearest folder that exists, as pass looks for it.
312
  QString folder = QDir::cleanPath(path);
×
313
  while (!QFileInfo(folder).isDir() &&
×
314
         folder.startsWith(root + QLatin1Char('/'))) {
×
315
    folder = QFileInfo(folder).path();
×
316
  }
317
  const QString relative = QDir(root).relativeFilePath(folder);
×
318
  if (relative == QLatin1String(".") || relative == QLatin1String("..") ||
×
319
      relative.startsWith(QLatin1String("../"))) {
×
320
    return {};
×
321
  }
322
  // The folder's place in its repository ("team/" in the store's own,
323
  // "" at the top of the one it holds itself).
324
  QString prefix;
×
325
  storeGit({QStringLiteral("-C"), relative, QStringLiteral("rev-parse"),
×
326
            QStringLiteral("--show-prefix")},
×
327
           &prefix);
328
  if (prefix.endsWith(QLatin1Char('\n'))) {
×
329
    prefix.chop(1);
×
330
  }
331
  const QString withSlash = relative + QLatin1Char('/');
×
332
  if (!withSlash.endsWith(prefix)) {
×
333
    return {};
×
334
  }
335
  QString repository = withSlash.chopped(prefix.size());
336
  if (repository.endsWith(QLatin1Char('/'))) {
×
337
    repository.chop(1);
×
338
  }
339
  return repository;
340
}
341

342
auto RealPass::statusEntries(const QStringList &args, const QString &repository)
133 ✔
343
    -> QStringList {
344
  if (!m_settings.useGit) {
133 ✔
345
    return {};
133 ✔
346
  }
347
  QString out;
×
348
  // -z: names as they are, not quoted when they hold a non-ASCII letter.
349
  // `pass git` exits 0 whatever git did: the output decides, and a git
350
  // that cannot say (no repository) prints nothing to it.
351
  storeGit(inRepository(repository, QStringList{QStringLiteral("status"),
×
352
                                                QStringLiteral("--porcelain"),
×
353
                                                QStringLiteral("-z")} +
×
354
                                        args),
×
355
           &out);
356
  const QString place =
357
      repository.isEmpty() ? QString() : repository + QLatin1Char('/');
×
358
  QStringList entries;
×
359
  const QStringList fields = out.split(QChar(0), Qt::SkipEmptyParts);
×
360
  for (qsizetype i = 0; i < fields.size(); ++i) {
×
361
    const QString &field = fields.at(i);
362
    if (field.size() < 4 || field.at(2) != QLatin1Char(' ')) {
×
363
      continue;
×
364
    }
365
    entries << field.left(3) + place + field.mid(3);
×
366
    // A rename or copy, in the index or in the work tree (an intent-to-add
367
    // file), is followed by its old name.
368
    if (field.at(0) == QLatin1Char('R') || field.at(0) == QLatin1Char('C') ||
×
369
        field.at(1) == QLatin1Char('R') || field.at(1) == QLatin1Char('C')) {
×
370
      ++i;
×
371
    }
372
  }
373
  return entries;
374
}
375

376
auto RealPass::unrecorded(const QStringList &paths, bool ignored)
93 ✔
377
    -> QStringList {
378
  if (paths.isEmpty()) {
93 ✔
379
    return {};
17 ✔
380
  }
381
  const QDir store(QDir::cleanPath(m_settings.passStore));
76 ✔
382
  // Each path in the repository pass commits it in: a folder may hold one
383
  // of its own, which the store's status does not look into.
384
  QMap<QString, QStringList> byRepository;
76 ✔
385
  for (const QString &path : paths) {
161 ✔
386
    const QString repository = repositoryOf(path);
85 ✔
387
    const QDir top(repository.isEmpty() ? store.path()
85 ✔
388
                                        : store.filePath(repository));
85 ✔
389
    byRepository[repository] << top.relativeFilePath(QDir::cleanPath(path));
85 ✔
390
  }
85 ✔
391
  QStringList entries;
76 ✔
392
  for (auto it = byRepository.cbegin(); it != byRepository.cend(); ++it) {
152 ✔
393
    QStringList args{QStringLiteral("--untracked-files=all")};
152 ✔
394
    if (ignored) {
76 ✔
395
      args << QStringLiteral("--ignored");
36 ✔
396
    }
397
    args << QStringLiteral("--");
76 ✔
398
    entries += statusEntries(args + it.value(), it.key());
152 ✔
399
  }
400
  return entries;
401
}
76 ✔
402

403
namespace {
404
/**
405
 * @brief The untracked files among @p lines that a file manager writes by
406
 * itself in the folders it opens: Finder's `.DS_Store`, Explorer's
407
 * `Thumbs.db` and `desktop.ini`, Dolphin's `.directory`. A rule in a
408
 * .gitignore keeps those out; one Git already tracks it does not.
409
 * @param lines `git status --porcelain` entries.
410
 * @param paths Receives each such file's path, as the entry names it.
411
 * @return Each such name once, in that order.
412
 */
413
auto fileManagerFiles(const QStringList &lines, QStringList *paths)
×
414
    -> QStringList {
415
  QStringList found;
×
416
  for (const QString &name :
×
417
       {QStringLiteral(".DS_Store"), QStringLiteral("Thumbs.db"),
×
418
        QStringLiteral("desktop.ini"), QStringLiteral(".directory")}) {
×
419
    for (const QString &line : lines) {
×
420
      if (line.startsWith(QLatin1String("?? ")) &&
×
421
          QFileInfo(line.mid(3)).fileName() == name) {
×
422
        if (!found.contains(name)) {
×
423
          found << name;
424
        }
425
        *paths << line.mid(3);
×
426
      }
427
    }
428
  }
×
429
  return found;
×
430
}
431

432
/**
433
 * @brief Whether @p name is one pass writes: an entry or a recipient list.
434
 * @param name A file name.
435
 * @return true for `*.gpg`, `.gpg-id` and `.gpg-id.sig`.
436
 */
437
auto isStoreFileName(const QString &name) -> bool {
×
438
  return name.endsWith(QLatin1String(".gpg")) ||
×
439
         name == QLatin1String(".gpg-id") ||
×
440
         name == QLatin1String(".gpg-id.sig");
×
441
}
442

443
/// At most this many status lines are named in a message.
444
constexpr qsizetype kMaxNamedChanges = 10;
445

446
/**
447
 * @brief @p lines for a message: the first kMaxNamedChanges, and how many
448
 * more there are.
449
 * @param lines `git status --porcelain` lines.
450
 * @return One per line.
451
 */
452
auto namedChanges(const QStringList &lines) -> QString {
×
453
  QString named = lines.mid(0, kMaxNamedChanges).join(QLatin1Char('\n'));
×
454
  if (lines.size() > kMaxNamedChanges) {
×
455
    named += QLatin1Char('\n') +
×
456
             RealPass::tr("and %n more", nullptr,
×
457
                          static_cast<int>(lines.size() - kMaxNamedChanges));
×
458
  }
459
  return named;
×
460
}
461
} // namespace
462

463
auto RealPass::refuseUnrecordedChanges(const QStringList &paths,
57 ✔
464
                                       const QStringList &committing) -> bool {
465
  QStringList changes = unrecorded(paths, false);
57 ✔
466
  QStringList repositories;
57 ✔
467
  for (const QString &path : committing) {
117 ✔
468
    const QString repository = repositoryOf(path);
60 ✔
469
    if (!repositories.contains(repository)) {
60 ✔
470
      repositories << repository;
471
    }
472
  }
473
  // pass commits the whole index, not only what it staged: anything staged
474
  // elsewhere goes along.
475
  for (const QString &repository : std::as_const(repositories)) {
114 ✔
476
    for (const QString &entry :
477
         statusEntries({QStringLiteral("--untracked-files=no")}, repository)) {
171 ✔
478
      if (entry.at(0) != QLatin1Char(' ') && !changes.contains(entry)) {
×
479
        changes << entry;
480
      }
481
    }
482
  }
483
  if (changes.isEmpty()) {
57 ✔
484
    return false;
485
  }
486
  QString why =
487
      tr("The folder holds changes Git has not recorded, and pass would "
×
488
         "commit and push them along with this one:\n\n%1\n\nCommit, "
489
         "remove or ignore them with Git first, then try again.")
490
          .arg(namedChanges(changes));
×
491
  // These come back in every folder the file manager opens: removing them
492
  // does not last, ignoring them once does, in the .gitignore of the
493
  // repository that reports them (a folder may hold one of its own).
494
  QStringList writtenAt;
×
495
  const QStringList written = fileManagerFiles(changes, &writtenAt);
×
496
  if (!written.isEmpty()) {
×
497
    const QDir store(QDir::cleanPath(m_settings.passStore));
×
498
    // Each .gitignore with the names its repository reports, alone: a
499
    // rule for a name that is not there could hide something else.
500
    QStringList ignoreFiles;
×
501
    QMap<QString, QStringList> namesFor;
×
502
    for (const QString &path : std::as_const(writtenAt)) {
×
503
      const QString repository = repositoryOf(store.filePath(path));
×
504
      const QString file = repository.isEmpty()
505
                               ? QStringLiteral(".gitignore")
×
506
                               : repository + QStringLiteral("/.gitignore");
×
507
      if (!ignoreFiles.contains(file)) {
×
508
        ignoreFiles << file;
509
      }
510
      const QString name = QFileInfo(path).fileName();
×
511
      if (!namesFor[file].contains(name)) {
×
512
        namesFor[file] << name;
×
513
      }
514
    }
515
    QStringList blocks;
×
516
    for (const QString &file : std::as_const(ignoreFiles)) {
×
517
      blocks << file + QStringLiteral(":\n") +
×
518
                    namesFor.value(file).join(QLatin1Char('\n'));
×
519
    }
520
    why += QStringLiteral("\n\n") +
×
521
           tr("The system writes %1 by itself, in folders a file manager "
×
522
              "opens (Finder on macOS, Explorer on Windows, Dolphin on "
523
              "KDE). Git leaves such files alone in every folder once each "
524
              ".gitignore in the store below holds its lines, committed:"
525
              "\n\n%2")
526
               .arg(written.join(QStringLiteral(", ")),
×
527
                    blocks.join(QStringLiteral("\n\n")));
×
528
  }
×
529
  // As the other refusals: the interface arms when an operation starts and
530
  // is released by processErrorExit(); a refusal starts nothing.
531
  emit startingExecuteWrapper();
×
532
  emit critical(tr("Changes Git has not recorded"), why);
×
533
  emit processErrorExit(1, why);
×
534
  return true;
535
}
536

537
void RealPass::reportUnrecorded(const QStringList &paths) {
36 ✔
538
  QStringList changes;
36 ✔
539
  for (const QString &line : unrecorded(paths, true)) {
72 ✔
540
    // What pass writes: entries and recipient lists. Other ignored files in
541
    // a folder are the user's own business.
542
    if (isStoreFileName(QFileInfo(line.mid(3)).fileName())) {
×
543
      changes << line;
544
    }
545
  }
546
  if (changes.isEmpty()) {
36 ✔
547
    return;
548
  }
549
  emit critical(tr("Saved, not committed"),
×
550
                tr("The change is in the store, but Git did not record it, "
×
551
                   "so it is not pushed, and a pull may overwrite it "
552
                   "(\"!!\" marks a file Git ignores):\n\n%1")
553
                    .arg(namedChanges(changes)));
×
554
}
555

556
auto RealPass::refuseIgnoredThatMoves(const QString &src, const QString &dest)
9 ✔
557
    -> bool {
558
  if (!m_settings.useGit || !QFileInfo(src).isDir()) {
9 ✔
559
    return false;
560
  }
561
  const QDir store(QDir::cleanPath(m_settings.passStore));
×
562
  // pass moves a folder into an existing one, as mv does.
563
  const QString landing = QFileInfo(dest).isDir()
×
564
                              ? QDir(dest).filePath(QFileInfo(src).fileName())
×
565
                              : dest;
×
566
  // Each side in its own repository: where the files lie now, and the one
567
  // pass commits them in.
568
  const QString fromRepository = repositoryOf(src);
×
569
  const QString toRepository = repositoryOf(landing);
×
570
  const QString from =
571
      QDir(fromRepository.isEmpty() ? store.path()
×
572
                                    : store.filePath(fromRepository))
×
573
          .relativeFilePath(QDir::cleanPath(src));
×
574
  const QString to =
575
      QDir(toRepository.isEmpty() ? store.path() : store.filePath(toRepository))
×
576
          .relativeFilePath(QDir::cleanPath(landing));
×
577
  // ls-files names files relative to where git runs, where status names
578
  // them from the repository's root; both are that repository here.
579
  QString out;
×
580
  storeGit(
×
581
      inRepository(fromRepository,
×
582
                   {QStringLiteral("ls-files"), QStringLiteral("-z"),
×
583
                    QStringLiteral("--others"), QStringLiteral("--ignored"),
×
584
                    QStringLiteral("--exclude-standard"), QStringLiteral("--"),
×
585
                    from}),
586
      &out);
587
  QStringList moving;
×
588
  QStringList landed;
×
589
  for (const QString &file : out.split(QChar(0), Qt::SkipEmptyParts)) {
×
590
    if (!file.startsWith(from + QLatin1Char('/')) ||
×
591
        isStoreFileName(QFileInfo(file).fileName())) {
×
592
      continue;
×
593
    }
594
    moving << file;
595
    landed << to + file.mid(from.size());
×
596
  }
597
  if (landed.isEmpty()) {
×
598
    return false;
599
  }
600
  // A rule in a .gitignore inside the folder goes with it, so what it
601
  // ignores stays ignored where it lands, and decides there: deeper rules
602
  // win. Into a folder that is already there, a rule waiting deeper in it
603
  // could undo that, so only the lookup there counts.
604
  QStringList travelling;
×
605
  QStringList rules;
×
606
  if (!QFileInfo::exists(landing) &&
×
607
      checkIgnore(fromRepository, moving, true, &rules)) {
×
608
    for (qsizetype i = 0; i + 3 < rules.size(); i += 4) {
×
609
      if (rules.at(i).startsWith(from + QLatin1Char('/'))) {
×
610
        travelling << rules.at(i + 3);
611
      }
612
    }
613
  }
614
  // A lookup that failed counts nothing as ignored: the move is refused.
615
  QStringList ignoredThere;
×
616
  if (!checkIgnore(toRepository, landed, false, &ignoredThere)) {
×
617
    ignoredThere.clear();
×
618
  }
619
  QStringList exposed;
×
620
  for (qsizetype i = 0; i < landed.size(); ++i) {
×
621
    if (!travelling.contains(moving.at(i)) &&
×
622
        !ignoredThere.contains(landed.at(i))) {
623
      exposed << moving.at(i) + QStringLiteral(" > ") + landed.at(i);
×
624
    }
625
  }
626
  if (exposed.isEmpty()) {
×
627
    return false;
628
  }
629
  const QString why =
630
      tr("Git ignores these files only where they are now, and pass would "
×
631
         "commit and push them where they land:\n\n%1\n\nMove them out of "
632
         "the folder, or have Git ignore them there too, then try again.")
633
          .arg(namedChanges(exposed));
×
634
  emit startingExecuteWrapper();
×
635
  emit critical(tr("Ignored files would be committed"), why);
×
636
  emit processErrorExit(1, why);
×
637
  return true;
638
}
×
639

640
auto RealPass::checkIgnore(const QString &repository, const QStringList &paths,
×
641
                           bool verbose, QStringList *fields) -> bool {
642
  // check-ignore takes -z only with --stdin. Without
643
  // GIT_LITERAL_PATHSPECS (below) a name starting with ':' reads as
644
  // pathspec magic: "./" keeps every name a name. Git answers with the
645
  // name as given.
646
  const QString here = QStringLiteral("./");
×
647
  QString input;
×
648
  for (const QString &path : paths) {
×
649
    input += here + path + QChar(0);
×
650
  }
651
  QStringList args{QStringLiteral("check-ignore"), QStringLiteral("--stdin"),
×
652
                   QStringLiteral("-z")};
×
653
  if (verbose) {
×
654
    args << QStringLiteral("-v");
×
655
  }
656
  // check-ignore refuses every path under GIT_LITERAL_PATHSPECS, which
657
  // the store's environment sets; it takes its paths as names anyway.
658
  QProcessEnvironment environment = storeEnvironment();
×
659
  environment.remove(QStringLiteral("GIT_LITERAL_PATHSPECS"));
×
660
  QProcess lookup;
×
661
  lookup.setProcessEnvironment(environment);
×
662
  QString out;
×
663
  QString err;
×
664
  (void)Executor::executeBlocking(lookup, m_settings.passExecutable,
×
665
                                  QStringList{QStringLiteral("git")} +
×
666
                                      inRepository(repository, args),
×
667
                                  input, &out, &err);
668
  // pass git exits 0 whatever git did: a lookup that failed shows only on
669
  // stderr.
670
  if (!err.trimmed().isEmpty()) {
×
671
    return false;
672
  }
673
  *fields = out.split(QChar(0));
×
674
  if (!fields->isEmpty() && fields->constLast().isEmpty()) {
×
675
    fields->removeLast();
×
676
  }
677
  // The path is every field, or every fourth with -v.
678
  const qsizetype step = verbose ? 4 : 1;
×
679
  for (qsizetype i = step - 1; i < fields->size(); i += step) {
×
680
    if ((*fields)[i].startsWith(here)) {
×
681
      (*fields)[i].remove(0, here.size());
×
682
    }
683
  }
684
  return true;
685
}
×
686

687
void RealPass::Insert(QString file, QString newValue, bool overwrite) {
25 ✔
688
  if (refuseLinkedPath(file + ".gpg")) {
50 ✔
689
    return;
8 ✔
690
  }
691
  const QString entry =
692
      QDir::cleanPath(QDir::isAbsolutePath(file)
693
                          ? file + ".gpg"
45 ✔
694
                          : QDir(m_settings.passStore).filePath(file) + ".gpg");
90 ✔
695
  if (refuseUnverifiedList(entry)) {
23 ✔
696
    return;
697
  }
698
  if (refuseUnfinishedGitOperation() || refusePendingPull() ||
19 ✔
699
      refuseUnrecordedChanges({}, {entry})) {
70 ✔
700
    return;
701
  }
702
  m_insertQueue.enqueue(entry);
703
  // Past every refusal: this insert is now queued and will report once.
704
  queueInsert();
705
  QStringList args = {"insert", "-m"};
85 ✔
706
  if (overwrite) {
17 ✔
707
    args.append("-f");
12 ✔
708
  }
709
  // pass takes every name as one below the store root: an absolute one
710
  // would be saved under <store>/<the whole path>, for the root's list
711
  // rather than the one refuseUnverifiedList() checked.
712
  // A name that starts with a dash is still the entry, not an option.
713
  args.append(QStringLiteral("--"));
17 ✔
714
  args.append(passName(entry, true));
34 ✔
715
  executePass(PASS_INSERT, args, newValue);
34 ✔
716
}
717

718
void RealPass::onDequeuing(int id, bool completes) {
72 ✔
719
  if (id == PASS_INIT || id == PASS_MOVE || id == PASS_COPY) {
72 ✔
720
    // Leaves the queue with its command: a dropped one's scope must not
721
    // pair with the next completion.
722
    const QString scope =
723
        m_reencryptScopes.isEmpty() ? QString() : m_reencryptScopes.dequeue();
40 ✔
724
    if (!completes) {
40 ✔
725
      return;
726
    }
727
    m_reencryptPending.enqueue(scope);
728
    // pass exits 0 when it could not re-encrypt an entry (reencrypt_path
729
    // drops the temporary and carries on), so its exit code says nothing.
730
    // gpg's status lines do, in every locale: on stderr (fd 1 is the
731
    // `gpg -d | gpg -e` pipe), for this one process (Pass resets the
732
    // environment before each start), the last --status-fd winning over a
733
    // user's own; pass's own `--status-fd=1` for verifying a signed
734
    // .gpg-id comes later on its command line and still wins. WSLENV
735
    // already forwards PASSWORD_STORE_GPG_OPTS.
736
    QProcessEnvironment environment = exec.environment();
39 ✔
737
    const QString key = QStringLiteral("PASSWORD_STORE_GPG_OPTS");
39 ✔
738
    environment.insert(
39 ✔
739
        key,
740
        (environment.value(key) + QStringLiteral(" --status-fd 2")).trimmed());
78 ✔
741
    exec.setEnvironment(environment);
39 ✔
742
    return;
743
  }
39 ✔
744
  if (id != PASS_INSERT || m_insertQueue.isEmpty()) {
32 ✔
745
    return;
746
  }
747
  const QString target = m_insertQueue.dequeue();
748
  if (completes) {
17 ✔
749
    m_insertPending.enqueue({target, entryFingerprint(target)});
17 ✔
750
  }
751
}
17 ✔
752

753
auto RealPass::insertWritten(const QString &err) const -> bool {
6 ✔
754
  if (m_insertDone.target.isEmpty()) {
6 ✔
755
    return false;
756
  }
757
  // gpg broke off (a full disk, killed): pass says so, and what gpg left
758
  // at the entry's name, if anything, is no entry. The line is pass's own
759
  // (`die "Password encryption aborted."` after gpg in cmd_insert and
760
  // cmd_edit of password-store.sh), which pass does not translate.
761
  if (err.contains(QLatin1String("Password encryption aborted."))) {
6 ✔
762
    return false;
763
  }
764
  // pass writes the new ciphertext to the entry's name before it commits,
765
  // and an encryption never gives the same bytes twice (a fresh session
766
  // key), so an edited entry has changed as surely as a new one appeared.
767
  const QByteArray after = entryFingerprint(m_insertDone.target);
5 ✔
768
  return !after.isEmpty() && after != m_insertDone.before;
5 ✔
769
}
770

771
auto RealPass::entryFingerprint(const QString &path) -> QByteArray {
22 ✔
772
  QFile file;
22 ✔
773
  if (!Util::openRegularFile(path, file)) {
22 ✔
774
    return {};
13 ✔
775
  }
776
  QCryptographicHash hash(QCryptographicHash::Sha256);
9 ✔
777
  if (!hash.addData(&file)) {
9 ✔
778
    return {};
×
779
  }
780
  return hash.result();
9 ✔
781
}
22 ✔
782

783
void RealPass::Remove(QString file, bool isDir) {
9 ✔
784
  // Nothing behind a link is the store's to delete.
785
  if (refuseLinkedPath(isDir ? file : file + ".gpg", LinkScope::ParentsOnly)) {
24 ✔
786
    return;
6 ✔
787
  }
788
  if (refuseUnfinishedGitOperation() || refusePendingPull()) {
8 ✔
789
    return;
×
790
  }
791
  // pass rm turns a folder into "<folder>/" and rm -rf then follows a link
792
  // and empties its target, so a linked folder is unlinked here and pass's
793
  // git is only asked to forget it. pass rm -f on a linked .gpg unlinks.
794
  const QString full = QDir::cleanPath(m_settings.passStore + file);
8 ✔
795
  if (isDir && Util::isLinkedFolder(full)) {
8 ✔
796
    if (!Util::removeTree(full)) {
5 ✔
797
      const QString why = tr("Could not remove the link %1.").arg(full);
1 ✔
798
      emit critical(tr("Delete failed"), why);
1 ✔
799
      emit processErrorExit(1, why);
1 ✔
800
      return;
801
    }
802
    if (m_settings.useGit) {
4 ✔
803
      // `pass git` exits 0 whatever git did, so ask by output whether git
804
      // knew the link (these quick lookups block; the commit is queued).
805
      const QString rel = QDir(m_settings.passStore).relativeFilePath(full);
4 ✔
806
      // With the store's environment (PASSWORD_STORE_DIR), as executePass.
807
      QString known;
4 ✔
808
      QString err;
4 ✔
809
      // The link is gone from disk either way. A failed lookup or rm leaves
810
      // git tracking it: say so rather than report a clean removal.
811
      bool recorded = Executor::executeBlocking(
28 ✔
812
                          exec.environment(), m_settings.passExecutable,
8 ✔
813
                          {"git", "ls-files", "--", rel}, &known, &err) == 0;
4 ✔
814
      if (recorded && !known.trimmed().isEmpty()) {
12 ✔
815
        recorded =
816
            Executor::executeBlocking(
27 ✔
817
                exec.environment(), m_settings.passExecutable,
6 ✔
818
                {"git", "rm", "-q", "--cached", "--", rel}, &known, &err) == 0;
819
        if (recorded) {
3 ✔
820
          // `pass git commit` is git's commit as it is: pass adds -S only
821
          // to the commits it makes itself, so ask as its git_commit() does.
822
          QString signs;
2 ✔
823
          const bool sign =
824
              Executor::executeBlocking(
26 ✔
825
                  exec.environment(), m_settings.passExecutable,
4 ✔
826
                  {"git", "config", "--bool", "--get", "pass.signcommits"},
827
                  &signs, nullptr) == 0 &&
2 ✔
828
              signs.trimmed() == QLatin1String("true");
4 ✔
829
          QStringList commit{"git", "commit", "-q"};
14 ✔
830
          if (sign) {
2 ✔
831
            commit << "-S";
2 ✔
832
          }
833
          // Queued, as every other commit, so a signer or hook that waits
834
          // (a pinentry, an agent) does not freeze the window; finished()
835
          // judges it by what is left staged, since `pass git` exits 0
836
          // whatever git did.
837
          m_linkCommits.enqueue(
2 ✔
838
              {rel, m_settings.passExecutable, exec.environment()});
839
          executePass(
4 ✔
840
              GIT_COMMIT,
841
              commit + QStringList{"-m", "Remove for " + rel + " using QtPass.",
2 ✔
842
                                   "--", rel});
14 ✔
843
          return;
844
        }
845
      }
846
      if (!recorded) {
2 ✔
847
        const QString why =
848
            tr("The link %1 was removed, but git could not record it: %2")
1 ✔
849
                .arg(rel, err.trimmed());
2 ✔
850
        emit critical(tr("Delete incomplete"), why);
1 ✔
851
        emit processErrorExit(1, why);
1 ✔
852
      }
853
    }
854
    // Nothing ran for pass to finish: the removal is done here, and the
855
    // store changed.
856
    emit finishedRemove(QString(), QString());
4 ✔
857
    return;
2 ✔
858
  }
859
  executePass(PASS_REMOVE, {"rm", (isDir ? "-rf" : "-f"), file});
15 ✔
860
}
18 ✔
861

862
void RealPass::finished(int id, int exitCode, const QString &out,
78 ✔
863
                        const QString &err) {
864
  if (static_cast<PROCESS>(id) == GIT_COMMIT && !m_linkCommits.isEmpty()) {
78 ✔
865
    // Whatever the exit code (pass itself failing, or 0 whatever git
866
    // did), what is left staged decides.
867
    finishLinkCommit(m_linkCommits.dequeue(), out, err);
2 ✔
868
    return;
2 ✔
869
  }
870
  if (static_cast<PROCESS>(id) == PASS_INSERT) {
76 ✔
871
    // This completion's own insert, not whichever left the queue last.
872
    m_insertDone =
873
        m_insertPending.isEmpty() ? InsertRecord{} : m_insertPending.dequeue();
53 ✔
874
  }
875
  const auto pid = static_cast<PROCESS>(id);
76 ✔
876
  if (pid == PASS_INIT || pid == PASS_MOVE || pid == PASS_COPY) {
76 ✔
877
    // Without a recorded scope (not queued through Init/Move/Copy), the
878
    // whole store: held as a whole, released by nothing short of it.
879
    const QString scope =
880
        m_reencryptPending.isEmpty() ? QString() : m_reencryptPending.dequeue();
39 ✔
881
    if (exitCode == 0 && reencryptFailed(out, err)) {
39 ✔
882
      holdAutoPush(scope);
10 ✔
883
      sendDeferredPush();
10 ✔
884
      reportReencryptFailure(pid, out, err);
10 ✔
885
      return;
886
    }
887
    // A run that failed may have stopped after its commit (pass init commits
888
    // the new .gpg-id before re-encrypting; signing it may fail, the process
889
    // may be killed): held as well, until a clean init covers it. A move or
890
    // copy that failed before re-encrypting anything (the destination
891
    // exists, a mistyped name) changed no recipients: not held.
892
    if (exitCode != 0 && (pid == PASS_INIT ||
29 ✔
893
                          out.contains(QLatin1String(": reencrypting to ")))) {
2 ✔
894
      holdAutoPush(scope);
3 ✔
895
    }
896
    // pass init re-encrypts everything under its folder: a clean run
897
    // releases the holds there. A move or copy covers only its entries.
898
    if (pid == PASS_INIT && exitCode == 0 && !scope.isEmpty()) {
29 ✔
899
      releaseAutoPush(scope);
19 ✔
900
    }
901
    if (exitCode == 0 && !scope.isEmpty()) {
29 ✔
902
      reportUnrecorded({scope});
75 ✔
903
    }
904
    sendDeferredPush();
29 ✔
905
    // The status lines are for this check, not for the output panel.
906
    Pass::finished(id, exitCode, out, withoutStatusLines(err));
29 ✔
907
    return;
29 ✔
908
  }
909
  if (pid == PASS_INSERT && exitCode == 0 && !m_insertDone.target.isEmpty()) {
37 ✔
910
    reportUnrecorded({m_insertDone.target});
33 ✔
911
  }
912
  Pass::finished(id, exitCode, out, err);
37 ✔
913
}
914

915
auto RealPass::reencryptFailed(const QString &out, const QString &err) -> bool {
43 ✔
916
  // pass's own line for each entry it re-encrypts ("name: reencrypting to
917
  // KEY..."), which it does not translate; one per line, counted once
918
  // even when the entry's own name holds the words.
919
  const QStringList outLines = out.split(QLatin1Char('\n'));
43 ✔
920
  const auto attempts = std::count_if(
43 ✔
921
      outLines.cbegin(), outLines.cend(), [](const QString &line) {
80 ✔
922
        return line.contains(QLatin1String(": reencrypting to "));
80 ✔
923
      });
924
  qsizetype encrypted = 0;
925
  bool status = false;
926
  for (QString line : err.split(QLatin1Char('\n'))) {
100 ✔
927
    line.remove(QLatin1Char('\r'));
69 ✔
928
    if (!line.startsWith(QLatin1String("[GNUPG:] "))) {
69 ✔
929
      continue;
930
    }
931
    status = true;
932
    // A recipient gpg cannot encrypt to, or a decrypt that failed (no
933
    // secret key, pinentry cancelled, no smartcard): that entry was left
934
    // as it was. KEYEXPIRED and NO_SECKEY alone are not failures.
935
    if (line.startsWith(QLatin1String("[GNUPG:] INV_RECP ")) ||
57 ✔
936
        line.startsWith(QLatin1String("[GNUPG:] FAILURE ")) ||
57 ✔
937
        line.startsWith(QLatin1String("[GNUPG:] DECRYPTION_FAILED"))) {
35 ✔
938
      return true;
939
    }
940
    if (line.startsWith(QLatin1String("[GNUPG:] END_ENCRYPTION"))) {
22 ✔
941
      ++encrypted;
20 ✔
942
    }
943
  }
944
  // Without any status line the option did not reach gpg (a pass that does
945
  // not pass PASSWORD_STORE_GPG_OPTS on): nothing to judge by.
946
  return status && encrypted < attempts;
31 ✔
947
}
948

949
void RealPass::reportReencryptFailure(PROCESS pid, const QString &out,
10 ✔
950
                                      const QString &err) {
951
  QStringList failures;
10 ✔
952
  for (QString line : err.split(QLatin1Char('\n'))) {
52 ✔
953
    line.remove(QLatin1Char('\r'));
32 ✔
954
    // Encrypt-side only: gpgErrorMessage() reads any FAILURE as a key that
955
    // cannot encrypt, wrong advice for a decrypt that failed (no secret
956
    // key, pinentry cancelled), whose reason gpg's own text gives.
957
    if (line.startsWith(QLatin1String("[GNUPG:] INV_RECP ")) ||
54 ✔
958
        line.startsWith(QLatin1String("[GNUPG:] FAILURE encrypt"))) {
54 ✔
959
      failures << line;
960
    }
961
  }
962
  const QString human = withoutStatusLines(err).trimmed();
20 ✔
963
  const QString reason = gpgErrorMessage(failures.join(QLatin1Char('\n')));
20 ✔
964
  QString body =
965
      tr("The recipients were changed, but some entries could not be "
966
         "re-encrypted for them: those are still encrypted to the previous "
967
         "recipients, who can still read them. With Git the change is "
968
         "committed locally and not pushed: QtPass does not push this store "
969
         "automatically until a re-encryption succeeds, and a push by hand "
970
         "sends it.");
971
  for (const QString &part : {reason, human}) {
50 ✔
972
    if (!part.isEmpty()) {
20 ✔
973
      body += QStringLiteral("\n\n") + part;
24 ✔
974
    }
975
  }
30 ✔
976
  // pass's "reencrypting to" lines and gpg's own text, for the output panel.
977
  emit finishedAnyWithPid(out, human, pid);
10 ✔
978
  emit critical(
10 ✔
979
      QCoreApplication::translate("ImitatePass", "Re-encryption failed"), body);
10 ✔
980
  // Not finishedInit/Move/Copy: that would push the store as it now is.
981
  emit processErrorExit(1, body);
10 ✔
982
}
10 ✔
983

984
void RealPass::finishLinkCommit(const LinkCommit &commit, const QString &out,
2 ✔
985
                                const QString &err) {
986
  // In the store the commit ran in, which a profile switch meanwhile does
987
  // not change.
988
  const QString &rel = commit.rel;
2 ✔
989
  QString staged;
2 ✔
990
  const bool committed =
991
      Executor::executeBlocking(
16 ✔
992
          commit.environment, commit.passExecutable,
2 ✔
993
          {"git", "diff", "--cached", "--name-only", "--", rel}, &staged,
994
          nullptr) == 0 &&
4 ✔
995
      staged.trimmed().isEmpty();
2 ✔
996
  if (committed) {
2 ✔
997
    // As Pass::finished() would: git's output (a hook's warning, say) for
998
    // the output panel, then the removal.
999
    emit finishedAnyWithPid(out, err, GIT_COMMIT);
1 ✔
1000
    emit finishedRemove(out, err);
1 ✔
1001
    return;
1002
  }
1003
  const QString why = tr("The link %1 was removed and git no longer tracks "
×
1004
                         "it, but the commit failed: %2")
1005
                          .arg(rel, err.trimmed());
2 ✔
1006
  emit critical(tr("Delete incomplete"), why);
1 ✔
1007
  emit processErrorExit(1, why);
1 ✔
1008
  emit finishedRemove(QString(), QString());
2 ✔
1009
}
2 ✔
1010

1011
void RealPass::Init(QString path, const QList<UserInfo> &users) {
38 ✔
1012
  // A relative path names a folder in the store, as --path does for pass:
1013
  // resolved once, so the checks below look where pass writes, not in the
1014
  // working directory.
1015
  const QString folder = QDir::cleanPath(
1016
      QDir::isAbsolutePath(path) ? path
62 ✔
1017
                                 : QDir(m_settings.passStore).filePath(path));
100 ✔
1018
  // pass init writes .gpg-id with a shell redirection and gpg writes the
1019
  // signature with --output; both follow a link planted under those names.
1020
  // --path is store-relative, or pass creates passStore/passStore/dir: the
1021
  // store check hands it over as it judged it, so a store root reached
1022
  // through a link and a folder spelled through its target agree (a lexical
1023
  // relativeFilePath() made that ../../target/dir, which pass refuses).
1024
  QString dirWithoutPassdir;
38 ✔
1025
  const auto refusePlaced = [this](const QString &placed) {
1026
    return refuseLinkedPath(placed, LinkScope::EntryAndParents,
111 ✔
1027
                            PathSpelling::PlacedByCaller);
1028
  };
1029
  if (refusePlaced(folder) ||
37 ✔
1030
      refusePlaced(folder + QStringLiteral("/.gpg-id")) ||
148 ✔
1031
      refusePlaced(folder + QStringLiteral("/.gpg-id.sig")) ||
183 ✔
1032
      refuseFolderOutsideStore(folder, &dirWithoutPassdir)) {
36 ✔
1033
    return;
1034
  }
1035
  // pass init writes this folder's list and then re-encrypts everything
1036
  // under it to each entry's nearest list, a deeper folder's own included:
1037
  // those are checked as for a move. This folder's list is the one being
1038
  // written, so it is neither verified nor missed. Walked in the store's
1039
  // own spelling: a folder spelled through the target of a linked store
1040
  // root is not under the store as named, and the lookup of each nearest
1041
  // list would stop at once and miss the deeper ones.
1042
  const QString inStore =
1043
      QDir::cleanPath(QDir(m_settings.passStore).filePath(dirWithoutPassdir));
68 ✔
1044
  if (refuseUnverifiedTree(inStore, true,
34 ✔
1045
                           QDir(inStore).filePath(QStringLiteral(".gpg-id")))) {
68 ✔
1046
    return;
1047
  }
1048
  if (refuseUnfinishedGitOperation() || refusePendingPull() ||
31 ✔
1049
      refuseUnrecordedChanges({inStore}, {inStore})) {
186 ✔
1050
    return;
1051
  }
1052
  QStringList args = {"init", "--path=" + dirWithoutPassdir};
93 ✔
1053
  for (const UserInfo &user : users) {
64 ✔
1054
    if (user.enabled) {
33 ✔
1055
      args.append(user.key_id);
32 ✔
1056
    }
1057
  }
1058
  m_reencryptScopes.enqueue(inStore);
1059
  executePass(PASS_INIT, args);
62 ✔
1060
}
31 ✔
1061

1062
void RealPass::Move(const QString src, const QString dest, const bool force) {
15 ✔
1063
  passMoveOrCopy(PASS_MOVE, QStringLiteral("mv"), src, dest, force);
30 ✔
1064
}
15 ✔
1065

1066
void RealPass::Copy(const QString src, const QString dest, const bool force) {
11 ✔
1067
  passMoveOrCopy(PASS_COPY, QStringLiteral("cp"), src, dest, force);
22 ✔
1068
}
11 ✔
1069

1070
auto RealPass::passName(const QString &path, bool stripGpg) const -> QString {
35 ✔
1071
  QString name =
1072
      QDir(QDir::cleanPath(m_settings.passStore))
35 ✔
1073
          .relativeFilePath(QDir::cleanPath(QDir(path).absolutePath()));
70 ✔
1074
  if (stripGpg) {
35 ✔
1075
    name.replace(Util::endsWithGpg(), "");
46 ✔
1076
  }
1077
  return name;
35 ✔
1078
}
1079

1080
void RealPass::passMoveOrCopy(PROCESS id, const QString &subcommand,
26 ✔
1081
                              const QString &src, const QString &dest,
1082
                              const bool force) {
1083
  if (refuseLinkedPath(src) || refuseLinkedPath(dest)) {
26 ✔
1084
    return;
17 ✔
1085
  }
1086
  QFileInfo srcFileInfo = QFileInfo(src);
23 ✔
1087
  QFileInfo destFileInfo = QFileInfo(dest);
23 ✔
1088
  // A drop hands over the folder; pass then writes <folder>/<name>, and cp
1089
  // writes through a link planted under that name.
1090
  if (destFileInfo.isDir() &&
23 ✔
1091
      refuseLinkedPath(QDir(dest).filePath(srcFileInfo.fileName()))) {
51 ✔
1092
    return;
1093
  }
1094

1095
  // pass always forces when called from QtPass, so refuse file-onto-file.
1096
  if (!force && srcFileInfo.isFile() && destFileInfo.isFile()) {
22 ✔
1097
    return;
1098
  }
1099

1100
  // pass re-encrypts what it moves or copies to the destination's list, a
1101
  // folder's entries also to the lists that go along with it, and, when it
1102
  // writes into an existing folder, everything already in that folder too
1103
  // (reencrypt_path on the whole destination).
1104
  if (refuseUnverifiedList(destFileInfo.isDir()
42 ✔
1105
                               ? QDir(dest).filePath(srcFileInfo.fileName())
55 ✔
1106
                               : dest) ||
17 ✔
1107
      (srcFileInfo.isDir() && refuseUnverifiedTree(src, true)) ||
66 ✔
1108
      (destFileInfo.isDir() && refuseUnverifiedTree(dest, false))) {
39 ✔
1109
    return;
1110
  }
1111
  // pass stages what it moved or copied with `git add` on the new path,
1112
  // and a folder brings whatever lies in it along. It commits there, and a
1113
  // move commits the removal where the original was as well.
1114
  const QStringList committing =
1115
      id == PASS_MOVE ? QStringList{src, dest} : QStringList{dest};
30 ✔
1116
  if (refuseUnfinishedGitOperation() || refusePendingPull() ||
27 ✔
1117
      refuseUnrecordedChanges({src, dest}, committing) ||
54 ✔
1118
      refuseIgnoredThatMoves(src, dest)) {
9 ✔
1119
    return;
1120
  }
1121

1122
  // pass appends .gpg itself, so an entry named with it would come out as
1123
  // "name.gpg.gpg"; the destination usually does not exist yet.
1124
  const QString passSrc =
1125
      passName(src, srcFileInfo.isFile() &&
9 ✔
1126
                        srcFileInfo.suffix() == QLatin1String("gpg"));
12 ✔
1127
  const QString passDest =
1128
      passName(dest, !destFileInfo.isDir() &&
9 ✔
1129
                         destFileInfo.suffix() == QLatin1String("gpg"));
13 ✔
1130

1131
  QStringList args;
9 ✔
1132
  args << subcommand;
1133
  if (force) {
9 ✔
1134
    args << "-f";
6 ✔
1135
  }
1136
  args << passSrc;
1137
  args << passDest;
1138
  m_reencryptScopes.enqueue(QDir::cleanPath(QDir(dest).absolutePath()));
18 ✔
1139
  executePass(id, args);
18 ✔
1140
}
23 ✔
1141

1142
// Not `pass grep` (find -L follows links out of the store): the native
1143
// search walks real files only (Util::regularFilesUnder), so it needs gpg.
1144
void RealPass::Grep(QString pattern, bool caseInsensitive) {
2 ✔
1145
  if (m_settings.gpgExecutable.isEmpty()) {
2 ✔
1146
    emit statusMsg(tr("Search needs the GPG executable to be configured."),
1 ✔
1147
                   5000);
1148
    emit finishedGrep({});
1 ✔
1149
    return;
1 ✔
1150
  }
1151
  m_grep.search(pattern, caseInsensitive, m_settings.gpgExecutable,
2 ✔
1152
                m_settings.passStore, exec.environment());
1 ✔
1153
}
1154

1155
void RealPass::executePass(PROCESS id, const QStringList &args, QString input,
72 ✔
1156
                           bool readStdout, bool readStderr) {
1157
  executeWrapper(id, m_settings.passExecutable, args, std::move(input),
72 ✔
1158
                 readStdout, readStderr);
1159
}
72 ✔
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