QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
imitatepass.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
9#include "imitatepass.h"
10#include "entryrecord.h"
11#include "executor.h"
12#include "gpgidgeneration.h"
13#include "passbackendfactory.h"
14#include "util.h"
15#include <QCryptographicHash>
16#include <QDateTime>
17#include <QDir>
18#include <QElapsedTimer>
19#include <QFile>
20#include <QFileInfo>
21#include <QLocale>
22#include <QPointer>
23#include <QProcess>
24#include <QRegularExpression>
25#include <QThread>
26#include <QTimer>
27#include <algorithm>
28#include <utility>
29
30#include "qtpasslogging.h"
31
35using Enums::GIT_ADD;
37using Enums::GIT_COPY;
38using Enums::GIT_INIT;
39using Enums::GIT_MOVE;
40using Enums::GIT_PULL;
41using Enums::GIT_PUSH;
42using Enums::GIT_RM;
44using Enums::INVALID;
53
57
59 // Grep workers wind down meanwhile; m_grep's destructor waits for them.
60 m_grep.cancel();
61 // The re-encryption worker calls members, so join it with no timeout; it
62 // ends its own blocked process on the flag (see execBlocking()).
63 if (m_reencryptThread && m_reencryptThread->isRunning()) {
64 m_reencryptCancel.store(true);
65 m_reencryptThread->wait();
66 }
67}
68
69// The helpers are shared by the owning thread and the worker; thread affinity
70// tells them apart. Only the worker touches its QProcess, so a cancel can
71// never hit an exited process or a reused pid.
72auto ImitatePass::prepareBlocking(QProcess &process)
73 -> const std::atomic_bool * {
74 // In the store's environment: the git ceiling QtPass's own does not
75 // carry.
76 if (QThread::currentThread() == thread()) {
77 process.setProcessEnvironment(storeEnvironment());
78 return nullptr;
79 }
80 process.setProcessEnvironment(withCurrentGitPin(m_reencryptEnv));
81 return &m_reencryptCancel;
82}
83
84auto ImitatePass::execBlocking(const QString &app, const QStringList &args,
85 const QString &input, QString *process_out,
86 QString *process_err) -> int {
87 QProcess process;
88 const std::atomic_bool *cancel = prepareBlocking(process);
89 return Executor::executeBlocking(process, app, args, input, process_out,
90 process_err, cancel);
91}
92
93auto ImitatePass::execBlockingRaw(const QString &app, const QStringList &args,
94 const QByteArray &input,
95 QByteArray *process_out) -> int {
96 QProcess process;
97 const std::atomic_bool *cancel = prepareBlocking(process);
98 return Executor::executeBlockingRaw(process, app, args, input, process_out,
99 nullptr, cancel);
100}
101
102auto ImitatePass::execBlocking(const QString &app, const QStringList &args,
103 QString *process_out, QString *process_err)
104 -> int {
105 return execBlocking(app, args, QString(), process_out, process_err);
106}
107
108auto ImitatePass::translatePathForWsl(const QString &path,
109 const QString &exe) const -> QString {
110 return Executor::translatePathForWsl(path, exe);
111}
112
113auto ImitatePass::storeGit(const QStringList &args, QString *out) -> bool {
114 if (!m_settings.useGit || m_settings.gitExecutable.isEmpty()) {
115 return false;
116 }
117 // -C the store: executeBlocking sets no working directory, so git would
118 // otherwise run in QtPass's launch directory.
119 const QString store = pgit(m_settings.passStore);
120 return execBlocking(m_settings.gitExecutable,
121 QStringList{QStringLiteral("-C"), store} + args, out,
122 nullptr) == 0;
123}
124
125auto ImitatePass::pgit(const QString &path) const -> QString {
126 return translatePathForWsl(path, m_settings.gitExecutable);
127}
128
129auto ImitatePass::pgpg(const QString &path) const -> QString {
130 return translatePathForWsl(path, m_settings.gpgExecutable);
131}
132
136
138 if (gitReady()) {
139 executeGit(GIT_PULL, {"pull"});
140 }
141}
142
143// Blocks until git finishes.
144void ImitatePass::GitPull_b(int timeoutMs) {
145 if (!gitReady())
146 return;
147 // -C the store: executeBlocking sets no working directory, so without it
148 // git would run in QtPass's launch directory and pull an unrelated
149 // repository, or fail with "not a git repository".
150 QString err;
151 QProcess process;
152 const std::atomic_bool *cancel = prepareBlocking(process);
153 QElapsedTimer timer;
154 timer.start();
155 const int rc =
157 {"-C", pgit(m_settings.passStore), "pull"},
158 QString(), nullptr, &err, cancel, timeoutMs);
159 if (rc != 0 && timer.elapsed() >= timeoutMs) {
160 emit statusMsg(pullTimedOut(timeoutMs), 5000);
161 } else if (rc != 0) {
162 emit statusMsg(tr("Git pull failed: %1").arg(err.trimmed()), 5000);
163 }
164}
165
167 // Now it would send the new .gpg-id with entries still encrypted to the
168 // previous recipients, a key just removed among them, also when the run
169 // then fails, and push a clean run twice. The same for a move whose
170 // re-encryption is not decided yet, or waits for the run in flight.
171 if ((m_reencryptActive && !m_reencryptPushing) || !m_pendingMoves.isEmpty() ||
172 !m_movedToReencrypt.isEmpty()) {
175 return;
176 }
177 if (gitReady()) {
178 executeGit(GIT_PUSH, {"push"});
179 }
180}
181
184 !m_movedToReencrypt.isEmpty()) {
185 return;
186 }
187 const bool byHand = m_deferredPushByHand;
188 m_pushAfterReencrypt = false;
189 m_deferredPushByHand = false;
190 if (!byHand && autoPushHeld()) {
191 emit statusMsg(tr("Not pushing: an earlier re-encryption in this "
192 "store did not finish"),
193 5000);
194 return;
195 }
196 GitPush();
197}
198
200 // A run refused at its start (reencryptPath() said why) leaves the next.
201 while (!m_reencryptActive && !m_movedToReencrypt.isEmpty()) {
202 const QString scope = m_movedToReencrypt.takeFirst();
203 // What the user moved is re-encrypted whatever it was encrypted to.
204 m_reencryptTrusted = {QDir::cleanPath(scope)};
205 reencryptPath(scope);
206 if (!m_reencryptActive) {
207 m_reencryptTrusted.clear();
208 // What moved is still encrypted for the recipients it came from: the
209 // automatic push after the move waits, as after a run that did not
210 // finish. A push by hand still goes.
211 holdAutoPush(scope);
212 }
213 }
215}
216
217void ImitatePass::Show(QString file) {
218 if (refuseLinkedPath(file + ".gpg")) {
219 return;
220 }
221 queueShow(file);
222 file = m_settings.passStore + file + ".gpg";
223 QStringList args = {"-d", "--quiet", "--yes", "--no-encrypt-to",
224 "--batch", "--use-agent"};
225 args << maxOutputArgs() << QStringLiteral("--") << pgpg(file);
226 executeGpg(PASS_SHOW, args);
227}
228
229namespace {
230
232constexpr int kReencryptMaxListedFailures = 15;
233
245constexpr QLatin1StringView kUnknownReader("?");
246
247auto encryptArgs(QStringList leading, const QString &output,
248 const QStringList &recipients) -> QStringList {
249 leading << "-eq" << "--compress-algo=none" << "--no-encrypt-to"
250 << "--no-textmode" << "--output" << output;
251 for (const QString &recipient : recipients) {
252 // A bare address as gpg's exact form, not a pattern.
253 leading << "-r" << Pass::exactRecipientArg(recipient);
254 }
255 leading << "-";
256 return leading;
257}
258
259} // namespace
260
261auto ImitatePass::recipientsForEntry(const QString &file,
262 QStringList *recipients) -> bool {
263 recipients->clear();
264 if (refuseSkippedGpgId(file, gpgIdSigner().enabled())) {
265 return false;
266 }
267 QString why;
269 recipients, &why)) {
270 emit critical(tr("Check .gpg-id file signature!"), why);
271 return false;
272 }
273 if (recipients->isEmpty()) {
274 emit critical(tr("Can not edit"),
275 tr("Could not read encryption key to use, .gpg-id "
276 "file missing or invalid."));
277 return false;
278 }
279 return true;
280}
281
283 // The path Insert() writes, read as decryptEntry() reads it; anything
284 // that cannot be told is left to Insert() to refuse or carry out.
285 const QString path =
286 QDir::cleanPath(Util::joinPath(m_settings.passStore, file) + ".gpg");
287 const QFileInfo entry(path);
288 if (!entry.isFile() || entry.isSymLink()) {
289 return {};
290 }
291 const QString gpgIdPath = Pass::getGpgIdPath(path, m_settings.passStore);
292 QStringList recipients;
293 QString why;
294 if (!loadVerifiedRecipients(gpgIdPath, &recipients, &why) ||
295 recipients.isEmpty()) {
296 return {};
297 }
298 QHash<QString, QString> primaries;
299 QHash<QString, QString> names;
300 const std::optional<QSet<QString>> now =
301 keysEncryptedTo(recipients, primaries, names);
302 if (!now || now->contains(kUnknownReader)) {
303 return {};
304 }
305 // With each key's ID: two keys can carry the same name, and a list that
306 // swapped one for the other while the question was open must not read
307 // as unchanged.
308 const auto named = [&names](const QSet<QString> &fprs) {
309 QStringList who;
310 for (const QString &fpr : fprs) {
311 who << (names.contains(fpr) ? QStringLiteral("%1 (%2)").arg(
312 names.value(fpr), fpr.right(16))
313 : fpr.right(16));
314 }
315 who.sort();
316 return who;
317 };
318 // The entry's recipient IDs are written by whoever can push. With signed
319 // lists, an entry whose folder takes a parent's list, at a path this
320 // device never saved, may be a folder renamed past its own list with an
321 // ID added for the attacker: asked about whatever its IDs say.
322 const bool inherited =
323 QDir::cleanPath(gpgIdPath) !=
324 QDir::cleanPath(QDir(entry.absolutePath()).filePath(".gpg-id"));
325 // Never seeded here: what the check finds may be the pusher's renamed
326 // folder. A store not seeded yet knows nothing, so it asks.
327 if (gpgIdSigner().enabled() && inherited && !EntryRecord::known(path)) {
328 return {named(*now), true};
329 }
330 const QStringList ids = getKeysFromFile(path);
331 if (ids.isEmpty()) {
332 return {};
333 }
334 const bool hidden =
335 std::all_of(ids.cbegin(), ids.cend(), [](const QString &id) {
336 return id == QLatin1String("0000000000000000");
337 });
338 if (hidden) {
339 return {{tr("anyone on the list: the entry's recipients cannot be told")},
340 false};
341 }
342 QSet<QString> gaining = *now;
343 gaining.subtract(primaryKeysOf(ids, primaries, names));
344 return {named(gaining), false};
345}
346
347void ImitatePass::Insert(QString file, QString newValue, bool overwrite) {
348 // The dialog names a new entry relative to the store; gpg used to resolve
349 // that in its working directory. Everything below works on the one path.
350 file = QDir::cleanPath(Util::joinPath(m_settings.passStore, file) + ".gpg");
351 if (refuseLinkedPath(file)) {
352 return;
353 }
355 return;
356 }
357 // gpg used to refuse an existing output without --yes; it writes
358 // elsewhere now, so the check is ours here, and again at the rename.
359 const QFileInfo target(file);
360 if (!overwrite && (target.exists() || target.isSymLink())) {
361 emit critical(tr("Cannot add"), tr("%1 already exists.").arg(file));
362 return;
363 }
364 QStringList recipients;
365 if (!recipientsForEntry(file, &recipients)) {
366 return;
367 }
368 // gpg never opens a store path for output: a co-writer could make it a link
369 // after refuseLinkedPath(). gpg writes into a 0700 directory of our own and
370 // placeEncryptedFile() brings the bytes in via an open handle and a rename.
371 auto scratch = std::make_shared<QTemporaryDir>();
372 if (!scratch->isValid()) {
373 emit critical(tr("Cannot write"),
374 tr("Cannot create a temporary directory: %1")
375 .arg(scratch->errorString()));
376 return;
377 }
378 // A line two key blocks hold may encrypt to either. Asked last, so a
379 // refusal for anything else runs no gpg.
380 if (refuseKeyLinesHeldTwice(recipients)) {
381 return;
382 }
383 const QString output = scratch->filePath(QStringLiteral("entry.gpg"));
385 const QStringList args =
386 encryptArgs({"--batch", "--status-fd", "2"}, pgpg(output), recipients);
387 m_pendingInserts.enqueue({std::move(scratch), output, file, overwrite});
388 // Past every refusal: this insert is now queued and will report once.
389 queueInsert(file);
390 executeGpg(PASS_INSERT, args, newValue);
391 if (!gitReady()) {
392 return;
393 }
394 // -f so the store's own .gitignore (a tracked file any co-writer of a
395 // shared store can push) cannot keep an entry untracked. An ignored,
396 // uncommitted entry is expendable to Git: a later pull that needs its path
397 // deletes it, and the typed secret is then in no file and no commit. Edits
398 // are staged too: an entry left ignored and untracked by an older version
399 // would otherwise fail the commit below. On a tracked path the add is a
400 // no-op.
401 executeGit(GIT_ADD, {"add", "-f", "--", pgit(file)});
402 gitCommit(file, QString(overwrite ? "Edit" : "Add") + " for " +
403 commitName(file) + " using QtPass.");
404}
405
406auto ImitatePass::commitArgs() -> QStringList {
407 // As pass's git_commit(): -S when the store (or the user's git config)
408 // sets pass.signcommits. A commit that cannot be signed then fails, as
409 // with pass, rather than going in unsigned.
410 QString out;
411 const bool sign = execBlocking(m_settings.gitExecutable,
412 {"-C", pgit(m_settings.passStore), "config",
413 "--bool", "--get", "pass.signcommits"},
414 &out) == 0 &&
415 out.trimmed() == QLatin1String("true");
416 return sign ? QStringList{"commit", "-S"} : QStringList{"commit"};
417}
418
419void ImitatePass::gitCommit(const QString &file, const QString &msg) {
420 gitCommit(QStringList{file}, msg);
421}
422
423void ImitatePass::gitCommit(const QStringList &files, const QString &msg) {
424 QStringList args = commitArgs() + QStringList{"-m", msg, "--"};
425 for (const QString &file : files) {
426 args << pgit(file);
427 }
428 executeGit(GIT_COMMIT, args);
429}
430
431void ImitatePass::Remove(QString file, bool isDir) {
432 // No trailing separator: "link/" makes git look for what is behind the
433 // link ("pathspec did not match") and rm follow it.
434 file = QDir::cleanPath(m_settings.passStore + file);
435 if (!isDir) {
436 file += ".gpg";
437 }
438 // A link itself may go; anything behind one is not the store's to delete.
440 return;
441 }
443 return;
444 }
445 // As in Move(): no message box inside the transaction, so it holds only
446 // the Git commands.
447 const QString path = commitName(file);
448 if (Util::isLinkedFolder(file)) {
449 // Unlink it here, never through a recursive rm: the link goes, what it
450 // points to stays. Git then only has to forget it, if it knew it.
451 if (!Util::removeTree(file)) {
452 emit critical(tr("Delete failed"),
453 tr("Could not remove the link %1.").arg(file));
454 return;
455 }
456 // Only when git knew it: a commit matching nothing (a link never
457 // committed) exits 1 and reads as a failed removal. ls-files reads the
458 // index, so it still answers now that the link is gone.
459 if (gitReady() && gitTracks(file)) {
461 executeGit(GIT_RM, {"rm", "-q", "--cached", "--", pgit(file)});
462 gitCommit(file, "Remove for " + path + " using QtPass.");
463 }
464 return;
465 }
466 if (gitReady()) {
468 executeGit(GIT_RM, {"rm", (isDir ? "-rf" : "-f"), "--", pgit(file)});
469 gitCommit(file, "Remove for " + path + " using QtPass.");
470 } else {
471 // Without Git nothing else reports a failure: git rm would print its own.
472 if (isDir) {
473 // Never QDir::removeRecursively(): it follows a junction inside the
474 // folder and empties whatever that points to.
475 if (!Util::removeTree(file)) {
476 // As rm -rf, it went on past what it could not remove: the folder
477 // is still there, without the entries that could go.
478 emit critical(tr("Delete failed"),
479 tr("Could not remove all of %1. What could be removed "
480 "is gone; check what is left in it.")
481 .arg(file));
482 }
483 } else {
484 QFile entry(file);
485 if (!entry.remove()) {
486 emit critical(
487 tr("Delete failed"),
488 tr("Could not remove %1: %2").arg(file, entry.errorString()));
489 }
490 }
491 }
492}
493
495 GpgIdSigner signer{m_settings.gpgExecutable,
497 [this](const QString &app, const QStringList &args,
498 const QString &input, QString *out, QString *err) {
499 return execBlocking(app, args, input, out, err);
500 }};
501 signer.setStoreRoot(m_settings.passStore);
502 return signer;
503}
504
505auto ImitatePass::addGenerationHeader(const QString &gpgIdFile,
506 const GpgIdSigner &signer,
507 QByteArray *contents) -> bool {
508 const std::optional<QString> folder =
509 GpgIdGeneration::folderOf(gpgIdFile, m_settings.passStore);
510 if (!folder) {
511 emit critical(tr("Cannot update"),
512 tr("%1 is not inside the password store, or a folder "
513 "name on the way holds a line break or another control "
514 "character, which a signed list cannot record.")
515 .arg(gpgIdFile));
516 return false;
517 }
518 // The list on disk counts only if it is this folder's own, verified list:
519 // a signature vouches for the bytes, the folder line for the place.
520 std::optional<qint64> verifiedOnDisk;
521 std::optional<QString> storeOnDisk;
522 QByteArray current;
523 if (signer.verifyFile(gpgIdFile, &current)) {
524 const auto header = GpgIdGeneration::parse(current);
525 if (header && (!header->folder || *header->folder == *folder)) {
526 verifiedOnDisk = header->generation;
527 // The store's id comes only from a list this store accepts. A refused
528 // one (a rollback, a conflict) may be another store's, signed with
529 // the same key and copied in: taking its id over would make the list
530 // saved now one of that store too. Its generation still counts, so the
531 // next one is above it. Without the record, which it is cannot be
532 // told: a store id made up now could split the store from devices
533 // that know its own.
534 QString unavailable;
536 gpgIdFile, current, m_settings.passStore, &unavailable);
538 emit critical(tr("Cannot update"), unavailable);
539 return false;
540 }
541 if (verdict == GpgIdGeneration::Verdict::Accepted) {
542 storeOnDisk = header->store;
543 }
544 }
545 }
546 QString why;
547 // The store's id: the one this device knows, else the one this store's
548 // lists already carry (#2050).
549 const std::optional<QString> store =
550 GpgIdGeneration::storeIdFor(m_settings.passStore, storeOnDisk, &why);
551 if (!store) {
552 emit critical(tr("Cannot update"), why);
553 return false;
554 }
555 const std::optional<qint64> generation =
556 GpgIdGeneration::reserveNext(gpgIdFile, verifiedOnDisk, &why);
557 if (!generation) {
558 emit critical(tr("Cannot update"), why);
559 return false;
560 }
561 *contents =
562 GpgIdGeneration::withHeader(*generation, *folder, *contents, *store);
563 return true;
564}
565
566auto ImitatePass::writeGpgIdFile(const QString &gpgIdFile,
567 const QList<UserInfo> &users,
568 QByteArray *written) -> bool {
569 QByteArray contents;
570 bool secret_selected = false;
571 for (const UserInfo &user : users) {
572 if (user.enabled) {
573 contents += (user.key_id + "\n").toUtf8();
574 secret_selected |= user.have_secret;
575 }
576 }
577 // Without a signing key the plain list stays (GpgIdGeneration).
578 const GpgIdSigner signer = gpgIdSigner();
579 if (signer.enabled() && !addGenerationHeader(gpgIdFile, signer, &contents)) {
580 return false;
581 }
582 // Whole or not at all, owner-only (it names the store's keys); a link
583 // planted since Init's check is replaced, not written through.
584 QString writeError;
585 if (!Util::writeFileReplacing(gpgIdFile, contents, true, &writeError)) {
586 emit critical(tr("Cannot update"), writeError);
587 return false;
588 }
589 if (written != nullptr) {
590 *written = contents;
591 }
592 if (signer.enabled()) {
593 // From now on these bytes are this generation. The list is signed either
594 // way (unsigned is refused everywhere); if the record could not take them
595 // (another writer, record busy), the user is told to save once more.
596 QString why;
597 if (!GpgIdGeneration::recordWritten(gpgIdFile, contents, &why)) {
598 qCWarning(lcQtPass) << "Could not record the written .gpg-id:" << why;
599 emit critical(
600 tr("Recipient list written, but not recorded"),
601 tr("%1 Save the recipients once more to get through.").arg(why));
602 }
603 }
604 if (!secret_selected) {
605 emit critical(
606 tr("Check selected users!"),
607 tr("None of the selected keys have a secret key available.\n"
608 "You will not be able to decrypt any newly added passwords!"));
609 }
610 return true;
611}
612
613auto ImitatePass::signGpgIdFile(const QString &gpgIdFile,
614 const QByteArray &contents) -> bool {
615 const GpgIdSigner signer = gpgIdSigner();
616 QString why;
617 if (!signer.sign(gpgIdFile, contents, &why)) {
618 emit critical(
619 tr("GPG signing failed!"),
620 why.trimmed().isEmpty()
621 ? tr("Failed to sign %1.").arg(gpgIdFile)
622 : tr("Failed to sign %1: %2").arg(gpgIdFile, why.trimmed()));
623 return false;
624 }
625 QByteArray signedBytes;
626 if (!signer.verifyFile(gpgIdFile, &signedBytes)) {
627 emit critical(tr("Check .gpg-id file signature!"),
628 tr("Signature for %1 is invalid.").arg(gpgIdFile));
629 return false;
630 }
631 return true;
632}
633
634// Synchronous on purpose: queued on the async executor, the add/commit raced
635// reencryptPath()'s blocking backup commit for index.lock and either left the
636// .gpg-id untracked or found nothing to commit.
637auto ImitatePass::gitAddGpgId(const QString &gpgIdFile,
638 const QString &gpgIdSigFile, QString *out,
639 QString *err) -> int {
640 const QString git = m_settings.gitExecutable;
641 const QString store = pgit(m_settings.passStore);
642 auto run = [&](const QStringList &args) -> int {
643 QString runOut;
644 QString runErr;
645 const int rc =
646 execBlocking(git, QStringList{"-C", store} + args, &runOut, &runErr);
647 if (out != nullptr) {
648 out->append(runOut);
649 }
650 if (err != nullptr) {
651 err->append(runErr);
652 }
653 return rc;
654 };
655 QStringList paths{pgit(gpgIdFile)};
656 if (!gpgIdSigFile.isEmpty()) {
657 paths << pgit(gpgIdSigFile);
658 }
659 // add stages new and modified files alike; already-clean ones are a no-op.
660 int rc = run(QStringList{"add", "-f", "--"} + paths);
661 if (rc != 0) {
662 return rc;
663 }
664 // Re-initialising with the same recipients changes nothing; that is not a
665 // failure, and `git commit` would make it one. diff --quiet: 0 nothing
666 // staged, 1 something staged, anything else is git failing.
667 rc = run(QStringList{"diff", "--cached", "--quiet", "--"} + paths);
668 if (rc == 0) {
669 return 0;
670 }
671 if (rc != 1) {
672 return rc;
673 }
674 return run(commitArgs() +
675 QStringList{"-m",
676 "Added " + commitName(gpgIdFile) + " using QtPass.",
677 "--"} +
678 paths);
679}
680
681auto ImitatePass::gitTracks(const QString &file) -> bool {
682 return execBlocking(m_settings.gitExecutable,
683 {"-C", pgit(m_settings.passStore), "ls-files",
684 "--error-unmatch", "--", pgit(file)}) == 0;
685}
686
687auto ImitatePass::refuseLinkedGpgIdFolder(const QString &path) -> bool {
688 // A link planted later is replaced, not written through: the writes stage
689 // and rename.
690 const QString folder = QDir::cleanPath(path);
691 // Init() places a folder spelled through a linked root's target itself.
692 const auto refusePlaced = [this](const QString &placed) {
695 };
696 return refusePlaced(path) ||
697 refusePlaced(folder + QStringLiteral("/.gpg-id")) ||
698 refusePlaced(folder + QStringLiteral("/.gpg-id.sig"));
699}
700
701auto ImitatePass::settleSignature(const QString &gpgIdFile,
702 const QByteArray &written,
703 const GpgIdSigner &signer, bool useGit,
704 QString *sigToCommit) -> bool {
705 const QString gpgIdSigFile = gpgIdFile + ".sig";
706 if (signer.enabled()) {
707 if (!signGpgIdFile(gpgIdFile, written)) {
708 return false;
709 }
710 *sigToCommit = gpgIdSigFile;
711 return true;
712 }
713 if (!QFile::exists(gpgIdSigFile)) {
714 return true;
715 }
716 // Signing was switched off; the removal goes into the same commit.
717 const bool tracked = useGit && gitTracks(gpgIdSigFile);
718 if (!QFile::remove(gpgIdSigFile)) {
719 emit critical(
720 tr("Cannot update"),
721 tr("Failed to remove the old signature %1.").arg(gpgIdSigFile));
722 return false;
723 }
724 if (tracked) {
725 *sigToCommit = gpgIdSigFile;
726 }
727 return true;
728}
729
730auto ImitatePass::fullKeyListing(QString *listing) -> int {
731 QString err;
732 return execBlocking(m_settings.gpgExecutable,
733 {QStringLiteral("--batch"), QStringLiteral("--no-tty"),
734 QStringLiteral("--with-colons"),
735 QStringLiteral("--with-fingerprint"),
736 QStringLiteral("--with-subkey-fingerprint"),
737 QStringLiteral("--list-keys")},
738 listing, &err);
739}
740
741void ImitatePass::Init(QString path, const QList<UserInfo> &users) {
742 // The .gpg-id is written as path + ".gpg-id": without the trailing
743 // separator (the context menu hands over a cleaned path) that would be a
744 // file beside the folder, not the folder's own list. A relative path names
745 // a folder in the store, as it does for pass, not one in the working
746 // directory.
747 path = Util::joinPath(m_settings.passStore, path);
748 // Cleaned before any check: the checks clean what they look at, and the
749 // write must go to the same place. Left as /store/link/../team/, the
750 // system resolves link first and writes beside wherever it points.
751 path = Util::normalizeFolderPath(QDir::cleanPath(path));
752 QString inStore;
753 if (refuseLinkedGpgIdFolder(path) ||
754 refuseFolderOutsideStore(path, &inStore)) {
755 return;
756 }
757 // A pull still queued would land after the new list is written: as with
758 // pass, nothing is changed until it has finished.
760 return;
761 }
762 // From here on in the store's own spelling, the same folder: one spelled
763 // through the target of a linked store root is not under the store as
764 // named, so each entry's nearest list was looked up past the new one and
765 // the entries were encrypted to the store root's.
767 QDir::cleanPath(Util::joinPath(m_settings.passStore, inStore)));
768 const GpgIdSigner signer = gpgIdSigner();
769 const QString gpgIdFile = path + ".gpg-id";
770 if (refuseInitBeforeWrite(gpgIdFile, signer)) {
771 return;
772 }
773 const bool useGit = gitReady();
774 // What the folder's entries were encrypted to until now: the run below
775 // re-encrypts those to the new list and leaves any other for the user.
776 const std::optional<PreviousList> previous = previousListOf(path, gpgIdFile);
777 // A line two key blocks hold may encrypt to either: refused after the
778 // other checks, so a refusal for them runs no gpg, and before anything
779 // is written.
781 return;
782 }
783 QByteArray written;
784 QString sigToCommit;
785 if (!writeGpgIdFile(gpgIdFile, users, &written)) {
786 return;
787 }
788 // The new list is on disk: held from here, so a stop before the run (a
789 // signature that fails, a refused start) leaves it out of a later backup
790 // commit's push; a clean run of this folder releases it.
791 holdAutoPush(path);
792 if (!settleSignature(gpgIdFile, written, signer, useGit, &sigToCommit)) {
793 return;
794 }
795
796 QString gitOut;
797 QString gitErr;
798 if (useGit && m_settings.addGPGId) {
799 // Commit the .gpg-id (and .sig) before re-encrypting to it: the backup
800 // commit only takes tracked files (#1685) and addFolder does not stage
801 // it, so entries were pushed without their recipients file (#1682).
802 const int gitExit = gitAddGpgId(gpgIdFile, sigToCommit, &gitOut, &gitErr);
803 if (gitExit != 0) {
804 reencryptAfterFailedCommit(path, gitExit, gitOut, gitErr, gpgIdFile,
805 previous);
806 return;
807 }
808 }
809 m_writtenGpgId = WrittenGpgId{gpgIdFile, std::move(written)};
810 keepPreviousList(gpgIdFile, previous);
811 reencryptPath(path);
812 if (!m_reencryptActive) {
813 // Refused before it started; reencryptPath() said why. The list it
814 // replaced still tells whom the change removed.
815 m_writtenGpgId.reset();
816 }
817 // finishedInit once the .gpg-id landed in git, as the async path did.
818 if (useGit) {
819 Pass::finished(PASS_INIT, 0, gitOut, gitErr);
820 }
821}
822
824 const QString &gpgIdFile, const std::optional<PreviousList> &previous) {
825 if (m_reencryptActive) {
826 return;
827 }
828 // A list replaced earlier whose run did not finish stays the one to go
829 // by: it, not the one in between, tells whom the changes removed.
830 if (!(m_previousList && m_previousList->gpgIdFile == gpgIdFile)) {
831 m_previousList = previous;
832 }
833}
834
836 const QString &path, int gitExit, const QString &gitOut,
837 const QString &gitErr, const QString &gpgIdFile,
838 const std::optional<PreviousList> &previous) {
839 Pass::finished(PASS_INIT, gitExit, gitOut, gitErr);
840 // The new list is on disk either way. Stopping here left every entry
841 // readable by whoever was just removed from it, so re-encrypt without
842 // Git and say the change is not committed. Putting the old list back
843 // is no way out: with signing the generation record has moved on and
844 // would refuse it as a rollback.
845 const QString why = gitErr.trimmed();
846 keepPreviousList(gpgIdFile, previous);
848 path, why.isEmpty() ? tr("Git exited with code %1.").arg(gitExit) : why);
849}
850
851auto ImitatePass::refuseInitBeforeWrite(const QString &gpgIdFile,
852 const GpgIdSigner &signer) -> bool {
853 // A running re-encryption cannot take a second folder: the new list would
854 // be written and its entries left encrypted to the old recipients, which
855 // for a removed person means they can still read them. Nothing is written.
856 if (m_reencryptActive) {
857 emit critical(tr("Recipients not changed"),
858 tr("A re-encryption is still running. Wait until it has "
859 "finished, then save the recipients again."));
860 return true;
861 }
862 if (signer.enabled() && !signer.haveSecretKey()) {
863 emit critical(tr("No signing key!"),
864 tr("None of the secret signing keys is available.\n"
865 "You will not be able to change the user list!"));
866 return true;
867 }
868
869 // Each name free or a regular file, before anything is written: a folder
870 // named .gpg-id.sig stopped the change after the new list was on disk,
871 // which was then neither committed nor were the entries re-encrypted to
872 // it, while the dialog had closed as if done. Links were refused above.
873 for (const QString &name : {gpgIdFile, gpgIdFile + QStringLiteral(".sig")}) {
874 if (const QFileInfo info(name); info.exists() && !info.isFile()) {
875 emit critical(tr("Recipients not changed"),
876 tr("%1 is not a regular file, so the recipients were not "
877 "changed. Move it out of the way, then save the "
878 "recipients again.")
879 .arg(QDir::toNativeSeparators(name)));
880 return true;
881 }
882 }
883 // The last point before the write: a list that changed since the users
884 // dialog read it is not replaced by the old one plus the change.
885 return refuseChangedList();
886}
887
888auto ImitatePass::previousListOf(const QString &path, const QString &gpgIdFile)
889 -> std::optional<PreviousList> {
890 QStringList before;
892 Pass::getGpgIdPath(QDir(path).filePath(QStringLiteral("x.gpg")),
893 m_settings.passStore),
894 &before, nullptr) &&
895 !before.isEmpty()) {
896 return PreviousList{gpgIdFile, std::move(before)};
897 }
898 return std::nullopt;
899}
900
901auto ImitatePass::loadVerifiedRecipients(const QString &gpgIdFile,
902 QStringList *recipients, QString *why)
903 -> bool {
904 recipients->clear();
905 if (why != nullptr) {
906 *why = tr("Signature for %1 is invalid.").arg(gpgIdFile);
907 }
908 // A link under the .gpg-id name is not the store's list: with signing
909 // off it reads as missing, with signing on verifyFile() refuses it.
910 if (Util::isLinkedFolder(gpgIdFile)) {
911 return !gpgIdSigner().enabled();
912 }
913 QByteArray contents;
914 const GpgIdSigner signer = gpgIdSigner();
915 if (signer.enabled()) {
916 if (!verifySignedList(signer, gpgIdFile, &contents, why)) {
917 return false;
918 }
919 } else {
920 if (const QFileInfo info(gpgIdFile); !info.exists() && !info.isSymLink()) {
921 // No file is not a bad signature; the empty list says it all.
922 return true;
923 }
924 // Bounded, only a regular file, and no folder on the way followed:
925 // see Util::readRegularFileInStore().
926 std::optional<QByteArray> bytes = Util::readRegularFileInStore(
927 m_settings.passStore, gpgIdFile, Util::kMaxGpgIdBytes);
928 if (!bytes) {
929 if (why != nullptr) {
930 *why = tr("%1 cannot be read as a recipient list (a regular file "
931 "of at most %2).")
932 .arg(gpgIdFile,
933 QLocale().formattedDataSize(Util::kMaxGpgIdBytes));
934 }
935 return false;
936 }
937 contents = *std::move(bytes);
938 }
939 *recipients = Pass::parseRecipients(contents, gpgIdFile);
940 return true;
941}
942
943void ImitatePass::reportUnrestorable(const QString &path,
944 QStringList &problems) {
945 problems << tr("%1 is not a regular file and was not restored. Look "
946 "at it and remove it, then re-encrypt again.")
947 .arg(path);
948}
949
950void ImitatePass::dropStaleTemporary(const QString &path) {
951 // A crash's temporary is picked up by a run an hour later.
952 if (QFileInfo(path).lastModified() >
953 QDateTime::currentDateTime().addSecs(-3600)) {
954 qCDebug(lcQtPass) << "Leaving a recent temporary alone:" << path;
955 return;
956 }
957 if (!QFile::remove(path)) {
958 qCWarning(lcQtPass) << "Could not remove stale temporary" << path;
959 }
960}
961
962auto ImitatePass::restoreBackup(const QString &path, QStringList &problems)
963 -> bool {
964 // Belt and braces: the walker only lists regular files.
965 const QFileInfo backup(path);
966 if (backup.isSymLink() || !backup.isFile()) {
967 reportUnrestorable(path, problems);
968 return false;
969 }
970 const QString original =
971 path.chopped(QStringLiteral(".reencrypt.bak").size());
972 if (QFileInfo::exists(original)) {
973 problems << tr("%1 exists next to %2. Both are encrypted copies of the "
974 "entry; check which one you want and delete the other, "
975 "then re-encrypt again.")
976 .arg(path, original);
977 return false;
978 }
979 // Qt's rename opens the destination for writing when a plain rename
980 // fails, and follows a symbolic link holding the name, writing the
981 // backup's bytes wherever the link points: outside the store. A co-writer
982 // can push such a dangling link (it passes the exists() check above, since
983 // its target does not exist yet). Util::replaceFile renames at the path
984 // level and refuses the link itself, never following it.
985 if (!Util::replaceFile(path, original, false)) {
986 problems << tr("%1 is missing and its backup %2 could not be renamed "
987 "back. Rename it by hand, then re-encrypt again.")
988 .arg(original, path);
989 return false;
990 }
991 qCWarning(lcQtPass) << "Restored" << original << "from" << path;
992 emit statusMsg(tr("Restored %1 from the backup an interrupted "
993 "re-encryption left behind.")
994 .arg(original),
995 5000);
996 return true;
997}
998
999auto ImitatePass::recoverReencryptLeftovers(const QString &dir) -> bool {
1000 // .qtpass-XXXXXX.tmp is today's staging name; 1.8.x replaced entries via
1001 // X.gpg.reencrypt.tmp and .bak in two renames, builds up to 2.0 wrote
1002 // X.gpg.XXXXXX.tmp. A .tmp is never a source of truth; a .bak is the only
1003 // copy when X.gpg is missing, and one of two valid ones when it is not.
1004 //
1005 // Regular files only: renaming a link under a leftover name into an entry's
1006 // place would re-encrypt whatever it points to. Links come back in
1007 // `skipped`; linked directories are left to reencryptFiles() to mention.
1008 const QStringList leftoverNames{QStringLiteral(".qtpass-??????.tmp"),
1009 QStringLiteral("*.gpg.reencrypt.tmp"),
1010 QStringLiteral("*.gpg.??????.tmp"),
1011 QStringLiteral("*.gpg.reencrypt.bak")};
1012 const auto isTemporary = [](const QString &path) {
1013 return path.endsWith(QStringLiteral(".tmp"));
1014 };
1015 QStringList skipped;
1016 // Hidden files included: the staged name starts with a dot.
1017 const QStringList leftovers = Util::regularFilesUnder(
1018 QDir::cleanPath(dir), leftoverNames, &skipped, true);
1019 // One report for all of them: a box per leftover opened each from inside
1020 // the one before (a modal box runs the next queued critical()), and a
1021 // store with thousands of them overflowed the stack.
1022 QStringList problems;
1023 for (const QString &path : std::as_const(skipped)) {
1024 if (!QDir::match(leftoverNames, QFileInfo(path).fileName())) {
1025 continue;
1026 }
1027 // Removing a link removes the link, never what it points to; a junction
1028 // or a directory symlink on Windows is a directory entry and goes with
1029 // rmdir.
1030 if (isTemporary(path)) {
1031 if (!QFile::remove(path) && !QDir().rmdir(path)) {
1032 qCWarning(lcQtPass) << "Could not remove stale temporary" << path;
1033 }
1034 continue;
1035 }
1036 reportUnrestorable(path, problems);
1037 }
1038 for (const QString &path : leftovers) {
1039 if (isTemporary(path)) {
1040 dropStaleTemporary(path);
1041 } else {
1042 restoreBackup(path, problems);
1043 }
1044 }
1045 if (problems.isEmpty()) {
1046 return true;
1047 }
1048 const qsizetype count = problems.size();
1049 if (count == 1) {
1050 emit critical(tr("Leftover from an earlier re-encryption"),
1051 problems.first());
1052 return false;
1053 }
1054 QStringList listed = problems.mid(0, kReencryptMaxListedFailures);
1055 if (count > listed.size()) {
1056 listed << tr("... and %n more", nullptr,
1057 static_cast<int>(count - listed.size()));
1058 }
1059 emit critical(tr("Leftovers from an earlier re-encryption"),
1060 tr("%n leftover(s) of an earlier re-encryption need a look "
1061 "before the run can start:",
1062 nullptr, static_cast<int>(count)) +
1063 "\n\n" + listed.join("\n\n"));
1064 return false;
1065}
1066
1067auto ImitatePass::verifyGpgIdForDir(const QString &file,
1068 QHash<QString, QStringList> &verified,
1069 QStringList &gpgId) -> bool {
1070 // Before the cache: two folders can resolve to the same list, and only
1071 // one of them may have had its own.
1072 if (refuseSkippedGpgId(file, gpgIdSigner().enabled())) {
1073 return false;
1074 }
1075 const QString gpgIdPath = Pass::getGpgIdPath(file, m_settings.passStore);
1076 // Keyed by .gpg-id, so every file under it gets exactly the list its
1077 // signature covered.
1078 const auto cached = verified.constFind(gpgIdPath);
1079 if (cached != verified.constEnd()) {
1080 gpgId = cached.value();
1081 return true;
1082 }
1083 QStringList recipients;
1084 QString why;
1085 if (!loadVerifiedRecipients(gpgIdPath, &recipients, &why)) {
1086 // An interrupted gpg is a cancel, not a bad signature.
1087 if (!m_reencryptCancel.load())
1088 emit critical(tr("Check .gpg-id file signature!"), why);
1089 return false;
1090 }
1091 // Once per list, as the cache holds it.
1092 if (refuseKeyLinesHeldTwice(recipients)) {
1093 return false;
1094 }
1095 recipients.sort();
1096 verified.insert(gpgIdPath, recipients);
1097 gpgId = std::move(recipients);
1098 return true;
1099}
1100
1101// From gpg's status lines on stdout, one ENC_TO per recipient, rather than
1102// its human messages on stderr: stderr is capped (Executor::CappedOutput),
1103// and a listing cut short there could match the folder's list while the
1104// entry is still encrypted to a recipient it left out, so its
1105// re-encryption was skipped. stdout is read whole.
1106auto ImitatePass::getKeysFromFile(const QString &fileName) -> QStringList {
1107 // --decrypt, as pass has it: --list-only is an option, not a command, and
1108 // without a command gpg guesses one. A file that is OpenPGP data but not
1109 // encrypted it then saved under the entry's name without ".gpg": in the
1110 // store, and through a link under that name, over an existing file. With
1111 // --decrypt such data goes to standard output, capped at one byte, which
1112 // cannot make a whole status line. "--" keeps a file name that starts with
1113 // a dash from being read as an option.
1114 const QStringList args = {QStringLiteral("--batch"),
1115 QStringLiteral("--no-secmem-warning"),
1116 QStringLiteral("--no-permission-warning"),
1117 QStringLiteral("--decrypt"),
1118 QStringLiteral("--list-only"),
1119 QStringLiteral("--max-output"),
1120 QStringLiteral("1"),
1121 QStringLiteral("--status-fd=1"),
1122 QStringLiteral("--keyid-format=long"),
1123 QStringLiteral("--"),
1124 pgpg(fileName)};
1125 QString status;
1126 QString err;
1127 const int result =
1128 execBlocking(m_settings.gpgExecutable, args, &status, &err);
1129 if (result != 0) {
1130 return {};
1131 }
1132 static const QRegularExpression encTo(
1133 QStringLiteral("^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
1134 QStringList actualKeys;
1135 const QStringList lines =
1136 status.split(Util::newLinesRegex(), Qt::SkipEmptyParts);
1137 for (const QString &line : lines) {
1138 const QRegularExpressionMatch match = encTo.match(line);
1139 if (match.hasMatch()) {
1140 actualKeys << match.captured(1).toUpper();
1141 }
1142 }
1143 actualKeys.sort();
1144 return actualKeys;
1145}
1146
1147namespace {
1148
1157void mapKeyListing(const QString &out, QHash<QString, QString> &primaries,
1158 QHash<QString, QString> &names) {
1159 QString primaryFpr;
1160 QStringList pendingIds;
1161 bool inPrimary = false;
1162 for (const QString &line : out.split(Util::newLinesRegex())) {
1163 const QStringList f = line.split(QLatin1Char(':'));
1164 const QString type = f.value(0);
1165 if (type == QLatin1String("pub")) {
1166 inPrimary = true;
1167 primaryFpr.clear();
1168 pendingIds = {f.value(4).toUpper()};
1169 } else if (type == QLatin1String("sub")) {
1170 inPrimary = false;
1171 pendingIds << f.value(4).toUpper();
1172 } else if (type == QLatin1String("fpr") && inPrimary &&
1173 primaryFpr.isEmpty()) {
1174 primaryFpr = f.value(9).toUpper();
1175 } else if (type == QLatin1String("uid") && !primaryFpr.isEmpty() &&
1176 !names.contains(primaryFpr)) {
1177 names.insert(primaryFpr, Util::displayable(f.value(9), false));
1178 }
1179 if (!primaryFpr.isEmpty()) {
1180 for (const QString &id : std::as_const(pendingIds)) {
1181 if (!id.isEmpty()) {
1182 primaries.insert(id, primaryFpr);
1183 }
1184 }
1185 pendingIds.clear();
1186 }
1187 }
1188}
1189
1190} // namespace
1191
1192auto ImitatePass::primaryKeysOf(const QStringList &ids,
1193 QHash<QString, QString> &primaries,
1194 QHash<QString, QString> &names)
1195 -> QSet<QString> {
1196 // One listing of every public key, on first use: the long ID of each key
1197 // and subkey to the fingerprint of its primary key, and that key's first
1198 // user ID for the question.
1199 if (primaries.isEmpty()) {
1200 QString out;
1201 QString err;
1202 if (execBlocking(m_settings.gpgExecutable,
1203 {QStringLiteral("--batch"),
1204 QStringLiteral("--with-colons"),
1205 QStringLiteral("--fixed-list-mode"),
1206 QStringLiteral("--list-keys")},
1207 &out, &err) == 0) {
1208 mapKeyListing(out, primaries, names);
1209 }
1210 }
1211 // A key gpg does not know (a hidden recipient, one not imported) is no
1212 // one this folder's list can name: left out.
1213 QSet<QString> result;
1214 for (const QString &id : ids) {
1215 const QString fpr = primaries.value(id.toUpper());
1216 if (!fpr.isEmpty()) {
1217 result.insert(fpr);
1218 }
1219 }
1220 return result;
1221}
1222
1223auto ImitatePass::entryHash(const QString &file) const -> QByteArray {
1224 // Read as decryptEntry() reads it: a regular file, no link followed.
1225 const std::optional<QByteArray> bytes = Util::readRegularFileInStore(
1226 m_settings.passStore, file, kMaxPlaintextBytes + 1024LL * 1024);
1227 return bytes ? QCryptographicHash::hash(*bytes, QCryptographicHash::Sha256)
1228 : QByteArray();
1229}
1230
1231auto ImitatePass::keysEncryptedTo(const QStringList &recipients,
1232 QHash<QString, QString> &primaries,
1233 QHash<QString, QString> &names, bool lookUp)
1234 -> std::optional<QSet<QString>> {
1235 // What `-r` makes of the list, groups, `!` suffixes and key lookups
1236 // included: a throwaway encryption with the same arguments as a real one,
1237 // outside the store, read back for its recipients.
1238 QTemporaryDir scratch;
1239 if (!scratch.isValid()) {
1240 return std::nullopt;
1241 }
1242 const QString probe = scratch.filePath(QStringLiteral("probe.gpg"));
1243 // --no-throw-keyids for the probe only: with throw-keyids in gpg.conf it
1244 // would name no one, and nobody would count as gaining.
1245 QStringList leading{QStringLiteral("--yes"), QStringLiteral("--batch"),
1246 QStringLiteral("--no-throw-keyids")};
1247 if (!lookUp) {
1248 leading << QStringLiteral("--no-auto-key-locate");
1249 }
1250 if (execBlockingRaw(m_settings.gpgExecutable,
1251 encryptArgs(std::move(leading), pgpg(probe), recipients),
1252 QByteArrayLiteral("probe"), nullptr) != 0) {
1253 return std::nullopt;
1254 }
1255 const QStringList ids = getKeysFromFile(probe);
1256 if (ids.isEmpty()) {
1257 // gpg encrypted but its recipients could not be read back: someone the
1258 // entry does not reach, as far as anyone can tell.
1259 return QSet<QString>{kUnknownReader};
1260 }
1261 QSet<QString> keys = primaryKeysOf(ids, primaries, names);
1262 // A key gpg encrypted to but did not list (fetched for the probe, say)
1263 // still counts, under its ID: no entry is taken to be readable by it.
1264 for (const QString &id : ids) {
1265 if (!primaries.contains(id.toUpper())) {
1266 keys.insert(id.toUpper());
1267 }
1268 }
1269 return keys;
1270}
1271
1272auto ImitatePass::decryptEntry(const QString &fileName, QByteArray *plaintext,
1273 QString *why) -> bool {
1274 // Read here, without following a link, and handed to gpg on stdin: the
1275 // name was listed as a regular file before the run, and a pull since may
1276 // have put a link there. gpg given the name would follow it, and the
1277 // file it points to would be re-encrypted for this folder's recipients.
1278 // The cap is on what decrypts; the ciphertext of an entry just under it
1279 // is a little larger (packet headers, one session key per recipient).
1280 constexpr qint64 kCiphertextMargin = 1024LL * 1024;
1281 // Every folder on the way down from the store is opened without
1282 // following a link too (readRegularFileUnder()), so none can become one
1283 // between a check and the read. The name may be spelled through the
1284 // target of a linked store root; anything under neither is refused.
1285 constexpr qint64 kMaxCiphertext = kMaxPlaintextBytes + kCiphertextMargin;
1286 const std::optional<QByteArray> ciphertext = Util::readRegularFileInStore(
1287 m_settings.passStore, fileName, kMaxCiphertext);
1288 if (!ciphertext) {
1289 qCDebug(lcQtPass) << "Not a regular file any more, or too large:"
1290 << fileName;
1291 if (why != nullptr) {
1292 *why = tr("%1 is no longer a regular file, or is too large, and was "
1293 "not re-encrypted.")
1294 .arg(fileName);
1295 }
1296 return false;
1297 }
1298 const QStringList args =
1299 QStringList{"-d", "--quiet", "--yes", "--no-encrypt-to",
1300 "--batch", "--use-agent"} +
1301 maxOutputArgs();
1302 if (execBlockingRaw(m_settings.gpgExecutable, args, *ciphertext, plaintext) !=
1303 0 ||
1304 plaintext->isEmpty()) {
1305 qCDebug(lcQtPass) << "Decrypt error on re-encrypt for:" << fileName;
1306 return false;
1307 }
1308 // No newline added: an entry is re-encrypted as it was, as pass(1) does
1309 // (gpg -d | gpg -e); a binary key without one would have grown a byte.
1310 return true;
1311}
1312
1313auto ImitatePass::encryptFor(const QString &output,
1314 const QStringList &recipients,
1315 const QByteArray &plaintext) -> bool {
1316 const QStringList args =
1317 encryptArgs({"--yes", "--batch"}, pgpg(output), recipients);
1318 if (execBlockingRaw(m_settings.gpgExecutable, args, plaintext, nullptr) !=
1319 0) {
1320 qCDebug(lcQtPass) << "Encrypt error on re-encrypt, output:" << output;
1321 return false;
1322 }
1323 return true;
1324}
1325
1326auto ImitatePass::ciphertextHolds(const QString &ciphertext,
1327 const QByteArray &plaintext) -> bool {
1328 QByteArray decrypted;
1329 const QStringList args =
1330 QStringList{"-d", "--quiet", "--batch", "--use-agent"} + maxOutputArgs() +
1331 QStringList{QStringLiteral("--"), pgpg(ciphertext)};
1332 if (execBlockingRaw(m_settings.gpgExecutable, args, QByteArray(),
1333 &decrypted) != 0 ||
1334 decrypted.isEmpty()) {
1335 qCDebug(lcQtPass) << "Verification failed for:" << ciphertext;
1336 return false;
1337 }
1338 // Defence in depth: gpg said it encrypted, and this is what comes back.
1339 // Exact: gpg returns the bytes it was given. Compared as text, the check
1340 // passed for an entry that had lost bytes, as both sides lost the same.
1341 if (decrypted != plaintext) {
1342 qCDebug(lcQtPass) << "Verification content mismatch for:" << ciphertext;
1343 return false;
1344 }
1345 return true;
1346}
1347
1348auto ImitatePass::commitReencrypted(const QString &fileName) -> bool {
1349 if (!reencryptUsesGit()) {
1350 return true;
1351 }
1352 // -C the store so git runs there rather than in QtPass's launch directory
1353 // (executeBlocking sets no working directory).
1354 const QString store = pgit(m_settings.passStore);
1355 if (execBlocking(m_settings.gitExecutable,
1356 {"-C", store, "add", "--", pgit(fileName)}) != 0) {
1357 // The file on disk is re-encrypted correctly; only the repository is
1358 // now behind. Report it so the caller counts this file as failed and
1359 // the run is not pushed.
1360 qCDebug(lcQtPass) << "git add failed after re-encrypting:" << fileName;
1361 return false;
1362 }
1363 const QString path = commitName(fileName);
1364 if (execBlocking(m_settings.gitExecutable,
1365 QStringList{"-C", store} + commitArgs() +
1366 QStringList{"-m",
1367 "Re-encrypt for " + path + " using QtPass.",
1368 "--", pgit(fileName)}) != 0) {
1369 qCDebug(lcQtPass) << "git commit failed after re-encrypting:" << fileName;
1370 return false;
1371 }
1372 return true;
1373}
1374
1375auto ImitatePass::reencryptSingleFile(const QString &fileName,
1376 const QStringList &recipients,
1377 QString *why) -> bool {
1378 qCDebug(lcQtPass) << "reencrypt" << fileName << "for" << recipients.size()
1379 << "recipients";
1380 if (recipients.isEmpty()) {
1381 emit critical(tr("Can not edit"),
1382 tr("Could not read encryption key to use, .gpg-id "
1383 "file missing or invalid."));
1384 return false;
1385 }
1386 QByteArray plaintext;
1387 if (!decryptEntry(fileName, &plaintext, why)) {
1388 return false;
1389 }
1390
1391 // gpg writes outside the store, into a 0700 directory with an unguessable
1392 // name no co-writer can pre-create or link; placeEncryptedFile() then
1393 // replaces the entry in one rename, as in Insert().
1394 QTemporaryDir scratch;
1395 if (!scratch.isValid()) {
1396 qCDebug(lcQtPass) << "Cannot create a scratch directory for re-encrypting"
1397 << fileName;
1398 return false;
1399 }
1400 const QString tempPath = scratch.filePath(QStringLiteral("reencrypted.tmp"));
1401 if (!encryptFor(tempPath, recipients, plaintext) ||
1402 !ciphertextHolds(tempPath, plaintext)) {
1403 return false;
1404 }
1405
1406 // Another client may have removed the entry while gpg ran; the rename
1407 // would bring it back under its old name. Best effort: the check and the
1408 // replace are two steps, as pass's own write is.
1409 const QFileInfo still(fileName);
1410 if (!still.exists() && !still.isSymLink()) {
1411 qCDebug(lcQtPass) << "Entry vanished before it could be replaced:"
1412 << fileName;
1413 return false;
1414 }
1415 if (!placeEncryptedFile(tempPath, fileName, true, why)) {
1416 // Reported once, in the run's summary: an unwritable folder fails every
1417 // entry alike. The old ciphertext stays unless the post-rename check
1418 // failed, and then `why` says so.
1419 if (why != nullptr && !why->contains(fileName)) {
1420 // Every reason but the copy's names the entry; that one names the
1421 // file gpg wrote, in a scratch directory the user never sees.
1422 *why = tr("%1 could not be re-encrypted: %2").arg(fileName, *why);
1423 }
1424 return false;
1425 }
1426 return commitReencrypted(fileName);
1427}
1428
1429namespace {
1439auto listsUnmergedPath(const QString &porcelain) -> bool {
1440 const QStringList lines = porcelain.split(u'\n', Qt::SkipEmptyParts);
1441 for (const QString &line : lines) {
1442 if (line.size() < 2) {
1443 continue;
1444 }
1445 const QChar x = line.at(0);
1446 const QChar y = line.at(1);
1447 if (x == u'U' || y == u'U' || (x == y && (x == u'A' || x == u'D'))) {
1448 return true;
1449 }
1450 }
1451 return false;
1452}
1453} // namespace
1454
1456 if (!reencryptUsesGit()) {
1457 return true;
1458 }
1459 emit statusMsg(tr("Creating backup commit"), 2000);
1460 const QString git = m_settings.gitExecutable;
1461 // -C the store: executeBlocking sets no working directory, so git would
1462 // run in QtPass's launch directory, possibly an unrelated repository.
1463 const QString store = pgit(m_settings.passStore);
1464 // Tracked files only: an untracked plaintext export or swap file must not
1465 // be swept into a commit that autoPush sends to the shared remote.
1466 QString statusOut;
1467 if (execBlocking(
1468 git, {"-C", store, "status", "--porcelain", "--untracked-files=no"},
1469 &statusOut) != 0) {
1470 // An interrupted git is a cancel, not a failure worth a dialog.
1471 if (!m_reencryptCancel.load())
1472 emit critical(
1473 tr("Backup commit failed"),
1474 tr("Could not inspect git status. Re-encryption was aborted."));
1475 return false;
1476 }
1477 // An unresolved conflict needs no merge or rebase in progress: a
1478 // `git stash pop` that conflicted leaves none of the markers the earlier
1479 // checks look for. `add -u` would record the work tree, conflict markers
1480 // and all, as the resolution, and the backup commit would be pushed.
1481 // The repository-wide status, not `ls-files` (which stops at the store's
1482 // folder): `add -u` stages a repository above the store as a whole.
1483 if (listsUnmergedPath(statusOut)) {
1484 if (!m_reencryptCancel.load())
1485 emit critical(tr("Unfinished Git operation"),
1486 tr("The password store's Git repository has unmerged "
1487 "files. Resolve the conflict with Git before "
1488 "re-encrypting."));
1489 return false;
1490 }
1491 // The store only: in a repository above it, a modified tracked file
1492 // outside the store is not the store's to back up, and autoPush would
1493 // publish it. `.` is the store, as git runs with -C the store.
1494 QString storeStatus;
1495 if (execBlocking(git,
1496 {"-C", store, "status", "--porcelain",
1497 "--untracked-files=no", "--", "."},
1498 &storeStatus) != 0) {
1499 if (!m_reencryptCancel.load())
1500 emit critical(
1501 tr("Backup commit failed"),
1502 tr("Could not inspect git status. Re-encryption was aborted."));
1503 return false;
1504 }
1505 if (!storeStatus.trimmed().isEmpty()) {
1506 if (execBlocking(git, {"-C", store, "add", "-u", "--", "."}) != 0 ||
1507 execBlocking(git, QStringList{"-C", store} + commitArgs() +
1508 QStringList{"-m", "Backup before re-encryption",
1509 "--", "."}) != 0) {
1510 if (!m_reencryptCancel.load())
1511 emit critical(tr("Backup commit failed"),
1512 tr("Re-encryption was aborted because a git backup "
1513 "could not be created."));
1514 return false;
1515 }
1516 }
1517 return true;
1518}
1519
1525 int total = 0;
1526 int checked = 0;
1527 int reencrypted = 0;
1528 QStringList rewritten;
1529 QStringList failed;
1532 bool cancelled = false;
1534 bool aborted = false;
1535 QStringList unexpected;
1538 QStringList unexpectedDetails;
1540 QList<QByteArray> unexpectedHashes;
1542 QList<QSet<QString>> unexpectedReaders;
1544 QHash<QString, QSet<QString>> stillReadByRemoved;
1547 QStringList walked;
1548};
1549
1554 std::optional<QSet<QString>> now;
1555 QSet<QString> before;
1556 bool beforeUnknown = false;
1558};
1559
1563 QHash<QString, QString> primaries;
1564 QHash<QString, QString> names;
1565 QHash<QString, ListKeys> lists;
1566};
1567
1570 bool gains = false;
1571 QSet<QString> gaining;
1572 QSet<QString> losing;
1573 QSet<QString> listNow;
1574};
1575
1576namespace {
1578constexpr int kReencryptRetryMs = 100;
1579} // namespace
1580
1581void ImitatePass::reencryptPath(const QString &dir,
1582 const AppSettings &settings) {
1583 if (!m_reencryptActive) {
1584 init(settings);
1585 updateEnv();
1586 }
1587 reencryptPath(dir);
1588}
1589
1590void ImitatePass::reencryptPath(const QString &dir) {
1591 if (m_reencryptActive) {
1592 emit statusMsg(tr("A re-encryption is already running"), 3000);
1593 return;
1594 }
1595 // The store root may be a link; a folder inside that is, or lies behind,
1596 // one is not part of the store. MainWindow refuses it too; this covers
1597 // Init().
1599 emit critical(tr("Not a folder of the store"),
1600 tr("%1 is, or lies behind, a symbolic link or junction. What "
1601 "that points to is not part of the password store and "
1602 "was not re-encrypted.")
1603 .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
1604 emit endReencryptPath();
1605 return;
1606 }
1608 // Re-encrypting now would run createBackupCommit()'s `git add -u` and
1609 // conclude the stopped merge; refuse before the worker starts.
1610 emit endReencryptPath();
1611 return;
1612 }
1613 m_reencryptActive = true;
1614 m_reencryptScope = dir;
1615 m_reencryptCancel.store(false);
1616 emit statusMsg(QFileInfo(dir).isDir()
1617 ? tr("Re-encrypting from folder %1").arg(dir)
1618 : tr("Re-encrypting %1").arg(dir),
1619 3000);
1620 emit startReencryptPath();
1622}
1623
1624// The worker's kill() after the grace period is needed: terminate() is only
1625// SIGTERM, or WM_CLOSE on Windows, which a console gpg ignores.
1627 if (!m_reencryptActive)
1628 return;
1629 m_reencryptCancel.store(true);
1630}
1631
1632// Init(), Move() and Copy() queue async git commands right before
1633// reencryptPath(); the worker's blocking git would fight them for the index
1634// lock, so wait for the queue to drain. The other backend's too: with pass
1635// as the backend an Update's `pass git pull` runs on RealPass's queue, and
1636// the run listed the store while that pull could still change it.
1637void ImitatePass::startReencryptWorker(const QString &dir) {
1638 if (m_reencryptCancel.load()) {
1639 ReencryptResult result;
1640 result.cancelled = true;
1641 finishReencrypt(result);
1642 return;
1643 }
1644 if (!exec.isIdle() || !PassBackendFactory::isIdle()) {
1645 QTimer::singleShot(kReencryptRetryMs, this,
1646 [this, dir]() { startReencryptWorker(dir); });
1647 return;
1648 }
1649 // Re-check now the queue is idle: a pull queued earlier through the
1650 // asynchronous GitPull() may have finished during the wait and left a
1651 // conflict. reencryptPath() checked before scheduling, but that was before
1652 // such a pull could run; starting the worker now would let its backup commit
1653 // conclude the stopped operation. The refusal already reported it, so finish
1654 // as an aborted run (clears m_reencryptActive, emits endReencryptPath).
1656 ReencryptResult result;
1657 result.aborted = true;
1658 finishReencrypt(result);
1659 return;
1660 }
1661
1662 // The worker calls member functions, so `this` must outlive it: the
1663 // destructor cancels and joins m_reencryptThread. `self` only guards the
1664 // queued completion, which may run after the thread object is gone.
1665 QPointer<ImitatePass> self(this);
1666 // The worker's own copy: env is the owning thread's to change meanwhile.
1667 updateEnv();
1669 QThread *thread = QThread::create([this, self = std::move(self), dir]() {
1670 ReencryptResult result = reencryptFiles(dir);
1671 QMetaObject::invokeMethod(
1672 self,
1673 [self, result = std::move(result)]() {
1674 if (self)
1675 self->finishReencrypt(result);
1676 },
1677 Qt::QueuedConnection);
1678 });
1679 m_reencryptThread = thread;
1680 connect(thread, &QThread::finished, this, [this, thread]() {
1681 if (m_reencryptThread == thread)
1682 m_reencryptThread = nullptr;
1683 });
1684 connect(thread, &QThread::finished, thread, &QObject::deleteLater);
1685 thread->start();
1686}
1687
1694 if (!m_settings.autoPull || !reencryptUsesGit()) {
1695 return true;
1696 }
1697 emit statusMsg(tr("Updating password-store"), 2000);
1698 if (execBlocking(m_settings.gitExecutable,
1699 {"-C", pgit(m_settings.passStore), "pull"}) == 0) {
1700 return true;
1701 }
1702 // A pull that could not reach the remote leaves the store as it was; one
1703 // that stopped in a merge leaves conflict markers and an unmerged index,
1704 // and re-encrypting on top of that would commit the mess.
1705 QString unmerged;
1706 if (execBlocking(m_settings.gitExecutable,
1707 {"-C", pgit(m_settings.passStore), "ls-files", "--unmerged"},
1708 &unmerged) != 0) {
1709 // Unknown is not clean: the pull may have stopped in a merge.
1710 emit critical(tr("Git pull failed"),
1711 tr("Could not check the store for unmerged files after the "
1712 "pull. Check it with git before re-encrypting."));
1713 return false;
1714 }
1715 if (!unmerged.trimmed().isEmpty()) {
1716 emit critical(tr("Git pull failed"),
1717 tr("The pull left the store with unmerged files. Resolve "
1718 "the conflict before re-encrypting."));
1719 return false;
1720 }
1721 // A third kind: the fetch got the commits and the checkout then failed at
1722 // one path (a link git could not create, say). Git leaves HEAD and the
1723 // index where they were, but the pulled versions of the other files are
1724 // already in the work tree, and the backup commit would take them as the
1725 // user's own, signed with the user's key. HEAD still behind the upstream
1726 // after a failed pull means the pull may have got that far. No upstream
1727 // (rev-list fails) means there was nothing to merge.
1728 QString behind;
1729 if (execBlocking(m_settings.gitExecutable,
1730 {"-C", pgit(m_settings.passStore), "rev-list", "--count",
1731 "HEAD..@{upstream}"},
1732 &behind) == 0 &&
1733 behind.trimmed().toInt() > 0) {
1734 emit critical(tr("Git pull failed"),
1735 tr("The pull stopped before the store was up to date with "
1736 "its remote, and may have left files of the pulled "
1737 "commits in it. Check the store with git before "
1738 "re-encrypting."));
1739 return false;
1740 }
1741 emit statusMsg(tr("Git pull failed, re-encrypting the store as it is"), 5000);
1742 return true;
1743}
1744
1745auto ImitatePass::entriesToReencrypt(const QString &dir, QStringList *failed)
1746 -> QStringList {
1747 // Regular files only: a symlink or junction is not a password entry, and
1748 // following one would decrypt and rewrite something outside the store.
1749 // One entry (what a move moved): itself, when it is one.
1750 if (const QFileInfo one(dir); !one.isDir()) {
1751 if (one.isFile() && !Util::isLinkedFolder(dir) &&
1752 one.fileName().endsWith(QLatin1String(".gpg"))) {
1753 return {one.filePath()};
1754 }
1755 return {};
1756 }
1757 QStringList skipped;
1758 QStringList unlisted;
1759 // A dot-named entry (.env.gpg) too, as with `pass init`: left out, it
1760 // stayed encrypted to a recipient just removed while the run reported
1761 // success. A hidden folder (.git, a sync tool's .stversions) stays closed.
1762 const QStringList files = Util::regularFilesUnder(
1763 dir, QStringList() << "*.gpg", &skipped, true, &unlisted);
1764 // A folder that cannot be read looked empty, and the run reported success
1765 // over it with its entries still encrypted to the old recipients (a key
1766 // just removed among them). Each is a failure: the dialog names it and
1767 // nothing is pushed.
1768 for (const QString &folder : std::as_const(unlisted)) {
1769 *failed << tr("%1 could not be read: its entries were not re-encrypted")
1770 .arg(QDir::toNativeSeparators(folder));
1771 }
1772 if (!skipped.isEmpty()) {
1773 emit statusMsg(tr("%n entr(y/ies) skipped: a symlink, junction or special "
1774 "file is not part of the store.",
1775 "", static_cast<int>(skipped.size())),
1776 5000);
1777 }
1778 return files;
1779}
1780
1781auto ImitatePass::recipientsForDir(const QString &fileName,
1782 QHash<QString, QStringList> &verified,
1783 QStringList &gpgId, ReencryptResult &result)
1784 -> bool {
1785 if (!verifyGpgIdForDir(fileName, verified, gpgId)) {
1786 if (m_reencryptCancel.load()) {
1787 result.cancelled = true;
1788 } else {
1789 result.aborted = true;
1790 }
1791 return false;
1792 }
1793 if (gpgId.isEmpty() && !verified.isEmpty()) {
1794 emit critical(tr("GPG ID verification failed"),
1795 tr("Could not verify .gpg-id for directory."));
1796 result.aborted = true;
1797 return false;
1798 }
1799 return true;
1800}
1801
1802// Worker thread: only blocking helpers, nothing touching `exec` or the
1803// transaction state; signals reach the GUI queued. A helper failing while the
1804// cancel flag is set was interrupted: its file is neither checked nor failed.
1806 ReencryptResult result;
1807 if (!startReencryptRun(dir, result)) {
1808 return result;
1809 }
1810
1811 QStringList files = entriesToReencrypt(dir, &result.failed);
1812 // A run the user agreed to takes the entries they were shown, no more.
1813 if (!m_reencryptAgreed.isEmpty()) {
1814 files.erase(std::remove_if(files.begin(), files.end(),
1815 [this](const QString &file) {
1816 return !m_reencryptAgreed.contains(file);
1817 }),
1818 files.end());
1819 }
1820 result.total = static_cast<int>(files.size());
1821 emit reencryptProgress(0, result.total);
1822
1823 QString currentDir;
1824 QHash<QString, QStringList> gpgIdFilesVerified;
1825 QStringList gpgId;
1826 WhoReads who;
1827 for (const QString &fileName : std::as_const(files)) {
1828 if (m_reencryptCancel.load()) {
1829 result.cancelled = true;
1830 break;
1831 }
1832 const QString fileDir = QFileInfo(fileName).path();
1833 if (fileDir != currentDir) {
1834 if (!recipientsForDir(fileName, gpgIdFilesVerified, gpgId, result)) {
1835 return result;
1836 }
1837 currentDir = fileDir;
1838 }
1839 if (!reencryptEntry(fileName, gpgId, who, result)) {
1840 result.cancelled = true;
1841 break;
1842 }
1843 result.checked++;
1844 emit reencryptProgress(result.checked, result.total);
1845 }
1846 return result;
1847}
1848
1849auto ImitatePass::startReencryptRun(const QString &dir, ReencryptResult &result)
1850 -> bool {
1851 if (!pullBeforeReencrypt()) {
1852 result.aborted = true;
1853 return false;
1854 }
1855 // The GUI-thread checks ran before this worker's own pull.
1856 // pullBeforeReencrypt refuses an unmerged index, but a pull that stopped in a
1857 // rebase can leave a rebase-merge/rebase-apply state with no unmerged entry
1858 // yet; the backup commit's `git add -u` would then conclude it. Re-check
1859 // here, before any write, with the non-emitting detection (the refusal is
1860 // reported once, as an aborted run).
1861 if (const QString midOp = unfinishedGitOperationReason(); !midOp.isEmpty()) {
1862 if (!m_reencryptCancel.load()) {
1863 emit critical(tr("Unfinished Git operation"), midOp);
1864 }
1865 result.aborted = true;
1866 return false;
1867 }
1868 // reencryptPath() checked the folder before the pull; a pulled commit can
1869 // have made it, or a folder above it, a link since. Recovery and the walk
1870 // below would then rename and remove files beyond the store.
1871 if (Util::isUnderLink(dir, m_settings.passStore)) {
1872 emit critical(tr("Not part of the store"),
1873 tr("%1 is, or lies behind, a symbolic link or junction "
1874 "after pulling. What that points to is not part of the "
1875 "password store and is left alone.")
1876 .arg(QDir::toNativeSeparators(QDir::cleanPath(dir))));
1877 result.aborted = true;
1878 return false;
1879 }
1880
1881 // Init() wrote the recipients the user ticked and committed them. A pull
1882 // that merged another change to the same list cleanly (a line removed
1883 // here, one added there) would have the run encrypt to keys nobody chose
1884 // in the dialog, and without a signing key nothing else notices.
1885 if (m_writtenGpgId) {
1886 const std::optional<QByteArray> now = Util::readRegularFileInStore(
1888 if (!now || *now != m_writtenGpgId->bytes) {
1889 if (!m_reencryptCancel.load()) {
1890 emit critical(
1891 tr("Recipients changed by the pull"),
1892 tr("The pull changed the recipients of %1 after you saved "
1893 "them, so nothing was re-encrypted: entries in it may still "
1894 "be encrypted to the previous recipients, and anyone you "
1895 "just removed may still be able to read them. Open the users "
1896 "dialog for that folder again, check the recipients, and "
1897 "save.")
1898 .arg(QDir::toNativeSeparators(
1899 QFileInfo(m_writtenGpgId->file).path())));
1900 }
1901 result.aborted = true;
1902 return false;
1903 }
1904 }
1905
1906 // Leftovers of an interrupted run first: a restored entry then goes into
1907 // the backup commit like everything else, and a stale temporary does not.
1908 if (!recoverReencryptLeftovers(dir)) {
1909 result.aborted = true;
1910 return false;
1911 }
1912
1913 if (!createBackupCommit()) {
1914 if (m_reencryptCancel.load()) {
1915 result.cancelled = true;
1916 } else {
1917 result.aborted = true;
1918 }
1919 return false;
1920 }
1921 return true;
1922}
1923
1924auto ImitatePass::isTrustedEntry(const QString &fileName,
1925 const QSet<QString> &listNow) const -> bool {
1926 // What the user moved or copied in is taken as it is; what they agreed to
1927 // in reencryptAlso() only while its bytes are the ones they were shown.
1928 if (std::any_of(m_reencryptTrusted.cbegin(), m_reencryptTrusted.cend(),
1929 [&fileName](const QString &trusted) {
1930 return fileName == trusted ||
1931 fileName.startsWith(trusted + QLatin1Char('/'));
1932 })) {
1933 return true;
1934 }
1935 const auto agreed = m_reencryptAgreed.constFind(fileName);
1936 // An entry that cannot be read as a regular file hashes to nothing,
1937 // which matches no agreement.
1938 return agreed != m_reencryptAgreed.constEnd() && !agreed->hash.isEmpty() &&
1939 agreed->readers == listNow && entryHash(fileName) == agreed->hash;
1940}
1941
1942auto ImitatePass::listKeysFor(const QString &gpgIdPath,
1943 const QStringList &gpgId, WhoReads &who)
1944 -> const ListKeys & {
1945 if (const auto known = who.lists.constFind(gpgIdPath);
1946 known != who.lists.constEnd()) {
1947 return *known;
1948 }
1949 ListKeys fresh;
1950 fresh.now = keysEncryptedTo(gpgId, who.primaries, who.names);
1951 std::optional<QSet<QString>> before = fresh.now;
1952 if (m_previousList && m_previousList->gpgIdFile == gpgIdPath) {
1953 before = keysEncryptedTo(m_previousList->recipients, who.primaries,
1954 who.names, false);
1955 }
1956 // A previous list gpg cannot encrypt to, or one whose probe names
1957 // nobody it can tell, exempts no one, and leaves unknown who was
1958 // taken off it.
1959 if (before && before->contains(kUnknownReader)) {
1960 before.reset();
1961 }
1962 fresh.before = before ? *before : fresh.now.value_or(QSet<QString>());
1963 fresh.beforeUnknown = !before;
1964 return *who.lists.insert(gpgIdPath, fresh);
1965}
1966
1967auto ImitatePass::readerChangeOf(const QString &fileName,
1968 const QStringList &keys, const ListKeys &lk,
1969 WhoReads &who) -> ReaderChange {
1970 ReaderChange change;
1971 if (!lk.now) {
1972 return change;
1973 }
1974 change.listNow = *lk.now;
1975 const QSet<QString> readers = primaryKeysOf(keys, who.primaries, who.names);
1976 change.gaining = *lk.now;
1977 change.gaining.subtract(readers);
1978 // Whom this change added gains every entry of the folder, as it
1979 // should.
1980 QSet<QString> added = *lk.now;
1981 added.subtract(lk.before);
1982 change.gaining.subtract(added);
1983 change.gains = !change.gaining.isEmpty();
1984 // Who was taken off the list and still reads it, if it is skipped:
1985 // by this change, or by an earlier one that left it so (and is not
1986 // back on it now).
1987 QSet<QString> removed = lk.before;
1988 removed.unite(m_removedReaders.value(fileName));
1989 removed.subtract(*lk.now);
1990 if (lk.beforeUnknown) {
1991 removed.insert(kUnknownReader);
1992 }
1993 // A recipient ID that names no known key (hidden by throw-keyids,
1994 // or not in the keyring) may be anyone removed. When every ID is
1995 // known, only those removed who are among them still read it.
1996 const bool readersKnown =
1997 std::all_of(keys.cbegin(), keys.cend(), [&who](const QString &id) {
1998 return who.primaries.contains(id.toUpper());
1999 });
2000 if (!readersKnown) {
2001 change.losing = std::move(removed);
2002 } else {
2003 change.losing = readers;
2004 change.losing.intersect(removed);
2005 // Who was taken off is not known (an old list gpg could not
2006 // encrypt to, or an earlier run that could not tell): any
2007 // reader no longer on the list may be one.
2008 if (removed.contains(kUnknownReader)) {
2009 QSet<QString> off = readers;
2010 off.subtract(*lk.now);
2011 change.losing.unite(off);
2012 }
2013 }
2014 return change;
2015}
2016
2017auto ImitatePass::namedReaders(const QSet<QString> &fprs,
2018 const QHash<QString, QString> &names)
2019 -> QString {
2020 QStringList who;
2021 for (const QString &fpr : fprs) {
2022 if (fpr == kUnknownReader) {
2023 who << tr("a recipient gpg does not name");
2024 continue;
2025 }
2026 who << names.value(fpr, fpr.right(16));
2027 }
2028 who.sort();
2029 return who.join(QStringLiteral(", "));
2030}
2031
2032auto ImitatePass::holdForAgreement(const QString &fileName,
2033 const QStringList &keys,
2034 const ReaderChange &change,
2035 const WhoReads &who, ReencryptResult &result)
2036 -> bool {
2037 const QByteArray shownHash = entryHash(fileName);
2038 if (shownHash.isEmpty()) {
2039 // gpg lists its recipients, but its bytes cannot be held to a yes
2040 // (over the read cap, or no longer a regular file): reported as
2041 // left, not asked about, or the question would come back after
2042 // every yes.
2043 result.failed << tr("%1 was not re-encrypted: it would become "
2044 "readable by %2, and it cannot be read to ask "
2045 "about it (too large, or not a regular file).")
2046 .arg(fileName,
2047 namedReaders(change.gaining, who.names));
2048 if (!change.losing.isEmpty()) {
2049 result.stillReadByRemoved.insert(fileName, change.losing);
2050 }
2051 return true;
2052 }
2053 const bool hidden =
2054 !keys.isEmpty() &&
2055 std::all_of(keys.cbegin(), keys.cend(), [](const QString &id) {
2056 return id == QLatin1String("0000000000000000");
2057 });
2058 result.unexpected << fileName;
2059 result.unexpectedHashes << shownHash;
2060 result.unexpectedReaders << change.listNow;
2061 QString detail = hidden
2062 ? tr("its recipients cannot be told (hidden key IDs); "
2063 "it would become readable by %1")
2064 .arg(namedReaders(change.gaining, who.names))
2065 : tr("would become readable by %1")
2066 .arg(namedReaders(change.gaining, who.names));
2067 if (!change.losing.isEmpty()) {
2068 // Named only where the entry's recipients say so; otherwise it
2069 // may be.
2070 detail +=
2071 QStringLiteral("; ") +
2072 (change.losing.contains(kUnknownReader) ||
2073 !std::all_of(keys.cbegin(), keys.cend(),
2074 [&who](const QString &id) {
2075 return who.primaries.contains(id.toUpper());
2076 })
2077 ? tr("may still be readable by someone taken off "
2078 "the list")
2079 : tr("still readable by %1, who was removed")
2080 .arg(namedReaders(change.losing, who.names)));
2081 result.stillReadByRemoved.insert(fileName, change.losing);
2082 }
2083 result.unexpectedDetails << detail;
2084 return false;
2085}
2086
2087auto ImitatePass::reencryptEntry(const QString &fileName,
2088 const QStringList &gpgId, WhoReads &who,
2089 ReencryptResult &result) -> bool {
2090 // A pull since the listing may have put a link under the name, or in
2091 // place of a folder on the way to it. gpg given the name reads the
2092 // target, and one already encrypted for these recipients would pass the
2093 // comparison without a word.
2094 bool keepRecord = false;
2095 const QFileInfo entry(fileName);
2096 if (entry.isSymLink() || !entry.isFile() ||
2097 Util::isUnderLink(fileName, m_settings.passStore)) {
2098 result.failed << tr("%1 is no longer a regular file, or lies behind a "
2099 "link, and was not re-encrypted.")
2100 .arg(fileName);
2101 } else if (const QStringList keys = getKeysFromFile(fileName);
2102 keys != gpgId) {
2103 // Re-encrypting hands the entry to this folder's recipients. Someone
2104 // on the list who cannot read it yet, and whom this change did not
2105 // add, gains it: an entry copied in from a folder they cannot read
2106 // is left for the user to agree to. Taking readers away (a removed
2107 // recipient, a rotated subkey) needs no question. Who reads it now is
2108 // what its recipient IDs say, which a writer can add to: this stops a
2109 // copy, not a crafted entry (SECURITY.md).
2110 ReaderChange change;
2111 // No recipients gpg can list: not an entry it can decrypt either, so
2112 // the attempt below fails without handing anything over.
2113 if (!keys.isEmpty()) {
2114 change = readerChangeOf(
2115 fileName, keys,
2116 listKeysFor(Pass::getGpgIdPath(fileName, m_settings.passStore), gpgId,
2117 who),
2118 who);
2119 }
2120 if (m_reencryptCancel.load()) {
2121 return false;
2122 }
2123 QString why;
2124 if (change.gains && !isTrustedEntry(fileName, change.listNow)) {
2125 keepRecord = holdForAgreement(fileName, keys, change, who, result);
2126 } else if (reencryptSingleFile(fileName, gpgId, &why)) {
2127 result.reencrypted++;
2128 result.rewritten << fileName;
2129 } else if (m_reencryptCancel.load()) {
2130 // Interrupted by the cancel: the file is untouched, not failed.
2131 return false;
2132 } else {
2133 // The reason names the entry itself when there is one to give.
2134 result.failed << (why.isEmpty() ? fileName : why);
2135 // Not rewritten: whoever was removed still reads it.
2136 keepRecord = true;
2137 }
2138 }
2139 if (!keepRecord) {
2140 result.walked << fileName;
2141 }
2142 return true;
2143}
2144
2145// No push after a cancel, abort or per-file failure: a partially re-encrypted
2146// store must not reach the remote before the user inspects it.
2148 // Written by this device now, under the list they were re-encrypted to.
2151 // A run of only the entries the user agreed to settles those, not the
2152 // rest of the folder's holds (settleAutoPushHold()).
2153 const bool agreedRun = !m_reencryptAgreed.isEmpty();
2154 const bool stillRead = settleAutoPushHold(result, agreedRun);
2155 reportReencryptOutcome(result, stillRead);
2156 if (m_uncommittedGpgId) {
2157 const UncommittedGpgId uncommitted = *m_uncommittedGpgId;
2158 m_uncommittedGpgId.reset();
2159 reportUncommittedGpgId(uncommitted.folder, uncommitted.gitError,
2160 !result.cancelled && !result.aborted &&
2161 result.failed.isEmpty() &&
2162 result.unexpected.isEmpty());
2163 }
2164 m_writtenGpgId.reset();
2165 // Whom the change removed is known only from the list it replaced: kept
2166 // until a full run of the folder has judged every entry, so a cancelled
2167 // or stopped one does not forget it.
2168 if (!result.cancelled && !result.aborted && !agreedRun) {
2169 m_previousList.reset();
2170 }
2171 m_reencryptTrusted.clear();
2172 m_reencryptAgreed.clear();
2173 rememberUnexpected(result);
2174 // No push after a cancel or abort; otherwise one asked for meanwhile is
2175 // still to make (by a run to come, or once a pending move settles).
2176 if (result.cancelled || result.aborted) {
2177 m_pushAfterReencrypt = false;
2178 m_deferredPushByHand = false;
2179 }
2180 const QString scope = m_reencryptScope;
2181 m_reencryptActive = false;
2182 emit endReencryptPath();
2183 // Asked after the run is over, so the interface is free for the question;
2184 // the entries were not touched, so nothing waits on the answer.
2185 if (!result.unexpected.isEmpty() && !result.cancelled && !result.aborted) {
2186 emit unexpectedRecipients(scope, result.unexpected,
2187 result.unexpectedDetails);
2188 }
2190}
2191
2192void ImitatePass::reportFailedEntries(const QStringList &failed) {
2193 if (failed.isEmpty()) {
2194 return;
2195 }
2196 QStringList listed = failed.mid(0, kReencryptMaxListedFailures);
2197 const int more = static_cast<int>(failed.size() - listed.size());
2198 if (more > 0) {
2199 listed << tr("... and %n more", nullptr, more);
2200 }
2201 emit critical(tr("Re-encryption failed"),
2202 tr("%n file(s) could not be re-encrypted:", nullptr,
2203 static_cast<int>(failed.size())) +
2204 "\n\n" + listed.join('\n'));
2205}
2206
2208 bool agreedRun) -> bool {
2209 // The recipients change is committed already: a run that did not finish
2210 // leaves entries for the previous recipients, which the next automatic
2211 // push (after any edit) would publish with it. A clean run releases only
2212 // the holds of what it covered. Also without Git: a recipients change
2213 // left uncommitted now is swept into a later commit (the next run's
2214 // backup commit) once Git is on, and pushed with it.
2215 // An entry left alone that a removed recipient still reads keeps the
2216 // automatic push waiting, as a failed one does: the change is not done.
2217 // Kept per entry across runs, until one re-encrypts it, finds nobody
2218 // removed reading it, or it is gone. A run of only the entries the user
2219 // agreed to settles those, not the rest of the folder's holds.
2220 for (const QString &file : result.walked) {
2221 m_removedReaders.remove(file);
2222 }
2223 for (auto it = result.stillReadByRemoved.cbegin();
2224 it != result.stillReadByRemoved.cend(); ++it) {
2225 m_removedReaders.insert(it.key(), it.value());
2226 }
2227 for (auto it = m_removedReaders.begin(); it != m_removedReaders.end();) {
2228 it = QFileInfo::exists(it.key()) ? std::next(it)
2229 : m_removedReaders.erase(it);
2230 }
2231 const QString heldScope = QDir::cleanPath(m_reencryptScope);
2232 const QString heldPrefix = heldScope + QLatin1Char('/');
2233 const bool stillRead =
2234 std::any_of(m_removedReaders.keyBegin(), m_removedReaders.keyEnd(),
2235 [&heldScope, &heldPrefix](const QString &file) {
2236 return file == heldScope || file.startsWith(heldPrefix);
2237 });
2238 if (result.cancelled || result.aborted || !result.failed.isEmpty() ||
2239 stillRead) {
2241 } else if (!agreedRun) {
2243 }
2244 return stillRead;
2245}
2246
2248 bool stillRead) {
2249 if (result.cancelled) {
2250 emit statusMsg(tr("Re-encryption cancelled: %1 of %2 files checked, "
2251 "%3 re-encrypted, %4 failed")
2252 .arg(result.checked)
2253 .arg(result.total)
2254 .arg(result.reencrypted)
2255 .arg(result.failed.size()),
2256 5000);
2257 } else if (!result.aborted) {
2258 if (!result.failed.isEmpty()) {
2259 emit statusMsg(tr("Re-encryption completed: %1 succeeded, %2 failed")
2260 .arg(result.reencrypted)
2261 .arg(result.failed.size()),
2262 5000);
2263 } else {
2264 emit statusMsg(tr("Re-encryption completed: %1 files re-encrypted")
2265 .arg(result.reencrypted),
2266 3000);
2267 }
2268 // With a moved entry's run still to come, that one pushes at its end.
2269 if (m_movedToReencrypt.isEmpty() &&
2271 m_pushAfterReencrypt = false;
2272 m_deferredPushByHand = false;
2273 if (stillRead) {
2274 emit statusMsg(tr("Not pushing: an entry left as it is is still "
2275 "readable by a removed recipient"),
2276 5000);
2277 } else if (result.failed.isEmpty() && autoPushHeld()) {
2278 // Clean here, but another folder's run did not finish.
2279 emit statusMsg(tr("Not pushing: an earlier re-encryption in this "
2280 "store did not finish"),
2281 5000);
2282 } else if (result.failed.isEmpty()) {
2283 emit statusMsg(tr("Updating password-store"), 2000);
2284 m_reencryptPushing = true;
2285 GitPush();
2286 m_reencryptPushing = false;
2287 } else {
2288 emit statusMsg(tr("Not pushing: %n file(s) failed to re-encrypt",
2289 nullptr, static_cast<int>(result.failed.size())),
2290 5000);
2291 }
2292 }
2293 }
2294}
2295
2297 // What was named, with the bytes it was named for: reencryptAlso() holds
2298 // the user's yes to those.
2299 m_lastUnexpected.clear();
2300 for (qsizetype i = 0; i < result.unexpected.size(); ++i) {
2301 m_lastUnexpected.insert(result.unexpected.at(i),
2302 Agreed{result.unexpectedHashes.value(i),
2303 result.unexpectedReaders.value(i)});
2304 }
2305}
2306
2307void ImitatePass::reencryptAlso(const QString &dir, const QStringList &files,
2308 const AppSettings &settings) {
2309 if (m_reencryptActive) {
2310 emit statusMsg(tr("A re-encryption is already running"), 3000);
2311 return;
2312 }
2313 // Each with the bytes the user was shown it with: one changed since (a
2314 // pull, a co-writer) is named again rather than taken.
2315 m_reencryptAgreed.clear();
2316 for (const QString &file : files) {
2317 const auto shown = m_lastUnexpected.constFind(QDir::cleanPath(file));
2318 if (shown != m_lastUnexpected.constEnd()) {
2319 m_reencryptAgreed.insert(shown.key(), shown.value());
2320 }
2321 }
2322 if (m_reencryptAgreed.isEmpty()) {
2323 // MainWindow locked the interface for the run that does not start.
2324 emit statusMsg(tr("Nothing to re-encrypt: those entries were not named "
2325 "by the last run"),
2326 5000);
2327 emit endReencryptPath();
2328 return;
2329 }
2330 reencryptPath(dir, settings);
2331 if (!m_reencryptActive) {
2332 m_reencryptAgreed.clear();
2333 }
2334}
2335
2336auto ImitatePass::reencryptUsesGit() const -> bool {
2337 return gitConfigured() && !m_uncommittedGpgId;
2338}
2339
2340void ImitatePass::reencryptWithoutGit(const QString &dir,
2341 const QString &gitError) {
2342 if (m_reencryptActive) {
2343 // The run in flight was started with its own Git mode; this folder is
2344 // not part of it.
2345 reportUncommittedGpgId(dir, gitError, false);
2346 return;
2347 }
2348 m_uncommittedGpgId = UncommittedGpgId{dir, gitError};
2349 reencryptPath(dir);
2351 // Refused before it started; reencryptPath() said why.
2352 m_uncommittedGpgId.reset();
2353 reportUncommittedGpgId(dir, gitError, false);
2354 }
2355}
2356
2358 const QString &gitError,
2359 bool reencrypted) {
2360 const QString folder = QDir::toNativeSeparators(QDir::cleanPath(dir));
2361 if (reencrypted) {
2362 emit critical(
2363 tr("Recipients not committed"),
2364 tr("The recipients of %1 were changed and its entries were "
2365 "re-encrypted to them, but the Git commit failed:\n\n%2\n\n"
2366 "The change is not committed or pushed yet. Fix the Git problem, "
2367 "then commit the changes, or save the recipients again.")
2368 .arg(folder, gitError));
2369 return;
2370 }
2371 emit critical(
2372 tr("Recipients not committed"),
2373 tr("The recipients of %1 were changed, but the Git commit "
2374 "failed:\n\n%2\n\nRe-encryption did not complete, so some or all "
2375 "entries are still encrypted to the previous recipients, who can "
2376 "still read them. Nothing was committed or pushed. Fix the Git "
2377 "problem, then save the recipients again.")
2378 .arg(folder, gitError));
2379}
2380
2382 const QString &dest, bool force)
2383 -> QString {
2384 QFileInfo srcFileInfo(src);
2385 QFileInfo destFileInfo(dest);
2386 QString destFile;
2387 QString srcFileBaseName = srcFileInfo.fileName();
2388
2389 if (srcFileInfo.isFile()) {
2390 if (destFileInfo.isFile()) {
2391 if (!force) {
2392 qCDebug(lcQtPass) << "Destination file already exists";
2393 return {};
2394 }
2395 destFile = dest;
2396 } else if (destFileInfo.isDir()) {
2397 destFile = Util::joinPath(dest, srcFileBaseName);
2398 } else {
2399 destFile = dest;
2400 }
2401
2402 // Case-sensitive: only an actual ".gpg" entry already carries the suffix.
2403 // A neighbouring file like "login.GPG" is a different name, so it must not
2404 // be chopped to "login" and re-suffixed to the real "login.gpg" entry,
2405 // which the forced move would then overwrite.
2406 if (destFile.endsWith(QLatin1String(".gpg"))) {
2407 destFile.chop(4);
2408 }
2409 destFile.append(".gpg");
2410 } else if (srcFileInfo.isDir()) {
2411 if (destFileInfo.isDir()) {
2412 destFile = Util::joinPath(dest, srcFileBaseName);
2413 } else if (destFileInfo.isFile()) {
2414 qCDebug(lcQtPass) << "Destination is a file";
2415 return {};
2416 } else {
2417 destFile = dest;
2418 }
2419 } else {
2420 qCDebug(lcQtPass) << "Source file does not exist";
2421 return {};
2422 }
2423 return destFile;
2424}
2425
2426void ImitatePass::executeMoveGit(const QString &src, const QString &destFile,
2427 bool force) {
2428 QStringList args;
2429 args << "mv";
2430 if (force) {
2431 args << "-f";
2432 }
2433 args << "--" << pgit(src) << pgit(destFile);
2434 executeGit(GIT_MOVE, args);
2435
2436 // The move alone: with no path, the commit took whatever else was
2437 // staged.
2438 gitCommit(QStringList{src, destFile},
2439 QString("Moved for %1 to %2 using QtPass.")
2440 .arg(commitName(src), commitName(destFile)));
2441}
2442
2443auto ImitatePass::commitName(const QString &path) const -> QString {
2444 QString name = QDir(m_settings.passStore).relativeFilePath(path);
2445 // Not under the store as spelled (a copy from elsewhere, the store's
2446 // other spelling through a link, another drive): "../.." or an absolute
2447 // path would carry the local layout too, so the file name alone.
2448 if (name == QLatin1String("..") || name.startsWith(QLatin1String("../")) ||
2449 QDir::isAbsolutePath(name)) {
2450 name = QFileInfo(path).fileName();
2451 }
2452 name.replace(Util::endsWithGpg(), "");
2453 return name;
2454}
2455
2456void ImitatePass::Move(const QString src, const QString dest,
2457 const bool force) {
2458 // Cleaned once, so the checks and the rename see one path: every check
2459 // removes ".." as text, while rename(2) follows a link first and applies
2460 // ".." after it, so "link/../x" was judged as <store>/x and landed beside
2461 // the link's target.
2462 const QString from = QDir::cleanPath(src);
2463 const QString to = QDir::cleanPath(dest);
2464 if (refuseLinkedPath(from) || refuseLinkedPath(to)) {
2465 return;
2466 }
2468 return;
2469 }
2470 // No message box opens inside the transaction: a process queued while one
2471 // is open (an entry opened from a search another instance forwarded) would
2472 // be booked as a step of the move, and its decrypted output reported as
2473 // the move's, which is not secret. So every check runs first, and the
2474 // transaction holds only the Git commands.
2475 const QString destFile = resolveMoveDestination(from, to, force);
2476 if (destFile.isEmpty()) {
2477 return;
2478 }
2479 if (refuseLinkedPath(destFile)) {
2480 return;
2481 }
2482
2483 if (refuseOverlappingMove(from, destFile)) {
2484 return;
2485 }
2486
2487 qCDebug(lcQtPass) << "Move Source: " << from;
2488 qCDebug(lcQtPass) << "Move Destination: " << destFile;
2489
2490 const bool folder = QFileInfo(from).isDir();
2491 PendingMove move{from, destFile,
2492 QDir::cleanPath(getGpgIdPath(from, m_settings.passStore)),
2493 std::nullopt};
2494
2495 if (gitReady()) {
2496 // Settled in finished() once the move's commands have run: only then
2497 // is it known whether git mv moved anything, and which list applies
2498 // where it landed (a move queued before this one may create that
2499 // folder). Every Move() through Git ends in one PASS_MOVE.
2500 m_pendingMoves.enqueue(move);
2502 executeMoveGit(from, destFile, force);
2503 return;
2504 }
2505 // A forced move replaces the destination entry in the one rename, as
2506 // git mv -f does: removing it first lost it when the rename then failed
2507 // (and lost the entry itself, moved onto its own name). A folder is never
2508 // replaced, forced or not. Without Git nothing else reports a failure.
2509 const bool moved = force && !folder ? Util::replaceFile(from, destFile, true)
2510 : QDir().rename(from, destFile);
2511 if (!moved) {
2512 emit critical(tr("Move failed"),
2513 tr("Could not move %1 to %2.").arg(from, destFile));
2514 return;
2515 }
2516 move.landed = true;
2517 reencryptMoved(move);
2519}
2520
2522 const QString &destFile) -> bool {
2523#ifdef Q_OS_WIN
2524 constexpr auto cs = Qt::CaseInsensitive;
2525#else
2526 constexpr auto cs = Qt::CaseSensitive;
2527#endif
2528 // The same path, or one inside the other.
2529 const auto overlap = [](const QString &a, const QString &b) {
2530 const QString x = QDir::cleanPath(a);
2531 const QString y = QDir::cleanPath(b);
2532 return x.compare(y, cs) == 0 || x.startsWith(y + QLatin1Char('/'), cs) ||
2533 y.startsWith(x + QLatin1Char('/'), cs);
2534 };
2535 QStringList busy = m_movedToReencrypt;
2536 for (const PendingMove &move : std::as_const(m_pendingMoves)) {
2537 busy << move.src << move.destFile;
2538 }
2539 if (m_reencryptActive) {
2540 busy << m_reencryptScope;
2541 }
2542 for (const QString &path : std::as_const(busy)) {
2543 if (overlap(path, src) || overlap(path, destFile)) {
2544 emit critical(tr("Move not started"),
2545 tr("%1 is still being moved or re-encrypted. Move it "
2546 "again once that has finished.")
2547 .arg(QDir::toNativeSeparators(QDir::cleanPath(path))));
2548 return true;
2549 }
2550 }
2551 return false;
2552}
2553
2555 // Only a move whose git mv (or rename) succeeded: one that failed, or
2556 // never ran, moved nothing, and re-encrypting the destination would
2557 // rewrite the entry that was there. Not the source name: something may
2558 // be written under it again before the move settles.
2559 if (move.landed != true) {
2560 return;
2561 }
2562 // The user moved it here: a path saved from this device.
2564 const QFileInfo landed(move.destFile);
2565 if (!landed.exists() || Util::isLinkedFolder(move.destFile)) {
2566 return;
2567 }
2568 // As `pass mv`, what moved is encrypted for the recipients where it
2569 // landed. Not needed when the same list applies there (a rename, a move
2570 // within its folder's reach) or a folder took its own list along.
2571 const QString toList =
2572 QDir::cleanPath(getGpgIdPath(move.destFile, m_settings.passStore));
2573 if (toList == move.fromList ||
2574 (landed.isDir() &&
2575 toList == QDir::cleanPath(QDir(move.destFile).filePath(".gpg-id")))) {
2576 return;
2577 }
2578 // The entry alone, or the folder: not its neighbours, which this move
2579 // did not touch. One run at a time: behind the one in flight, if any.
2580 const QString scope = QDir::cleanPath(move.destFile);
2581 if (!m_movedToReencrypt.contains(scope)) {
2582 m_movedToReencrypt << scope;
2583 }
2584}
2585
2586auto ImitatePass::copyDestination(const QString &src, const QString &dest,
2587 bool force) -> QString {
2588 const auto refuse = [this, &src](const QString &to) {
2589 emit critical(tr("Copy failed"),
2590 tr("Could not copy %1 to %2.").arg(src, to));
2591 return QString();
2592 };
2593 // Like `pass cp`, dest may be an existing folder (a drag-and-drop copy hands
2594 // over the folder, not the new file name). Resolve the real target the same
2595 // way Move does: into the folder, .gpg appended, no clobbering without force.
2596 QString destFile = resolveMoveDestination(src, dest, force);
2597 if (destFile.isEmpty()) {
2598 return refuse(dest);
2599 }
2600 // A link planted under that name (dangling ones pass exists()) is not an
2601 // entry to write.
2602 if (refuseLinkedPath(destFile)) {
2603 return {};
2604 }
2605 const QFileInfo destFileInfo(destFile);
2606 // A folder destination that is the source's own folder resolves to the
2607 // source itself; with force that would replace the only copy with itself.
2608 // And resolveMoveDestination only sees a clash when dest names the file.
2609 if (QFileInfo(src) == destFileInfo || (!force && destFileInfo.exists())) {
2610 return refuse(destFile);
2611 }
2612 return destFile;
2613}
2614
2615void ImitatePass::Copy(const QString src, const QString dest,
2616 const bool force) {
2617 // Cleaned once, as in Move().
2618 const QString from = QDir::cleanPath(src);
2619 const QString to = QDir::cleanPath(dest);
2620 // QFile::copy reads through a link: the target's bytes would become an
2621 // entry of the store.
2622 if (refuseLinkedPath(from) || refuseLinkedPath(to)) {
2623 return;
2624 }
2626 return;
2627 }
2628 // As in Move(): no message box inside the transaction.
2629 const QString destFile = copyDestination(from, to, force);
2630 if (destFile.isEmpty()) {
2631 return;
2632 }
2633 // git has no "cp": copy on disk in both modes, then stage. Synchronous and
2634 // atomic (Util::copyFileReplacing follows no link), so it exists before the
2635 // re-encryption below and a forced overwrite survives a half-way failure;
2636 // without force nothing is replaced, not even what appeared since the check.
2637 QString why;
2638 if (!Util::copyFileReplacing(from, destFile, force, &why)) {
2639 emit critical(tr("Copy failed"),
2640 tr("Could not copy %1 to %2.").arg(from, destFile) + "\n" +
2641 why);
2642 return;
2643 }
2644 // The user copied it here: a path saved from this device.
2645 EntryRecord::remember({destFile});
2646 if (gitReady()) {
2648 executeGit(GIT_COPY, {"add", "-f", "--", pgit(destFile)});
2649 gitCommit(destFile, QString("Copied from %1 to %2 using QtPass.")
2650 .arg(commitName(from), commitName(destFile)));
2651 }
2652 const QFileInfo written(destFile);
2653 // What the user copied is re-encrypted whatever it was encrypted to. Not
2654 // while a run is active: its worker reads the list (and refuses this one).
2655 const bool idle = !m_reencryptActive;
2656 if (idle) {
2657 m_reencryptTrusted = {QDir::cleanPath(written.absoluteFilePath())};
2658 }
2659 if (written.isDir()) {
2660 reencryptPath(written.absoluteFilePath());
2661 } else if (written.isFile()) {
2662 reencryptPath(written.dir().path());
2663 }
2664 if (idle && !m_reencryptActive) {
2665 m_reencryptTrusted.clear();
2666 }
2667}
2668
2669void ImitatePass::executeGpg(PROCESS id, const QStringList &args, QString input,
2670 bool readStdout, bool readStderr) {
2671 executeWrapper(id, m_settings.gpgExecutable, args, std::move(input),
2672 readStdout, readStderr);
2673}
2674
2675// useGit can be on with no gitExecutable (fresh setup, git removed later);
2676// handing that to the Executor used to wedge the queue (#1682).
2677auto ImitatePass::gitConfigured() const -> bool {
2678 return m_settings.useGit && !m_settings.gitExecutable.isEmpty();
2679}
2680
2681// Tells the user once per operation why git was skipped, so the store
2682// silently drifting from git does not go unnoticed.
2684 if (m_settings.useGit && m_settings.gitExecutable.isEmpty()) {
2685 emit statusMsg(tr("Git executable not configured, skipping git"), 3000);
2686 return false;
2687 }
2688 return m_settings.useGit;
2689}
2690
2691void ImitatePass::executeGit(PROCESS id, const QStringList &args, QString input,
2692 bool readStdout, bool readStderr) {
2693 // Callers check gitReady() first; an empty executable that still gets here
2694 // is reported by the Executor instead of wedging the queue (#1682).
2695 executeWrapper(id, m_settings.gitExecutable, args, std::move(input),
2696 readStdout, readStderr);
2697}
2698
2699// Only PASS_* processes reach Pass::finished, so to the interface this looks
2700// the same as RealPass.
2701void ImitatePass::finished(int id, int exitCode, const QString &out,
2702 const QString &err) {
2703 qCDebug(lcQtPass) << "Imitate Pass";
2704 QString error = err;
2705 // A move's git mv runs first in its transaction, so in order: the first
2706 // pending move without an answer is this one's.
2707 if (id == GIT_MOVE) {
2708 for (PendingMove &move : m_pendingMoves) {
2709 if (!move.landed) {
2710 move.landed = exitCode == 0;
2711 break;
2712 }
2713 }
2714 }
2715 if (id == PASS_INSERT && !m_pendingInserts.isEmpty()) {
2716 // Insert()'s gpg step: place the ciphertext before the queued git steps
2717 // run (the executor starts the next item only after this returns). On
2718 // failure it fails like a gpg error: git steps cancelled below.
2719 // No dialog here: it would spin the event loop and run git steps first.
2720 exitCode = placePendingInsert(exitCode, &error);
2721 }
2722 PROCESS pid = m_transaction.transactionIsOver(static_cast<PROCESS>(id));
2723 m_transactionOutput.append(out);
2724
2725 if (exitCode == 0) {
2726 if (pid == INVALID) {
2727 return;
2728 }
2729 } else {
2730 while (pid == INVALID) {
2731 id = exec.cancelNext();
2732 if (id == -1) {
2733 // this is probably irrecoverable and shall not happen
2734 qCDebug(lcQtPass) << "No such transaction!";
2735 return;
2736 }
2737 pid = m_transaction.transactionIsOver(static_cast<PROCESS>(id));
2738 }
2739 }
2740 Pass::finished(pid, exitCode, m_transactionOutput, error);
2741 m_transactionOutput.clear();
2742 if (pid == PASS_MOVE && !m_pendingMoves.isEmpty()) {
2743 reencryptMoved(m_pendingMoves.dequeue());
2745 }
2746}
2747
2748auto ImitatePass::placePendingInsert(int exitCode, QString *error) -> int {
2749 const PendingInsert pending = m_pendingInserts.dequeue();
2750 // The flag answers for this insert, the one whose gpg step just ended, not
2751 // for whichever Insert() was called last: with two inserts queued, a gpg
2752 // failure of the second must report written=false even though the first
2753 // was placed. Cleared here, before placement, and set only on success.
2754 m_insertPlaced = false;
2755 if (exitCode != 0) {
2756 return exitCode;
2757 }
2758 // Insert() checked the repository when the save was requested, but a
2759 // pull queued before it (the asynchronous Update button) may have run
2760 // and stopped in a conflict while this gpg step encrypted. Placing the
2761 // entry and committing it now would land it in the unfinished operation,
2762 // where `git rebase --abort` would drop it. Re-check and, if so, fail the
2763 // save instead of placing it; finished() cancels the queued git steps.
2764 const QString midOp = unfinishedGitOperationReason();
2765 if (!midOp.isEmpty()) {
2766 *error = midOp;
2767 return 1;
2768 }
2769 m_insertPlaced = placeEncryptedFile(pending.output, pending.file,
2770 pending.overwrite, error);
2771 if (!m_insertPlaced) {
2772 return 1;
2773 }
2774 EntryRecord::remember({pending.file});
2775 return 0;
2776}
2777
2778auto ImitatePass::placeEncryptedFile(const QString &output, const QString &file,
2779 bool overwrite, QString *error) -> bool {
2780 if (QFileInfo(output).size() <= 0) {
2781 // gpg reported success and wrote nothing: not an entry.
2782 *error = tr("gpg wrote no ciphertext for %1.").arg(file);
2783 return false;
2784 }
2785 // A link planted since the check is replaced as an entry; without
2786 // overwrite, anything new under the name fails the add.
2787 return Util::copyFileReplacing(output, file, overwrite, error);
2788}
2789
2793
2794// PCRE, as for RealPass (see Pass::Grep). Runs on a NativeGrep thread; the
2795// result arrives on this thread as finishedGrep.
2796void ImitatePass::Grep(QString pattern, bool caseInsensitive) {
2797 m_grep.search(pattern, caseInsensitive, m_settings.gpgExecutable,
2799}
static void remember(const QStringList &paths)
Record entries this device has just written.
static auto known(const QString &entryFile) -> bool
Whether this device saved entryFile, or found it there when the store was seeded.
auto isIdle() const -> bool
Whether no command is running and nothing is queued.
Definition executor.h:620
static auto executeBlocking(const QString &app, const QStringList &args, const QString &input=QString(), QString *process_out=nullptr, QString *process_err=nullptr) -> int
Run a command synchronously and return its exit code.
Definition executor.cpp:700
static auto translatePathForWsl(const QString &path, const QString &exe) -> QString
Translate a native path for a WSL-routed executable.
Definition executor.cpp:335
auto environment() const -> QProcessEnvironment
Return the environment passed to child processes.
Definition executor.cpp:735
static auto executeBlockingRaw(QProcess &process, const QString &app, const QStringList &args, const QByteArray &input, QByteArray *process_out, QString *process_err=nullptr, const std::atomic_bool *cancel=nullptr, int timeoutMs=-1) -> int
executeBlocking() on bytes, for an entry's plaintext: input is written to stdin and stdout returned e...
Definition executor.cpp:690
auto cancelNext() -> int
Cancel the next queued command without executing it.
Definition executor.cpp:780
static auto accept(const QString &gpgIdFile, const QByteArray &contents, const QString &storeRoot, QString *error=nullptr) -> Verdict
Decide about a verified list: its folder against where it sits, its generation against the remembered...
static auto folderOf(const QString &gpgIdFile, const QString &storeRoot) -> std::optional< QString >
The store-relative folder of gpgIdFile, as written in and compared against the folder line: ....
static auto reserveNext(const QString &gpgIdFile, std::optional< qint64 > verifiedOnDisk, QString *error=nullptr) -> std::optional< qint64 >
Reserve the generation to write next for gpgIdFile: one above both what this device remembers and ver...
static auto recordWritten(const QString &gpgIdFile, const QByteArray &contents, QString *error=nullptr) -> bool
Record the bytes just written for gpgIdFile, so that this device recognises its own list afterwards a...
Verdict
The outcome of accept(). Only Accepted means the list may be used; the others say why not,...
@ Accepted
Folder, generation and record all agree; remembered.
@ RecordUnavailable
The record could not be read or written.
static auto withHeader(qint64 generation, const QString &folder, const QByteArray &recipients, const QString &store={}) -> QByteArray
A complete list: the header in front of the recipients.
static auto parse(const QByteArray &contents, QString *error=nullptr) -> std::optional< Header >
The header a .gpg-id's bytes declare.
static auto storeIdFor(const QString &storeRoot, const std::optional< QString > &onDisk, QString *error=nullptr) -> std::optional< QString >
The store id to write into a list of storeRoot: the one this device knows the store by; else onDisk,...
The detached signature on a store's .gpg-id: whether the configured signing key is usable,...
Definition gpgidsigner.h:29
void setStoreRoot(const QString &root)
The store the lists and signatures this signer reads belong to.
Definition gpgidsigner.h:76
auto enabled() const -> bool
Whether any signing key is configured at all.
auto sign(const QString &gpgIdFile, const QByteArray &contents, QString *error=nullptr) const -> bool
Write <file>.sig, a detached signature by the first key over contents, the bytes the caller just wrot...
auto verifyFile(const QString &gpgIdFile, QByteArray *contents) const -> bool
Read gpgIdFile and verify it against <file>.sig.
static auto keysFromSetting(const QString &passSigningKey) -> QStringList
Split the settings value into keys, upper-cased the way gpg prints fingerprints.
RAII helper for wrapping operations in transactions.
auto commitReencrypted(const QString &fileName) -> bool
Stage and commit a re-encrypted entry, when the store is a Git repository QtPass manages.
auto reencryptEntry(const QString &fileName, const QStringList &gpgId, WhoReads &who, ReencryptResult &result) -> bool
Check one entry and re-encrypt it to gpgId when it is not encrypted to those keys yet,...
QHash< QString, Agreed > m_reencryptAgreed
auto prepareBlocking(QProcess &process) -> const std::atomic_bool *
Give process the environment for the calling thread: the store's on the owning thread,...
auto createBackupCommit() -> bool
Create git backup commit before re-encryption.
auto previousListOf(const QString &path, const QString &gpgIdFile) -> std::optional< PreviousList >
The verified list the entries of path were encrypted to before Init() replaces it,...
auto primaryKeysOf(const QStringList &ids, QHash< QString, QString > &primaries, QHash< QString, QString > &names) -> QSet< QString >
The primary keys behind key IDs from an entry (ENC_TO).
void finishReencrypt(const ReencryptResult &result)
Report the outcome of a run and emit endReencryptPath().
void Remove(QString file, bool isDir) override
Remove password.
bool m_insertPlaced
QString m_transactionOutput
stdout of the steps of the transaction in flight, collected by finished() and handed on,...
auto execBlocking(const QString &app, const QStringList &args, const QString &input=QString(), QString *process_out=nullptr, QString *process_err=nullptr) -> int
Executor::executeBlocking() for the re-encryption helpers.
auto refuseOverlappingMove(const QString &src, const QString &destFile) -> bool
Refuse a move of src to destFile that touches what an earlier move or a re-encryption still has to se...
void GitInit() override
Initialize Git repository.
auto recipientsForEntry(const QString &file, QStringList *recipients) -> bool
The recipients to encrypt file to: its folder's .gpg-id, verified when a signing key is set.
void executeGpg(PROCESS id, const QStringList &args, QString input=QString(), bool readStdout=true, bool readStderr=true)
Execute GPG command.
auto reencryptSingleFile(const QString &fileName, const QStringList &recipients, QString *why) -> bool
Re-encrypt single file with new recipients.
void reportUncommittedGpgId(const QString &dir, const QString &gitError, bool reencrypted)
Tell the user that the recipients of dir changed on disk but the change is not committed,...
QHash< QString, Agreed > m_lastUnexpected
auto keysEncryptedTo(const QStringList &recipients, QHash< QString, QString > &primaries, QHash< QString, QString > &names, bool lookUp=true) -> std::optional< QSet< QString > >
The primary keys gpg encrypts to for recipients, found by a throwaway encryption outside the store wi...
auto placePendingInsert(int exitCode, QString *error) -> int
Finish the oldest pending insert after its gpg step: place the ciphertext with placeEncryptedFile(),...
auto copyDestination(const QString &src, const QString &dest, bool force) -> QString
The file a copy of src to dest writes: like pass cp, into an existing folder with ....
auto fullKeyListing(QString *listing) -> int override
Pass::fullKeyListing() in the calling thread's environment, so a re-encryption run's worker lists the...
bool m_reencryptActive
Set while a re-encryption run is pending or on the worker thread.
void reportUnrestorable(const QString &path, QStringList &problems)
Note for the user that a leftover is not a regular file and was left.
void startReencryptWorker(const QString &dir)
Start the worker thread once the Executor queue is idle.
auto writeGpgIdFile(const QString &gpgIdFile, const QList< UserInfo > &users, QByteArray *written=nullptr) -> bool
Write the enabled recipients to a .gpg-id, atomically: a write that fails halfway (full disk,...
auto commitArgs() -> QStringList
The start of a git commit for the store: "commit", and "-S" when git config pass.signcommits is true ...
auto verifyGpgIdForDir(const QString &file, QHash< QString, QStringList > &verified, QStringList &gpgId) -> bool
Recipients for the directory of file, from its verified .gpg-id.
void Grep(QString pattern, bool caseInsensitive) override
Search all password content by GPG-decrypting each .gpg file.
void Insert(QString file, QString newValue, bool overwrite) override
Insert new password.
auto recipientsForDir(const QString &fileName, QHash< QString, QStringList > &verified, QStringList &gpgId, ReencryptResult &result) -> bool
The verified recipients for the folder fileName sits in.
auto gitTracks(const QString &file) -> bool
Check whether git already tracks a file in the store.
~ImitatePass() override
Cancel a running content search, and cancel and join a running re-encryption worker,...
void cancelReencryptPath()
Ask a running reencryptPath() to stop.
QStringList m_reencryptTrusted
auto execBlockingRaw(const QString &app, const QStringList &args, const QByteArray &input, QByteArray *process_out) -> int
execBlocking() on bytes (Executor::executeBlockingRaw()), for an entry's plaintext,...
ImitatePass()
Construct the backend and connect its content search.
auto listKeysFor(const QString &gpgIdPath, const QStringList &gpgId, WhoReads &who) -> const ListKeys &
The keys of the list at gpgIdPath, worked out once per run.
auto gitReady() -> bool
gitConfigured() plus a status message when git is enabled but no executable is configured.
bool m_reencryptPushing
Set while finishReencrypt() pushes, so GitPush() does not hold it.
void executeGit(PROCESS id, const QStringList &args, QString input=QString(), bool readStdout=true, bool readStderr=true)
Execute git command.
QStringList m_movedToReencrypt
void Init(QString path, const QList< UserInfo > &users) override
Initialize store.
auto loadVerifiedRecipients(const QString &gpgIdFile, QStringList *recipients, QString *why=nullptr) -> bool
Read a .gpg-id, verify its detached signature and parse the recipients from the bytes that were verif...
auto readerChangeOf(const QString &fileName, const QStringList &keys, const ListKeys &lk, WhoReads &who) -> ReaderChange
Who would gain an entry by re-encrypting it to its list, other than those this change added,...
void Copy(const QString src, const QString dest, const bool force) override
Copy password file.
QThread * m_reencryptThread
The re-encryption worker while it runs, null otherwise. The destructor sets m_reencryptCancel and joi...
void rememberUnexpected(const ReencryptResult &result)
Keep what the run named in unexpectedRecipients(), with the bytes and readers it was named for: reenc...
auto holdForAgreement(const QString &fileName, const QStringList &keys, const ReaderChange &change, const WhoReads &who, ReencryptResult &result) -> bool
Leave an entry that would gain readers for the user: named in the question after the run,...
QQueue< PendingMove > m_pendingMoves
Moves through Git, in order, each settled when its PASS_MOVE ends.
auto reencryptFiles(const QString &dir) -> ReencryptResult
Worker-thread body: scan dir and re-encrypt stale files.
auto startReencryptRun(const QString &dir, ReencryptResult &result) -> bool
The checks a run makes after its own pull, before it writes: no unfinished Git operation,...
auto encryptFor(const QString &output, const QStringList &recipients, const QByteArray &plaintext) -> bool
Encrypt plaintext to recipients, into output.
auto placeEncryptedFile(const QString &output, const QString &file, bool overwrite, QString *error) -> bool
Bring the ciphertext gpg wrote to output into the store as file (Util::copyFileReplacing): through a ...
auto settleSignature(const QString &gpgIdFile, const QByteArray &written, const GpgIdSigner &signer, bool useGit, QString *sigToCommit) -> bool
Bring the signature in line with the list just written: a new one when signing is on,...
QString m_reencryptScope
The folder the re-encryption in flight covers, for the push hold.
SimpleTransaction m_transaction
auto entryHash(const QString &file) const -> QByteArray
SHA-256 of an entry's bytes, read as a regular file without following a link.
void unexpectedRecipients(const QString &dir, const QStringList &files, const QStringList &details)
A run left files alone: re-encrypting one would let someone on its folder's list read it who cannot n...
auto settleAutoPushHold(const ReencryptResult &result, bool agreedRun) -> bool
Bring the record of entries a removed recipient still reads up to date with a run,...
auto signGpgIdFile(const QString &gpgIdFile, const QByteArray &contents) -> bool
Sign a .gpg-id with the configured key and verify the result; failures are reported through critical(...
bool m_pushAfterReencrypt
QProcessEnvironment m_reencryptEnv
void reencryptProgress(int current, int total)
Re-encryption progress: current of total files checked.
void reencryptAfterFailedCommit(const QString &path, int gitExit, const QString &gitOut, const QString &gitErr, const QString &gpgIdFile, const std::optional< PreviousList > &previous)
After Init() wrote the new list but could not commit it: report Git's failure and re-encrypt without ...
void executeMoveGit(const QString &src, const QString &destFile, bool force)
Execute git move operation.
void endReencryptPath()
A reencryptPath() run is over, whether it finished, failed, was cancelled or was refused; the main wi...
auto translatePathForWsl(const QString &path, const QString &exe) const -> QString
Translate path for the given exe when WSL-routed: wraps in wslpath substitution, otherwise returns pa...
void finished(int id, int exitCode, const QString &out, const QString &err) override
Handle process completion.
void reencryptWithoutGit(const QString &dir, const QString &gitError)
Re-encrypt dir to the .gpg-id Init() wrote although its commit failed, without any Git step (they wou...
auto addGenerationHeader(const QString &gpgIdFile, const GpgIdSigner &signer, QByteArray *contents) -> bool
Put the generation header on a list that is about to be signed: reserve a generation above what this ...
auto restoreBackup(const QString &path, QStringList &problems) -> bool
Put a 1.8.x backup back in its entry's place when the entry is missing; report it when both exist (bo...
void startMovedReencrypts()
Start the runs in m_movedToReencrypt, one at a time, while none is in flight; then send a deferred pu...
auto gitAddGpgId(const QString &gpgIdFile, const QString &gpgIdSigFile, QString *out, QString *err) -> int
Stage a .gpg-id and, when given, its .sig, and commit both in one commit, so no commit in the history...
std::optional< UncommittedGpgId > m_uncommittedGpgId
void reencryptAlso(const QString &dir, const QStringList &files, const AppSettings &settings)
Re-encrypt files in dir after the user agreed to it.
std::atomic< bool > m_reencryptCancel
void GitPull() override
Pull from remote.
void reencryptMoved(const PendingMove &move)
Queue a re-encryption of what move moved, if it moved and another .gpg-id applies where it landed; a ...
auto refuseLinkedGpgIdFolder(const QString &path) -> bool
Refuse a folder, or a .gpg-id/.gpg-id.sig in it, that is a link: writing there would reach outside th...
auto decryptEntry(const QString &fileName, QByteArray *plaintext, QString *why) -> bool
Decrypt fileName for re-encryption.
auto refuseInitBeforeWrite(const QString &gpgIdFile, const GpgIdSigner &signer) -> bool
The checks Init() runs before it writes anything: no re-encryption running, the signing key's secret ...
void reportReencryptOutcome(const ReencryptResult &result, bool stillRead)
The status line for a run, and the push after it when one is due and nothing holds it.
auto isTrustedEntry(const QString &fileName, const QSet< QString > &listNow) const -> bool
Whether an entry that would gain readers is taken without a question: the user moved or copied it in,...
void Show(QString file) override
Show decrypted password.
std::optional< WrittenGpgId > m_writtenGpgId
auto pgpg(const QString &path) const -> QString
Translate path for gpg when WSL-routed: wraps in wslpath substitution, otherwise returns path unchang...
static auto namedReaders(const QSet< QString > &fprs, const QHash< QString, QString > &names) -> QString
The names of fprs for a question or a failure, sorted.
auto entriesToReencrypt(const QString &dir, QStringList *failed) -> QStringList
The entries under dir a run considers, telling the user about anything skipped for not being a regula...
auto storeGit(const QStringList &args, QString *out) -> bool override
Run git with -C <store> in the store, blocking.
QQueue< PendingInsert > m_pendingInserts
The inserts whose gpg step has not ended yet, oldest first.
void GitPull_b(int timeoutMs) override
Run git pull in the store and wait for it, at most timeoutMs.
auto readersAnEditWouldAdd(const QString &file) -> EditReaders override
Who saving over an existing entry would let read it who may not now.
QHash< QString, QSet< QString > > m_removedReaders
auto ciphertextHolds(const QString &ciphertext, const QByteArray &plaintext) -> bool
Decrypt ciphertext again and compare it with plaintext, byte for byte, so nothing replaces an entry u...
NativeGrep m_grep
Background search over the decrypted store; relays to finishedGrep.
auto resolveMoveDestination(const QString &src, const QString &dest, bool force) -> QString
Resolve destination for move operation.
auto recoverReencryptLeftovers(const QString &dir) -> bool
Deal with what a crashed or failed earlier run left under dir before touching anything: stale tempora...
void GitPush() override
Push to remote. While a re-encryption runs the push is held (Users â–¸ OK and a copy ask for it as soon...
void Move(const QString src, const QString dest, const bool force) override
Move password file.
void sendDeferredPush()
Make the push GitPush() deferred, once no run is in flight and no move is waiting; an automatic one o...
void dropStaleTemporary(const QString &path)
Remove a stale temporary a crashed run left, unless it was modified within the hour: on a shared stor...
bool m_deferredPushByHand
std::optional< PreviousList > m_previousList
void startReencryptPath()
A reencryptPath() run is about to start its worker thread.
void reportFailedEntries(const QStringList &failed)
Tell the user which entries a run could not re-encrypt, the first few by name.
auto getKeysFromFile(const QString &fileName) -> QStringList
Read recipients from file.
auto commitName(const QString &path) const -> QString
How a commit message names a file of the store: relative to the store, without .gpg ("work/bank",...
auto reencryptUsesGit() const -> bool
gitConfigured(), unless the current run is one reencryptWithoutGit() started.
auto gitConfigured() const -> bool
Git is enabled and an executable is configured.
void reencryptPath(const QString &dir)
Re-encrypt entire directory.
auto pgit(const QString &path) const -> QString
Translate path for git when WSL-routed: wraps in wslpath substitution, otherwise returns path unchang...
void keepPreviousList(const QString &gpgIdFile, const std::optional< PreviousList > &previous)
Take previous as the PreviousList of the run Init() starts for gpgIdFile, unless a run is active or a...
auto pullBeforeReencrypt() -> bool
Pull before a run, when the store is a Git repository and automatic pulling is on.
void gitCommit(const QString &file, const QString &msg)
Commit one path to git.
void beforeExecute(PROCESS id) override
Open a transaction for every execution.
auto gpgIdSigner() -> GpgIdSigner
The signer for this store's .gpg-id, bound to the configured gpg and signing keys and to execBlocking...
void finished(const QList< QPair< QString, QStringList > > &results)
The newest search is over.
void search(const QString &pattern, bool caseInsensitive, const QString &gpgExe, const QString &storeDir, const QProcessEnvironment &env)
Start a search; finished() follows asynchronously, also for an empty or invalid pattern (with no resu...
void cancel()
Ask running searches to stop without waiting for them: the walk ends at the next file and a gpg that ...
static auto isIdle() -> bool
Whether neither backend runs or waits for anything: after a switch of backend the previous one is kep...
auto storeEnvironment() const -> QProcessEnvironment
The environment QtPass runs the store's processes in.
Definition pass.h:124
AppSettings m_settings
Application settings snapshot injected at init() time.
Definition pass.h:145
static auto getGpgIdPath(const QString &for_file, const QString &passStore) -> QString
Get .gpg-id file path for a password file.
Definition pass.cpp:1511
auto refusePendingPull() -> bool
Refuse a store change while a Git pull is still queued or running.
Definition pass.cpp:1427
void releaseAutoPush(const QString &folder)
Release the holds a clean re-encryption of folder covers: those for folder itself and everything unde...
Definition pass.cpp:1312
Enums::PROCESS PROCESS
Alias for Enums::PROCESS used throughout this class.
Definition pass.h:154
void queueInsert(const QString &entry=QString())
Count one insert that has started queueing but not yet reported.
Definition pass.h:853
void queueShow(const QString &file)
Remember what a Show() asked for, so its completion can say so.
Definition pass.h:841
void statusMsg(const QString &msg, int timeout)
Progress or a non-fatal problem worth a line in the status bar ("Creating backup commit",...
auto unfinishedGitOperationReason() -> QString
The unfinished git operation in progress in the store, if any.
Definition pass.cpp:1363
@ PlacedByCaller
Through the target of a linked store root, by a caller that places such a folder itself (Init()): not...
Definition pass.h:879
auto pushIsAutomatic() const -> bool
Whether the GitPush() running now is an automatic one.
Definition pass.cpp:1306
static auto maxOutputArgs() -> QStringList
The gpg options that enforce kMaxPlaintextBytes.
Definition pass.cpp:1184
void holdAutoPush(const QString &scope)
Hold automatic pushes of the store that holds scope (autoPushHeld()): its re-encryption did not finis...
Definition pass.cpp:1308
void executeWrapper(PROCESS id, const QString &app, const QStringList &args, bool readStdout=true, bool readStderr=true)
Execute external wrapper command.
Definition pass.cpp:126
static auto exactRecipientArg(const QString &line) -> QString
A bare mail address in gpg's exact form, <address>; any other line as written.
Definition pass.cpp:695
auto refuseLinkedPath(const QString &path, LinkScope scope=LinkScope::EntryAndParents, PathSpelling spelling=PathSpelling::Configured) -> bool
Refuse an operation on something that is, or lies behind, a symbolic link or NTFS junction inside the...
Definition pass.cpp:1321
void finishedGrep(const QList< QPair< QString, QStringList > > &results)
The newest Grep() is over; an empty list means no entry matched.
static auto enabledKeyLines(const QList< UserInfo > &users) -> QStringList
The enabled users' key IDs, as Init() writes them to .gpg-id.
Definition pass.cpp:580
Executor exec
Internal command executor for queuing and running subprocesses.
Definition pass.h:149
auto verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile, QByteArray *contents, QString *why) const -> bool
Whether gpgIdFile is a signed list QtPass accepts: its signature verifies (GpgIdSigner::verifyFile())...
Definition pass.cpp:1555
void init(const AppSettings &settings)
Initialize the Pass instance with a settings snapshot.
Definition pass.cpp:171
auto refuseChangedList() -> bool
Refuse an Init() under initIfUnchanged() when the folder's list no longer reads as the caller read it...
Definition pass.cpp:1452
auto withCurrentGitPin(QProcessEnvironment base) const -> QProcessEnvironment
base with GIT_DIR and GIT_WORK_TREE as the store is now (Util::gitStoreVariables()),...
Definition pass.cpp:1169
auto autoPushHeld() const -> bool
Whether automatic pushes of the current store are held because its last re-encryption did not finish ...
Definition pass.cpp:1291
static auto pullTimedOut(int timeoutMs) -> QString
The status-bar text for a blocking pull stopped at its deadline.
Definition pass.cpp:1940
void updateEnv()
Update environment for subprocesses.
Definition pass.cpp:984
void idle()
Nothing of the store's runs or waits any more (isIdle()).
virtual void finished(int id, int exitCode, const QString &out, const QString &err)
Handle process completion.
Definition pass.cpp:860
void critical(const QString &title, const QString &message)
Something went wrong that the user has to be told about in a dialog, such as a refused path or a fail...
auto refuseSkippedGpgId(const QString &file, bool signing, const QString &except=QString(), SkippedWalks *walks=nullptr) -> bool
With signing on, refuse to encrypt file when the lookup passed over its folder's own list (skippedGpg...
Definition pass.cpp:1518
auto refuseKeyLinesHeldTwice(const QStringList &lines) -> bool
Refuse, with critical(), a recipient list with a line that more than one key block holds (keyLinesHel...
Definition pass.cpp:568
static constexpr qint64 kMaxPlaintextBytes
Most bytes of plaintext a gpg decryption may produce.
Definition pass.h:511
@ ParentsOnly
Only the folders above it: a removal unlinks a link and touches nothing behind it.
Definition pass.h:865
@ EntryAndParents
The entry itself and every folder above it in the store.
Definition pass.h:860
auto refuseUnfinishedGitOperation() -> bool
Refuse to change the store while git is mid-rebase, -merge, -cherry-pick or -revert.
Definition pass.cpp:1489
static auto parseRecipients(const QByteArray &contents, const QString &sourceName) -> QStringList
Parse the contents of a .gpg-id: one recipient per line, # starts a comment, unusable lines are logge...
Definition pass.cpp:1848
auto refuseFolderOutsideStore(const QString &folder, QString *relative=nullptr) -> bool
Refuse recipients for a folder outside the store, as pass refuses a path with .. in it.
Definition pass.cpp:1347
void transactionAdd(Enums::PROCESS process)
Note that process has been queued.
auto transactionIsOver(Enums::PROCESS current) -> Enums::PROCESS
Tell whether the process that just finished ends the oldest pending transaction, and take that transa...
static auto removeTree(const QString &dir) -> bool
Remove dir and everything in it, the way rm -rf does: a symbolic link or NTFS junction,...
Definition util.cpp:1985
static auto endsWithGpg() -> const QRegularExpression &
Returns a regex to match .gpg file extensions.
Definition util.cpp:759
static auto isUnderLink(const QString &path, const QString &storeRoot, bool includeSelf=true) -> bool
Whether the way from storeRoot down to path passes through a symbolic link or NTFS junction: path its...
Definition util.cpp:1217
static auto writeFileReplacing(const QString &path, const QByteArray &bytes, bool replace, QString *error=nullptr) -> bool
Write bytes as the file path through stageFileReplacing().
Definition util.cpp:1911
static auto regularFilesUnder(const QString &dir, const QStringList &nameFilters, QStringList *skipped=nullptr, bool hiddenFiles=false, QStringList *unlisted=nullptr) -> QStringList
Regular files under dir whose name matches one of nameFilters, found by walking only real directories...
Definition util.cpp:1149
static constexpr qint64 kMaxGpgIdBytes
Most bytes of a .gpg-id QtPass reads.
Definition util.h:561
static auto displayable(const QString &text, bool lineBreaks=true) -> QString
text with the characters that change how the text around them reads replaced by U+FFFD,...
Definition util.cpp:898
static auto isLinkedFolder(const QString &path) -> bool
Whether path names a symbolic link or NTFS junction, with or without a trailing separator (which woul...
Definition util.cpp:1213
static auto replaceFile(const QString &from, const QString &to, bool replace) -> bool
Give the file at from the name to, atomically and without following anything: the operating system's ...
Definition util.cpp:1333
static auto joinPath(const QString &dir, const QString &name) -> QString
name in dir, as the file system means it.
Definition util.cpp:110
static auto copyFileReplacing(const QString &src, const QString &dst, bool replace, QString *error=nullptr) -> bool
Copy the regular file src to the name dst through stageFileReplacing(): src is read through a handle ...
Definition util.cpp:1925
static auto newLinesRegex() -> const QRegularExpression &
Returns a regex to match newline characters.
Definition util.cpp:1055
static auto normalizeFolderPath(const QString &path) -> QString
Ensure a folder path always ends with '/'.
Definition util.cpp:118
static auto readRegularFileInStore(const QString &store, const QString &path, qint64 maxBytes) -> std::optional< QByteArray >
readRegularFileUnder() for a file of the store at store, spelled under the store as configured or und...
Definition util.cpp:1564
EntryRecord: the entry paths this device has saved, kept outside the store.
Executor, the FIFO queue every gpg, git and pass child process of QtPass goes through,...
Rollback detection for signed .gpg-id files: the generation counter and the record of what was last s...
@ PASS_INIT
Definition enums.h:53
@ PASS_INSERT
Definition enums.h:51
@ GIT_INIT
Definition enums.h:44
@ PASS_COPY
Definition enums.h:56
@ PASS_MOVE
Definition enums.h:55
@ GIT_MOVE
Definition enums.h:57
@ PASS_REMOVE
Definition enums.h:52
@ GIT_COPY
Definition enums.h:58
@ INVALID
Definition enums.h:63
@ GIT_COMMIT
Definition enums.h:46
@ GIT_RM
Definition enums.h:47
@ PASS_SHOW
Definition enums.h:50
@ GIT_ADD
Definition enums.h:45
@ GIT_PULL
Definition enums.h:48
@ GIT_PUSH
Definition enums.h:49
ImitatePass, the backend that does what pass does by running gpg and git itself.
@ CLIPBOARD_ALWAYS
Definition enums.h:26
@ CLIPBOARD_NEVER
Definition enums.h:25
@ CLIPBOARD_ON_DEMAND
Definition enums.h:27
@ PASS_INIT
Definition enums.h:53
@ PASS_INSERT
Definition enums.h:51
@ GIT_INIT
Definition enums.h:44
@ PASS_COPY
Definition enums.h:56
@ PASS_MOVE
Definition enums.h:55
@ GIT_MOVE
Definition enums.h:57
@ PASS_GREP
Definition enums.h:59
@ GPG_GENKEYS
Definition enums.h:54
@ PASS_REMOVE
Definition enums.h:52
@ GIT_COPY
Definition enums.h:58
@ INVALID
Definition enums.h:63
@ GIT_COMMIT
Definition enums.h:46
@ GIT_RM
Definition enums.h:47
@ PASS_SHOW
Definition enums.h:50
@ GIT_ADD
Definition enums.h:45
@ PROCESS_COUNT
Definition enums.h:62
@ GIT_PULL
Definition enums.h:48
@ GIT_PUSH
Definition enums.h:49
PassBackendFactory, which constructs the two Pass backends on demand and hands out the one the settin...
The "qtpass" logging category.
Plain value-object holding all flat QtPass configuration.
Definition appsettings.h:36
QString gpgExecutable
Path to the gpg/gpg2 executable.
Definition appsettings.h:66
QString passStore
Password-store root path.
Definition appsettings.h:60
QString gitExecutable
Path to the git executable.
Definition appsettings.h:65
bool useGit
Enable git integration.
bool addGPGId
Auto-add .gpg-id files to git.
What the user was shown for an entry: its bytes and its folder's keys.
std::optional< QSet< QString > > now
Encrypted to now, if gpg can.
QSet< QString > before
Encrypted to before Init().
QString file
The entry's path in the store, where output goes.
bool overwrite
Whether an entry already at file may be replaced.
QString output
The ciphertext file gpg writes, inside scratch.
A move whose re-encryption is decided once it has run.
QString destFile
Where to: the entry's .gpg file, or the folder.
std::optional< bool > landed
Whether its git mv succeeded, once that has run (finished()).
The list a folder had before Init() replaced it, for the run it starts. It tells whom the change adde...
How re-encrypting one entry changes who can read it.
QSet< QString > gaining
Those, by primary fingerprint.
QSet< QString > losing
Removed recipients who still read it.
QSet< QString > listNow
The list's keys now.
bool gains
Someone not added by this change gains it.
Outcome of one reencryptPath() run; filled on the worker thread and consumed by finishReencrypt() on ...
int reencrypted
Files rewritten for the current recipients.
QList< QByteArray > unexpectedHashes
int checked
Files whose recipients were inspected.
int total
.gpg files found under the directory.
QList< QSet< QString > > unexpectedReaders
QHash< QString, QSet< QString > > stillReadByRemoved
QStringList walked
Entries whose recipients the run judged.
bool aborted
Stopped early on an error already reported.
QStringList rewritten
Those files, for EntryRecord.
A .gpg-id Init() wrote but could not commit.
QString folder
The folder whose recipients changed.
QString gitError
What Git said when the commit failed.
QHash< QString, QString > names
Primary fingerprint to a name.
QHash< QString, QString > primaries
Key ID to primary fingerprint.
QHash< QString, ListKeys > lists
.gpg-id path to its keys.
The .gpg-id Init() wrote for the run it starts: the recipients the user ticked, as written.
What saving over an existing entry would change about who reads it (readersAnEditWouldAdd()).
Definition pass.h:250
Stores GPG key info including validity, creation date, and more.
Definition userinfo.h:20
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...