QtPass Developer documentation
QtPass test coverage
Current view: top level - src/imitatepass.h (source / functions) Coverage Total Hit
Test: QtPass Lines: 100.0 % 11 11
Test Date: 2026-12-03 23:34:20 Functions: 100.0 % 2 2

            Line data    Source code
       1              : // SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
       2              : // SPDX-License-Identifier: GPL-3.0-or-later
       3              : /**
       4              :  * @file
       5              :  * @brief ImitatePass, the backend that does what `pass` does by running gpg
       6              :  * and git itself.
       7              :  */
       8              : #ifndef SRC_IMITATEPASS_H_
       9              : #define SRC_IMITATEPASS_H_
      10              : 
      11              : #include "gpgidsigner.h"
      12              : #include "nativegrep.h"
      13              : #include "pass.h"
      14              : #include "simpletransaction.h"
      15              : #include <QQueue>
      16              : #include <QSet>
      17              : #include <QTemporaryDir>
      18              : 
      19              : #include <atomic>
      20              : #include <memory>
      21              : #include <optional>
      22              : 
      23              : class QRegularExpression;
      24              : class QThread;
      25              : 
      26              : /**
      27              :  * @class ImitatePass
      28              :  * @ingroup backend
      29              :  * @brief Implementation that imitates 'pass' when the real tool is unavailable.
      30              :  *
      31              :  * ImitatePass provides a complete password store implementation using direct
      32              :  * GPG operations when 'pass' is not installed or not enabled. It handles:
      33              :  * - Direct GPG encryption/decryption
      34              :  * - Git operations via direct subprocess calls
      35              :  * - GPG key management and recipient lists
      36              :  * - File-based password storage (.gpg files)
      37              :  * - Re-encryption when recipients change
      38              :  *
      39              :  * This is used as a fallback when RealPass cannot be initialized.
      40              :  */
      41              : class ImitatePass : public Pass {
      42          926 :   Q_OBJECT
      43              : 
      44              :   friend class tst_util;
      45              :   friend class tst_imitatepass;
      46              : 
      47              : protected:
      48              :   /**
      49              :    * @brief The signer for this store's `.gpg-id`, bound to the configured gpg
      50              :    * and signing keys and to execBlocking(), so a verification on the
      51              :    * re-encryption worker can be interrupted like every other gpg run there.
      52              :    * @return A signer; cheap to build, valid while m_settings is.
      53              :    */
      54              :   auto gpgIdSigner() -> GpgIdSigner;
      55              :   /**
      56              :    * @brief Read a `.gpg-id`, verify its detached signature and parse the
      57              :    * recipients from the bytes that were verified.
      58              :    *
      59              :    * One read serves both the check and the parse, so a file swapped in
      60              :    * between cannot smuggle in a recipient the signature never covered.
      61              :    * @param gpgIdFile The `.gpg-id`.
      62              :    * @param recipients Receives the recipients; empty on failure.
      63              :    * @param why Receives, if not null, what to tell the user on failure: a
      64              :    *        bad signature, or a signed list older than one accepted before
      65              :    *        (GpgIdGeneration).
      66              :    * @return false when the file cannot be read, the signature is bad or the
      67              :    *         list is a rollback (with a signing key configured). true
      68              :    *         otherwise, also for an empty list; the caller decides what an
      69              :    *         empty list means.
      70              :    */
      71              :   auto loadVerifiedRecipients(const QString &gpgIdFile, QStringList *recipients,
      72              :                               QString *why = nullptr) -> bool;
      73              :   /**
      74              :    * @brief Write the enabled recipients to a .gpg-id, atomically: a write
      75              :    * that fails halfway (full disk, dead network share) leaves the previous
      76              :    * file in place instead of a truncated list that would then be signed
      77              :    * and encrypted to.
      78              :    * @param gpgIdFile Path to .gpg-id file.
      79              :    * @param users List of recipients.
      80              :    * @param written Receives the exact bytes written, if not null: what the
      81              :    *        signature is then made over.
      82              :    * @return true when the file was written; false after reporting through
      83              :    *         critical().
      84              :    */
      85              :   auto writeGpgIdFile(const QString &gpgIdFile, const QList<UserInfo> &users,
      86              :                       QByteArray *written = nullptr) -> bool;
      87              :   /**
      88              :    * @brief Sign a `.gpg-id` with the configured key and verify the result;
      89              :    * failures are reported through critical().
      90              :    * @param gpgIdFile Path to .gpg-id file.
      91              :    * @param contents The bytes just written as that file: the signature is
      92              :    *        made over these, not over whatever is under the name by then.
      93              :    * @return true on success, false on failure.
      94              :    */
      95              :   auto signGpgIdFile(const QString &gpgIdFile, const QByteArray &contents)
      96              :       -> bool;
      97              :   /**
      98              :    * @brief Refuse a folder, or a `.gpg-id`/`.gpg-id.sig` in it, that is a
      99              :    * link: writing there would reach outside the store.
     100              :    * @param path The folder, with its trailing separator.
     101              :    * @return Whether it was refused (and the user told).
     102              :    */
     103              :   auto refuseLinkedGpgIdFolder(const QString &path) -> bool;
     104              :   /**
     105              :    * @brief The recipients to encrypt @p file to: its folder's `.gpg-id`,
     106              :    * verified when a signing key is set.
     107              :    * @param file The entry, absolute.
     108              :    * @param recipients Receives the key IDs.
     109              :    * @return false when there are none to use (the user was told why).
     110              :    */
     111              :   auto recipientsForEntry(const QString &file, QStringList *recipients) -> bool;
     112              :   /**
     113              :    * @brief The file a copy of @p src to @p dest writes: like `pass cp`, into
     114              :    * an existing folder with `.gpg` appended. Refused (the user told) when it
     115              :    * is a link, the source itself, or taken and @p force is off.
     116              :    * @param src The entry to copy.
     117              :    * @param dest Where to, a file or a folder.
     118              :    * @param force Whether an existing entry may be replaced.
     119              :    * @return The file, or an empty string when refused.
     120              :    */
     121              :   auto copyDestination(const QString &src, const QString &dest, bool force)
     122              :       -> QString;
     123              :   /**
     124              :    * @brief Put the generation header on a list that is about to be signed:
     125              :    * reserve a generation above what this device accepted and what the
     126              :    * verified list on disk says, and bind the list to its folder, so no older
     127              :    * or relocated signed list comes back.
     128              :    * @param gpgIdFile The `.gpg-id` being written.
     129              :    * @param signer Its signer, which verifies the list on disk.
     130              :    * @param contents The key IDs, one per line; receives the header too.
     131              :    * @return false when no generation could be reserved (the user was told);
     132              :    * an unrecordable list must not be written, it would let the old one back.
     133              :    */
     134              :   auto addGenerationHeader(const QString &gpgIdFile, const GpgIdSigner &signer,
     135              :                            QByteArray *contents) -> bool;
     136              :   /**
     137              :    * @brief Bring the signature in line with the list just written: a new one
     138              :    * when signing is on, the old one removed when it is off (pass and other
     139              :    * clients would reject the new list under it).
     140              :    * @param gpgIdFile The `.gpg-id` that was written.
     141              :    * @param written Its bytes, which are what gets signed.
     142              :    * @param signer Whether and with which keys to sign.
     143              :    * @param useGit Whether the store is a Git repository QtPass manages.
     144              :    * @param sigToCommit Receives the signature file to commit, if any.
     145              :    * @return false when signing or removing failed (the user was told).
     146              :    */
     147              :   auto settleSignature(const QString &gpgIdFile, const QByteArray &written,
     148              :                        const GpgIdSigner &signer, bool useGit,
     149              :                        QString *sigToCommit) -> bool;
     150              :   /**
     151              :    * @brief Stage a `.gpg-id` and, when given, its `.sig`, and commit both in
     152              :    * one commit, so no commit in the history has a recipient list without
     153              :    * the signature that covers it. Nothing is committed when neither file
     154              :    * changed.
     155              :    * @param gpgIdFile Absolute path of the `.gpg-id`.
     156              :    * @param gpgIdSigFile Absolute path of the `.gpg-id.sig`, or empty when no
     157              :    *        signing key is configured.
     158              :    * @param out Receives the concatenated stdout of the git commands.
     159              :    * @param err Receives the concatenated stderr of the git commands.
     160              :    * @return Exit code of the first failing git command, 0 on success.
     161              :    */
     162              :   auto gitAddGpgId(const QString &gpgIdFile, const QString &gpgIdSigFile,
     163              :                    QString *out, QString *err) -> int;
     164              :   /**
     165              :    * @brief How a commit message names a file of the store: relative to the
     166              :    * store, without `.gpg` ("work/bank", "work/.gpg-id"), never the local
     167              :    * path, which the shared history would carry to everyone.
     168              :    * @param path Absolute path, normally inside the store.
     169              :    * @return The store-relative name; for a path outside the store, its
     170              :    *         file name alone.
     171              :    */
     172              :   [[nodiscard]] auto commitName(const QString &path) const -> QString;
     173              :   /**
     174              :    * @brief Check whether git already tracks a file in the store.
     175              :    * @param file Absolute path inside the password store.
     176              :    * @return true when the file is in the git index.
     177              :    */
     178              :   auto gitTracks(const QString &file) -> bool;
     179              :   /**
     180              :    * @brief The start of a `git commit` for the store: "commit", and "-S"
     181              :    * when git config pass.signcommits is true there, as pass signs its own.
     182              :    * @return The arguments, to which the message and paths are appended.
     183              :    */
     184              :   auto commitArgs() -> QStringList;
     185              :   /**
     186              :    * @brief Recipients for the directory of @p file, from its verified
     187              :    * `.gpg-id`.
     188              :    * @param file Password file path.
     189              :    * @param verified Cache of `.gpg-id` path to the recipients its verified
     190              :    *        contents held; a hit skips gpg and reuses exactly that list.
     191              :    * @param gpgId Output parameter for recipient key IDs, sorted.
     192              :    * @return true on success, false when the file is unreadable or its
     193              :    *         signature is bad (reported through critical()).
     194              :    */
     195              :   auto verifyGpgIdForDir(const QString &file,
     196              :                          QHash<QString, QStringList> &verified,
     197              :                          QStringList &gpgId) -> bool;
     198              :   /**
     199              :    * @brief Create git backup commit before re-encryption.
     200              :    * @return true if backup created or not needed, false if backup failed.
     201              :    */
     202              :   auto createBackupCommit() -> bool;
     203              :   /**
     204              :    * @brief Read recipients from file.
     205              :    * @param fileName Path to file.
     206              :    * @return List of key IDs.
     207              :    */
     208              :   auto getKeysFromFile(const QString &fileName) -> QStringList;
     209              :   /**
     210              :    * @brief The primary keys behind key IDs from an entry (ENC_TO).
     211              :    * @param ids Long key IDs of encryption subkeys.
     212              :    * @param primaries Key ID to primary fingerprint, filled from one key
     213              :    *        listing on first use.
     214              :    * @param names Primary fingerprint to its first user ID, filled with it.
     215              :    * @return The fingerprints; a key ID gpg does not know is left out.
     216              :    */
     217              :   auto primaryKeysOf(const QStringList &ids, QHash<QString, QString> &primaries,
     218              :                      QHash<QString, QString> &names) -> QSet<QString>;
     219              :   /**
     220              :    * @brief The primary keys gpg encrypts to for @p recipients, found by a
     221              :    * throwaway encryption outside the store with the arguments a real one
     222              :    * uses, so groups, `!` suffixes and key lookups count as `-r` makes them.
     223              :    * @param recipients A recipient list.
     224              :    * @param primaries As for primaryKeysOf().
     225              :    * @param names As for primaryKeysOf().
     226              :    * @param lookUp Whether gpg may look keys up (auto-key-locate, WKD) as a
     227              :    *        real encryption would; false for a list being replaced, whose
     228              :    *        removed recipients should not be fetched over the network.
     229              :    * @return The fingerprints; nothing when gpg cannot encrypt to the list.
     230              :    */
     231              :   auto keysEncryptedTo(const QStringList &recipients,
     232              :                        QHash<QString, QString> &primaries,
     233              :                        QHash<QString, QString> &names, bool lookUp = true)
     234              :       -> std::optional<QSet<QString>>;
     235              :   /**
     236              :    * @brief SHA-256 of an entry's bytes, read as a regular file without
     237              :    * following a link.
     238              :    * @param file The entry, absolute.
     239              :    * @return The hash; empty when it cannot be read so.
     240              :    */
     241              :   auto entryHash(const QString &file) const -> QByteArray;
     242              :   /**
     243              :    * @brief Re-encrypt single file with new recipients.
     244              :    * @param fileName File to re-encrypt.
     245              :    * @param recipients New recipient key IDs.
     246              :    * @param why Receives, for a failure the user can act on (the new
     247              :    * ciphertext could not be put under the entry's name), the reason for the
     248              :    * run's summary; left empty for a gpg failure, which is logged.
     249              :    * @return true on success, false on failure.
     250              :    */
     251              :   auto reencryptSingleFile(const QString &fileName,
     252              :                            const QStringList &recipients, QString *why) -> bool;
     253              :   /**
     254              :    * @brief Decrypt @p fileName for re-encryption.
     255              :    *
     256              :    * Bytes, not text: an entry that is not UTF-8 (a Latin-1 password, a
     257              :    * binary key) went through QString before, and every such byte came back
     258              :    * as U+FFFD in the re-encrypted entry.
     259              :    * The entry is read without following a link and given to gpg on
     260              :    * stdin, so a link put under its name since the run listed it is refused.
     261              :    * @param fileName The entry to read.
     262              :    * @param plaintext Receives exactly what gpg printed.
     263              :    * @param why Set when the entry is no longer a regular file; may be null.
     264              :    * @return Whether gpg decrypted it to something.
     265              :    */
     266              :   auto decryptEntry(const QString &fileName, QByteArray *plaintext,
     267              :                     QString *why) -> bool;
     268              :   /**
     269              :    * @brief Encrypt @p plaintext to @p recipients, into @p output.
     270              :    * @param output Where gpg writes the ciphertext; outside the store.
     271              :    * @param recipients The keys to encrypt to; gpg.conf adds none.
     272              :    * @param plaintext The bytes to encrypt, fed on stdin.
     273              :    * @return Whether gpg wrote the ciphertext.
     274              :    */
     275              :   auto encryptFor(const QString &output, const QStringList &recipients,
     276              :                   const QByteArray &plaintext) -> bool;
     277              :   /**
     278              :    * @brief Decrypt @p ciphertext again and compare it with @p plaintext,
     279              :    * byte for byte, so nothing replaces an entry until it is known to hold
     280              :    * what it held.
     281              :    * @param ciphertext The file gpg just wrote.
     282              :    * @param plaintext What it must decrypt to.
     283              :    * @return Whether it does.
     284              :    */
     285              :   auto ciphertextHolds(const QString &ciphertext, const QByteArray &plaintext)
     286              :       -> bool;
     287              :   /**
     288              :    * @brief Stage and commit a re-encrypted entry, when the store is a Git
     289              :    * repository QtPass manages.
     290              :    * @param fileName The entry that was replaced.
     291              :    * @return Whether the repository is up to date with the file; false makes
     292              :    * the run count the file as failed, so a partial store is not pushed.
     293              :    */
     294              :   auto commitReencrypted(const QString &fileName) -> bool;
     295              :   /**
     296              :    * @brief Resolve destination for move operation.
     297              :    * @param src Source path.
     298              :    * @param dest Destination path.
     299              :    * @param force Overwrite existing.
     300              :    * @return Resolved destination path.
     301              :    */
     302              :   auto resolveMoveDestination(const QString &src, const QString &dest,
     303              :                               bool force) -> QString;
     304              : 
     305              : public:
     306              :   /**
     307              :    * @brief Execute git move operation.
     308              :    * @param src Source path.
     309              :    * @param destFile Destination path.
     310              :    * @param force Overwrite existing.
     311              :    */
     312              :   void executeMoveGit(const QString &src, const QString &destFile, bool force);
     313              : 
     314              :   /**
     315              :    * @brief Commit one path to git.
     316              :    * @param file Changed file path.
     317              :    * @param msg Commit message.
     318              :    */
     319              :   void gitCommit(const QString &file, const QString &msg);
     320              :   /**
     321              :    * @brief Commit these paths and nothing else: a change someone staged
     322              :    * meanwhile stays staged, out of a commit autoPush would send.
     323              :    * @param files Changed paths (a moved entry's old and new path).
     324              :    * @param msg Commit message.
     325              :    */
     326              :   void gitCommit(const QStringList &files, const QString &msg);
     327              : 
     328              :   /**
     329              :    * @brief Execute git command.
     330              :    * @param id Process identifier.
     331              :    * @param args Git arguments.
     332              :    * @param input Input to stdin.
     333              :    * @param readStdout Capture stdout.
     334              :    * @param readStderr Capture stderr.
     335              :    */
     336              :   void executeGit(PROCESS id, const QStringList &args,
     337              :                   QString input = QString(), bool readStdout = true,
     338              :                   bool readStderr = true);
     339              :   /**
     340              :    * @brief Git is enabled and an executable is configured.
     341              :    * @return true when git commands can actually run.
     342              :    */
     343              :   auto gitConfigured() const -> bool;
     344              :   /**
     345              :    * @brief gitConfigured() plus a status message when git is enabled but
     346              :    * no executable is configured.
     347              :    * @return true when git commands can actually run.
     348              :    */
     349              :   auto gitReady() -> bool;
     350              :   /**
     351              :    * @brief Execute GPG command.
     352              :    * @param id Process identifier.
     353              :    * @param args GPG arguments.
     354              :    * @param input Input to stdin.
     355              :    * @param readStdout Capture stdout.
     356              :    * @param readStderr Capture stderr.
     357              :    */
     358              :   void executeGpg(PROCESS id, const QStringList &args,
     359              :                   QString input = QString(), bool readStdout = true,
     360              :                   bool readStderr = true);
     361              : 
     362              :   /**
     363              :    * @class TransactionHelper
     364              :    * @brief RAII helper for wrapping operations in transactions.
     365              :    */
     366              :   class TransactionHelper {
     367              :     /** @brief The transaction being bracketed; not owned. */
     368              :     SimpleTransaction *m_transaction;
     369              :     /** @brief What the transaction reports as once its last step ends. */
     370              :     PROCESS m_result;
     371              : 
     372              :   public:
     373              :     /**
     374              :      * @brief Start transaction.
     375              :      * @param trans Transaction object.
     376              :      * @param result Result code on commit.
     377              :      */
     378              :     TransactionHelper(SimpleTransaction *trans, PROCESS result)
     379              :         : m_transaction(trans), m_result(result) {
     380          127 :       m_transaction->transactionStart();
     381          127 :     }
     382              :     /**
     383              :      * @brief End transaction on destruction.
     384              :      */
     385          127 :     ~TransactionHelper() { m_transaction->transactionEnd(m_result); }
     386              :   };
     387              : 
     388              : protected:
     389              :   /// storeEnvironment() as it was when the worker started; the worker's
     390              :   /// processes run in it.
     391              :   QProcessEnvironment m_reencryptEnv;
     392              :   /**
     393              :    * @brief Executor::executeBlocking() for the re-encryption helpers.
     394              :    *
     395              :    * Runs in the store's environment (storeEnvironment(); on the worker, the
     396              :    * copy taken when it started), which carries the git ceiling QtPass's own
     397              :    * does not. On the owning thread this is a plain blocking run. On the worker
     398              :    * thread it hands m_reencryptCancel to the cancellable executeBlocking()
     399              :    * overload: nothing is started once the flag is set, and a process that is
     400              :    * running when it gets set is terminated (then killed) by the worker thread,
     401              :    * which is what lets cancelReencryptPath() and the destructor interrupt an
     402              :    * active gpg or git without touching its QProcess or pid.
     403              :    * @param app The program.
     404              :    * @param args Its arguments.
     405              :    * @param input What to write to its stdin.
     406              :    * @param process_out Receives stdout, if not null.
     407              :    * @param process_err Receives stderr, if not null.
     408              :    * @return Exit code, or -1 when refused, failed to start or interrupted.
     409              :    */
     410              :   [[nodiscard]] auto execBlocking(const QString &app, const QStringList &args,
     411              :                                   const QString &input = QString(),
     412              :                                   QString *process_out = nullptr,
     413              :                                   QString *process_err = nullptr) -> int;
     414              :   /**
     415              :    * @brief Overload capturing stdout (and stderr) without stdin input.
     416              :    * @param app The program.
     417              :    * @param args Its arguments.
     418              :    * @param process_out Receives stdout.
     419              :    * @param process_err Receives stderr, if not null.
     420              :    * @return As the overload above.
     421              :    */
     422              :   [[nodiscard]] auto execBlocking(const QString &app, const QStringList &args,
     423              :                                   QString *process_out,
     424              :                                   QString *process_err = nullptr) -> int;
     425              :   /**
     426              :    * @brief execBlocking() on bytes (Executor::executeBlockingRaw()), for an
     427              :    * entry's plaintext, which need not be UTF-8.
     428              :    * @param app The program.
     429              :    * @param args Its arguments.
     430              :    * @param input Bytes to write to its stdin (empty = none).
     431              :    * @param process_out Receives stdout as written, if not null.
     432              :    * @return As execBlocking().
     433              :    */
     434              :   [[nodiscard]] auto execBlockingRaw(const QString &app,
     435              :                                      const QStringList &args,
     436              :                                      const QByteArray &input,
     437              :                                      QByteArray *process_out) -> int;
     438              :   /**
     439              :    * @brief Give @p process the environment for the calling thread: the
     440              :    * store's on the owning thread, the re-encryption run's on its worker.
     441              :    * @param process The process to set up.
     442              :    * @return The cancel flag to pass on: null on the owning thread, the
     443              :    *         re-encryption run's on the worker.
     444              :    */
     445              :   auto prepareBlocking(QProcess &process) -> const std::atomic_bool *;
     446              :   /**
     447              :    * @brief Run git with `-C <store>` in the store, blocking.
     448              :    * @param args The git arguments (without the executable or `-C`).
     449              :    * @param out Receives stdout; may be null.
     450              :    * @return true when git ran and exited 0 (git on and configured).
     451              :    */
     452              :   auto storeGit(const QStringList &args, QString *out) -> bool override;
     453              :   /**
     454              :    * @brief Handle process completion.
     455              :    * @param id Process identifier.
     456              :    * @param exitCode Process exit code.
     457              :    * @param out Standard output from the process.
     458              :    * @param err Standard error from the process.
     459              :    */
     460              :   void finished(int id, int exitCode, const QString &out,
     461              :                 const QString &err) override;
     462              : 
     463              :   /**
     464              :    * @brief Whether the failed insert had placed its entry (see
     465              :    * placeEncryptedFile()) before a later git step failed.
     466              :    * @param err Not needed: the placement is known, not inferred.
     467              :    * @return true when the entry is in the store.
     468              :    */
     469            1 :   [[nodiscard]] auto insertWritten(const QString &err) const -> bool override {
     470              :     Q_UNUSED(err);
     471            1 :     return m_insertPlaced;
     472              :   }
     473              : 
     474              :   /**
     475              :    * @brief Open a transaction for every execution.
     476              :    *
     477              :    * In native (imitate) mode each wrapped command is a git/gpg transaction;
     478              :    * register it before the subprocess runs.
     479              :    * @param id Process identifier.
     480              :    */
     481              :   void beforeExecute(PROCESS id) override;
     482              : 
     483              : public:
     484              :   /**
     485              :    * @brief Construct the backend and connect its content search.
     486              :    */
     487              :   ImitatePass();
     488              :   /**
     489              :    * @brief Cancel a running content search, and cancel and join a running
     490              :    * re-encryption worker, before the members they use go away.
     491              :    */
     492              :   ~ImitatePass() override;
     493              : 
     494              :   // Git operations
     495              :   /**
     496              :    * @brief Initialize Git repository.
     497              :    */
     498              :   void GitInit() override;
     499              :   /**
     500              :    * @brief Pull from remote.
     501              :    */
     502              :   void GitPull() override;
     503              :   /**
     504              :    * @brief Run git pull in the store and wait for it, at most @p timeoutMs.
     505              :    * @param timeoutMs Most milliseconds to wait (Pass::kBlockingPullMs).
     506              :    */
     507              :   void GitPull_b(int timeoutMs) override;
     508              :   /**
     509              :    * @brief Push to remote. While a re-encryption runs the push is held
     510              :    * (Users ▸ OK and a copy ask for it as soon as their commit is made, before
     511              :    * the worker is done) and made when the run ends with every file
     512              :    * re-encrypted; after a failed or cancelled run nothing is pushed.
     513              :    */
     514              :   void GitPush() override;
     515              : 
     516              :   // Password operations
     517              :   /**
     518              :    * @brief Show decrypted password.
     519              :    * @param file Path to the password file relative to store root.
     520              :    */
     521              :   void Show(QString file) override;
     522              :   /**
     523              :    * @brief Insert new password.
     524              :    * @param file Path to the password file.
     525              :    * @param newValue Password content to store.
     526              :    * @param overwrite true to overwrite an existing file.
     527              :    */
     528              :   void Insert(QString file, QString newValue, bool overwrite) override;
     529              :   auto readersAnEditWouldAdd(const QString &file) -> EditReaders override;
     530              :   /**
     531              :    * @brief Remove password.
     532              :    * @param file Path to the file or directory to remove.
     533              :    * @param isDir true if removing a directory.
     534              :    */
     535              :   void Remove(QString file, bool isDir) override;
     536              :   /**
     537              :    * @brief Initialize store.
     538              :    *
     539              :    * Writes (and signs) the folder's `.gpg-id`, commits it when Git is used
     540              :    * and re-encrypts the folder to it. When that commit fails the entries are
     541              :    * still re-encrypted, without any Git step, and a critical() afterwards
     542              :    * says the change is not committed and whether the re-encryption
     543              :    * completed. Nothing is written while `.gpg-id` or `.gpg-id.sig` is
     544              :    * there as something other than a regular file (a folder).
     545              :    * @param path Root path of the password store.
     546              :    * @param users List of recipient GPG keys.
     547              :    */
     548              :   void Init(QString path, const QList<UserInfo> &users) override;
     549              : 
     550              : protected:
     551              :   /**
     552              :    * @brief Pass::fullKeyListing() in the calling thread's environment, so a
     553              :    *        re-encryption run's worker lists the store's keyring.
     554              :    * @param listing Receives the colon listing.
     555              :    * @return As Pass::fullKeyListing().
     556              :    */
     557              :   auto fullKeyListing(QString *listing) -> int override;
     558              : 
     559              : public:
     560              :   /**
     561              :    * @brief Re-encrypt entire directory.
     562              :    *
     563              :    * Emits startReencryptPath() synchronously, then runs the scan and the
     564              :    * per-file gpg calls on a worker thread. Progress is reported through
     565              :    * reencryptProgress(); per-file failures are collected and reported in a
     566              :    * single critical() once the run is over, followed by endReencryptPath().
     567              :    * A second call while a run is active is ignored. Dot-named entries
     568              :    * (`.env.gpg`) are re-encrypted too, as with `pass init`; hidden folders
     569              :    * (`.git`, `.stversions`) are not entered.
     570              :    * @param dir Directory path, or one entry's `.gpg` file (a move
     571              :    *        re-encrypts what it moved, not the folder around it).
     572              :    */
     573              :   void reencryptPath(const QString &dir);
     574              :   /**
     575              :    * @brief Re-encrypt @p dir under @p settings, the current profile's.
     576              :    *
     577              :    * This backend re-encrypts also when pass is the active one, and then is
     578              :    * not re-initialised on a profile switch: without this it would decrypt
     579              :    * the current profile's entries and encrypt them to the recipients and
     580              :    * signing policy of the profile it last ran for. The settings are taken
     581              :    * only when no run is active, so a running one keeps its own.
     582              :    * @param dir Directory path.
     583              :    * @param settings The current settings.
     584              :    */
     585              :   void reencryptPath(const QString &dir, const AppSettings &settings);
     586              :   /**
     587              :    * @brief Ask a running reencryptPath() to stop.
     588              :    *
     589              :    * Only sets a flag. The worker starts no further gpg or git process, and
     590              :    * the one it is blocked on (gpg waiting on pinentry, say) is terminated by
     591              :    * the worker itself, and killed if it is still running after a short grace
     592              :    * period, so the cancel takes effect promptly rather than after the current
     593              :    * file. The store stays
     594              :    * consistent: reencryptSingleFile() only replaces a file once the new
     595              :    * ciphertext is verified, so an interrupted file is left untouched, or
     596              :    * already re-encrypted but not yet committed when git was the process that
     597              :    * was interrupted. The remaining files are left untouched and the
     598              :    * interrupted file is not reported as a failure. endReencryptPath() is
     599              :    * still emitted when the worker has stopped.
     600              :    */
     601              :   void cancelReencryptPath();
     602              :   /**
     603              :    * @brief Re-encrypt @p files in @p dir after the user agreed to it.
     604              :    *
     605              :    * A run leaves alone an entry encrypted to other keys than its folder had
     606              :    * (unexpectedRecipients()): someone who can read one folder could have
     607              :    * copied it in from a folder they cannot read, and re-encrypting it would
     608              :    * hand them its plaintext. This runs @p dir again with @p files taken as
     609              :    * they are.
     610              :    * Only entries the last run named, each only while its bytes are those it
     611              :    * was named with; the run takes those and nothing else.
     612              :    * @param dir The folder of the run that found them.
     613              :    * @param files The entries, as unexpectedRecipients() named them.
     614              :    * @param settings The current settings, as for reencryptPath().
     615              :    */
     616              :   void reencryptAlso(const QString &dir, const QStringList &files,
     617              :                      const AppSettings &settings);
     618              : 
     619              : signals:
     620              :   /**
     621              :    * @brief A reencryptPath() run is about to start its worker thread.
     622              :    *
     623              :    * The main window disables the interface and shows a progress dialog
     624              :    * with a Cancel button on it. Always followed by endReencryptPath().
     625              :    */
     626              :   void startReencryptPath();
     627              :   /**
     628              :    * @brief A reencryptPath() run is over, whether it finished, failed, was
     629              :    * cancelled or was refused; the main window releases the interface.
     630              :    *
     631              :    * Also emitted without a preceding startReencryptPath() when the folder
     632              :    * is refused before anything starts.
     633              :    */
     634              :   void endReencryptPath();
     635              :   /**
     636              :    * @brief Re-encryption progress: @p current of @p total files checked.
     637              :    *
     638              :    * Emitted from the worker thread; connect with a queued (or automatic)
     639              :    * connection.
     640              :    * @param current Number of files checked so far, including this one.
     641              :    * @param total Total number of files found by the scan.
     642              :    */
     643              :   void reencryptProgress(int current, int total);
     644              :   /**
     645              :    * @brief A run left @p files alone: re-encrypting one would let someone
     646              :    * on its folder's list read it who cannot now, and whom the change of the
     647              :    * list did not add. An entry copied in from a folder they cannot read
     648              :    * must not reach them without the user's say. reencryptAlso() takes them
     649              :    * once the user agreed. Emitted after endReencryptPath().
     650              :    * @param dir The folder of the run.
     651              :    * @param files The entries left alone, absolute.
     652              :    * @param details For each, who would gain it, and who was removed from
     653              :    *        the list and still reads it (the run then holds the automatic
     654              :    *        push).
     655              :    */
     656              :   void unexpectedRecipients(const QString &dir, const QStringList &files,
     657              :                             const QStringList &details);
     658              : 
     659              :   // Pass interface
     660              : public:
     661              :   /**
     662              :    * @brief Move password file.
     663              :    *
     664              :    * As `pass mv`, what moved is then re-encrypted for the recipients where
     665              :    * it landed, when another `.gpg-id` applies there than where it came from
     666              :    * (a folder with its own list takes that along): see reencryptMoved().
     667              :    * With Git that happens once the queued git mv has run. No message box
     668              :    * opens while the move's Git commands are being queued.
     669              :    * @param src Source path.
     670              :    * @param dest Destination path.
     671              :    * @param force true to overwrite existing destination.
     672              :    */
     673              :   void Move(const QString src, const QString dest, const bool force) override;
     674              :   /**
     675              :    * @brief Copy password file.
     676              :    * @param src Source path.
     677              :    * @param dest Destination path.
     678              :    * @param force true to overwrite existing destination.
     679              :    */
     680              :   void Copy(const QString src, const QString dest, const bool force) override;
     681              :   /**
     682              :    * @brief Search all password content by GPG-decrypting each .gpg file.
     683              :    *
     684              :    * Pattern is interpreted as a QRegularExpression (PCRE-like); RealPass::Grep
     685              :    * uses the same search, so both backends match alike.
     686              :    *
     687              :    * @param pattern Search pattern (QRegularExpression).
     688              :    * @param caseInsensitive true for case-insensitive search.
     689              :    */
     690              :   void Grep(QString pattern, bool caseInsensitive) override;
     691              :   /**
     692              :    * @brief Stop the running search (NativeGrep::cancel()).
     693              :    */
     694           28 :   void CancelGrep() override { m_grep.cancel(); }
     695              : 
     696              : private:
     697              :   /// Groups the git/gpg processes of one operation (Insert, Remove, Move,
     698              :   /// Copy) into a single completion; see finished() and TransactionHelper.
     699              :   SimpleTransaction m_transaction;
     700              :   /**
     701              :    * @brief A move whose re-encryption is decided once it has run.
     702              :    */
     703              :   struct PendingMove {
     704              :     QString src;      ///< What was moved.
     705              :     QString destFile; ///< Where to: the entry's `.gpg` file, or the folder.
     706              :     QString fromList; ///< The `.gpg-id` that applied to it before.
     707              :     /// Whether its git mv succeeded, once that has run (finished()).
     708              :     std::optional<bool> landed;
     709              :   };
     710              :   /// Moves through Git, in order, each settled when its PASS_MOVE ends.
     711              :   QQueue<PendingMove> m_pendingMoves;
     712              :   /// What settled moves still need re-encrypted: one run each, started by
     713              :   /// startMovedReencrypts() once no run is in flight. Pushes wait for them.
     714              :   QStringList m_movedToReencrypt;
     715              :   /// The deferred push (m_pushAfterReencrypt) includes one asked for by
     716              :   /// hand, which a hold (autoPushHeld()) does not stop.
     717              :   bool m_deferredPushByHand = false;
     718              :   /**
     719              :    * @brief Start the runs in m_movedToReencrypt, one at a time, while none
     720              :    * is in flight; then send a deferred push once nothing is left.
     721              :    */
     722              :   void startMovedReencrypts();
     723              :   /**
     724              :    * @brief Make the push GitPush() deferred, once no run is in flight and
     725              :    * no move is waiting; an automatic one only while the store is not held.
     726              :    */
     727              :   void sendDeferredPush();
     728              :   /**
     729              :    * @brief Queue a re-encryption of what @p move moved, if it moved and
     730              :    * another `.gpg-id` applies where it landed; a folder that has its own
     731              :    * list is left as it is. Only that entry or folder, not what is around
     732              :    * it; startMovedReencrypts() starts it.
     733              :    * @param move The move, as Move() recorded it.
     734              :    */
     735              :   void reencryptMoved(const PendingMove &move);
     736              :   /**
     737              :    * @brief Refuse a move of @p src to @p destFile that touches what an
     738              :    * earlier move or a re-encryption still has to settle: moving it again
     739              :    * meanwhile would leave the run for the place it is no longer at.
     740              :    * @param src What is to be moved.
     741              :    * @param destFile Where to, as resolveMoveDestination() gave it.
     742              :    * @return true if refused (the user told).
     743              :    */
     744              :   auto refuseOverlappingMove(const QString &src, const QString &destFile)
     745              :       -> bool;
     746              :   /// Background search over the decrypted store; relays to finishedGrep.
     747              :   NativeGrep m_grep;
     748              :   /**
     749              :    * @brief stdout of the steps of the transaction in flight, collected by
     750              :    * finished() and handed on, then cleared, when its last step ends.
     751              :    */
     752              :   QString m_transactionOutput;
     753              : 
     754              :   /// An Insert() whose gpg is running or queued: the private directory gpg
     755              :   /// writes into (removed with it), the entry it is for, and whether an
     756              :   /// existing entry may be replaced. Consumed by finished() when the gpg
     757              :   /// step ends; one per Insert(), in order.
     758              :   struct PendingInsert {
     759              :     /** @brief The private directory gpg writes into; removed with this. */
     760              :     std::shared_ptr<QTemporaryDir> scratch;
     761              :     /** @brief The ciphertext file gpg writes, inside @ref scratch. */
     762              :     QString output;
     763              :     /** @brief The entry's path in the store, where @ref output goes. */
     764              :     QString file;
     765              :     /** @brief Whether an entry already at @ref file may be replaced. */
     766              :     bool overwrite = false;
     767              :   };
     768              :   /** @brief The inserts whose gpg step has not ended yet, oldest first. */
     769              :   QQueue<PendingInsert> m_pendingInserts;
     770              :   /// The insert whose gpg step ended last placed its entry in the store; its
     771              :   /// git steps may still fail. Set per gpg completion in finished(), not per
     772              :   /// Insert() call, so a second queued insert's failure is not reported with
     773              :   /// an earlier insert's answer.
     774              :   bool m_insertPlaced = false;
     775              : 
     776              :   /**
     777              :    * @brief Bring the ciphertext gpg wrote to @p output into the store as
     778              :    * @p file (Util::copyFileReplacing): through a temporary created next to
     779              :    * the entry and written by its open handle, then the operating system's
     780              :    * rename, which replaces the entry under that name (or, without
     781              :    * @p overwrite, fails when one has appeared) and follows nothing. Reports
     782              :    * nothing itself: Insert()'s finished() routes the reason through the
     783              :    * failed-operation path once the queued git steps are cancelled, and
     784              :    * re-encryption lists it in the run's summary.
     785              :    * @param output The file gpg wrote, in a directory of QtPass's own.
     786              :    * @param file The entry's path.
     787              :    * @param overwrite Whether an entry already there may be replaced.
     788              :    * @param error Receives why @p file could not be written, if not.
     789              :    * @return Whether @p file now holds the new ciphertext.
     790              :    */
     791              :   auto placeEncryptedFile(const QString &output, const QString &file,
     792              :                           bool overwrite, QString *error) -> bool;
     793              :   /**
     794              :    * @brief Finish the oldest pending insert after its gpg step: place the
     795              :    * ciphertext with placeEncryptedFile(), unless gpg failed or a Git
     796              :    * operation stopped half-way meanwhile. Sets m_insertPlaced.
     797              :    * @param exitCode The gpg step's exit code.
     798              :    * @param error Receives why the entry was not placed, if so.
     799              :    * @return @p exitCode when gpg failed, 1 when the entry was not placed,
     800              :    * else 0.
     801              :    */
     802              :   auto placePendingInsert(int exitCode, QString *error) -> int;
     803              : 
     804              :   /**
     805              :    * @brief Outcome of one reencryptPath() run; filled on the worker thread and
     806              :    * consumed by finishReencrypt() on the owning thread.
     807              :    */
     808              :   struct ReencryptResult;
     809              :   /// Set while a re-encryption run is pending or on the worker thread.
     810              :   bool m_reencryptActive = false;
     811              :   /// A push was asked for while a run was active (GitPush()); the run makes
     812              :   /// it at its end, when every file went through.
     813              :   bool m_pushAfterReencrypt = false;
     814              :   /// The folder the re-encryption in flight covers, for the push hold.
     815              :   QString m_reencryptScope;
     816              :   /// Set while finishReencrypt() pushes, so GitPush() does not hold it.
     817              :   bool m_reencryptPushing = false;
     818              :   /// Set by cancelReencryptPath() and the destructor; read by the worker
     819              :   /// between files and polled by Executor::executeBlocking() while the worker
     820              :   /// waits on a process, which the worker then ends itself. The flag is the
     821              :   /// only thing shared with the worker: its QProcess is not thread-safe and
     822              :   /// is never touched from another thread.
     823              :   std::atomic<bool> m_reencryptCancel{false};
     824              :   /**
     825              :    * @brief The re-encryption worker while it runs, null otherwise. The
     826              :    * destructor sets m_reencryptCancel and joins it.
     827              :    */
     828              :   QThread *m_reencryptThread = nullptr;
     829              :   /**
     830              :    * @brief Start the worker thread once the Executor queue is idle.
     831              :    * @param dir Directory passed to reencryptPath().
     832              :    */
     833              :   void startReencryptWorker(const QString &dir);
     834              :   /**
     835              :    * @brief Worker-thread body: scan @p dir and re-encrypt stale files.
     836              :    * @param dir Directory passed to reencryptPath().
     837              :    * @return Counts and the list of files that could not be re-encrypted.
     838              :    */
     839              :   auto reencryptFiles(const QString &dir) -> ReencryptResult;
     840              :   /// Per list: the primary keys gpg encrypts to now and before Init().
     841              :   struct ListKeys;
     842              :   /// What one run has learnt about who reads what.
     843              :   struct WhoReads;
     844              :   /// How re-encrypting one entry changes who can read it.
     845              :   struct ReaderChange;
     846              :   /**
     847              :    * @brief The checks a run makes after its own pull, before it writes:
     848              :    * no unfinished Git operation, @p dir not a link or behind one, the list
     849              :    * Init() wrote unchanged by the pull; then the leftovers of an
     850              :    * interrupted run, and the backup commit.
     851              :    * @param dir Directory passed to reencryptPath().
     852              :    * @param result Marked aborted or cancelled when the run stops.
     853              :    * @return Whether the run goes on.
     854              :    */
     855              :   auto startReencryptRun(const QString &dir, ReencryptResult &result) -> bool;
     856              :   /**
     857              :    * @brief Whether an entry that would gain readers is taken without a
     858              :    * question: the user moved or copied it in, or agreed to it in
     859              :    * reencryptAlso() while its bytes and its list's keys are unchanged.
     860              :    * @param fileName The entry.
     861              :    * @param listNow The keys its list encrypts to now.
     862              :    * @return Whether it is re-encrypted without asking.
     863              :    */
     864              :   [[nodiscard]] auto isTrustedEntry(const QString &fileName,
     865              :                                     const QSet<QString> &listNow) const -> bool;
     866              :   /**
     867              :    * @brief The keys of the list at @p gpgIdPath, worked out once per run.
     868              :    * @param gpgIdPath The `.gpg-id` the entry falls under.
     869              :    * @param gpgId The recipients read from it.
     870              :    * @param who The run's record; the result is kept in it.
     871              :    * @return Its keys now and before Init() replaced it.
     872              :    */
     873              :   auto listKeysFor(const QString &gpgIdPath, const QStringList &gpgId,
     874              :                    WhoReads &who) -> const ListKeys &;
     875              :   /**
     876              :    * @brief Who would gain an entry by re-encrypting it to its list, other
     877              :    * than those this change added, and who was taken off and still reads
     878              :    * it.
     879              :    * @param fileName The entry.
     880              :    * @param keys The recipient key IDs it is encrypted to.
     881              :    * @param lk Its list's keys (listKeysFor()).
     882              :    * @param who The run's record of key IDs and names.
     883              :    * @return The change; nobody gains when gpg cannot encrypt to the list.
     884              :    */
     885              :   auto readerChangeOf(const QString &fileName, const QStringList &keys,
     886              :                       const ListKeys &lk, WhoReads &who) -> ReaderChange;
     887              :   /**
     888              :    * @brief The names of @p fprs for a question or a failure, sorted.
     889              :    * @param fprs Primary fingerprints, or kUnknownReader.
     890              :    * @param names Fingerprint to name, as the run learnt them.
     891              :    * @return The names, comma-separated.
     892              :    */
     893              :   static auto namedReaders(const QSet<QString> &fprs,
     894              :                            const QHash<QString, QString> &names) -> QString;
     895              :   /**
     896              :    * @brief Leave an entry that would gain readers for the user: named in
     897              :    * the question after the run, with the bytes it is named for, or
     898              :    * reported as failed when its bytes cannot be read to hold a yes to.
     899              :    * @param fileName The entry.
     900              :    * @param keys The recipient key IDs it is encrypted to.
     901              :    * @param change Who gains it and who still reads it.
     902              :    * @param who The run's record of key IDs and names.
     903              :    * @param result Gets the question or the failure.
     904              :    * @return Whether its removed-reader record is kept (reported as failed).
     905              :    */
     906              :   auto holdForAgreement(const QString &fileName, const QStringList &keys,
     907              :                         const ReaderChange &change, const WhoReads &who,
     908              :                         ReencryptResult &result) -> bool;
     909              :   /**
     910              :    * @brief Check one entry and re-encrypt it to @p gpgId when it is not
     911              :    * encrypted to those keys yet, unless it would gain readers no one
     912              :    * agreed to.
     913              :    * @param fileName The entry.
     914              :    * @param gpgId The recipients of its folder.
     915              :    * @param who The run's record of who reads what.
     916              :    * @param result Gets the entry's outcome.
     917              :    * @return false when the run was cancelled meanwhile.
     918              :    */
     919              :   auto reencryptEntry(const QString &fileName, const QStringList &gpgId,
     920              :                       WhoReads &who, ReencryptResult &result) -> bool;
     921              :   /**
     922              :    * @brief Pull before a run, when the store is a Git repository and
     923              :    * automatic pulling is on.
     924              :    * @return Whether re-encrypting may go ahead: false when a failed pull
     925              :    * left unmerged files, the check for them fails, or HEAD is still behind
     926              :    * its upstream (the checkout may have stopped half-way).
     927              :    */
     928              :   auto pullBeforeReencrypt() -> bool;
     929              :   /**
     930              :    * @brief The entries under @p dir a run considers, telling the user about
     931              :    * anything skipped for not being a regular file.
     932              :    * @param dir Directory to walk, recursively.
     933              :    * @param failed Receives a failure line for every folder that could not be
     934              :    *        read: its entries are not in the result, and the run must not
     935              :    *        pass for complete.
     936              :    * @return The `.gpg` files, links and special files left out.
     937              :    */
     938              :   auto entriesToReencrypt(const QString &dir, QStringList *failed)
     939              :       -> QStringList;
     940              :   /**
     941              :    * @brief The verified recipients for the folder @p fileName sits in.
     942              :    * @param fileName An entry in the folder.
     943              :    * @param verified Cache of the `.gpg-id` files already checked.
     944              :    * @param gpgId Receives the recipients to encrypt that folder to.
     945              :    * @param result Marked cancelled or aborted when the answer is no.
     946              :    * @return Whether the run may go on with this folder.
     947              :    */
     948              :   auto recipientsForDir(const QString &fileName,
     949              :                         QHash<QString, QStringList> &verified,
     950              :                         QStringList &gpgId, ReencryptResult &result) -> bool;
     951              :   /**
     952              :    * @brief Deal with what a crashed or failed earlier run left under @p dir
     953              :    * before touching anything: stale temporaries (today's staged
     954              :    * `.qtpass-XXXXXX.tmp`, 1.8.x's `<entry>.reencrypt.tmp`, the
     955              :    * `<entry>.XXXXXX.tmp` of builds in between) are removed unless they were
     956              :    * modified within the hour, where they may be another QtPass's write in
     957              :    * flight on a shared store; a 1.8.x `<entry>.reencrypt.bak` whose original
     958              :    * is missing is put back, one next to a present original is reported and
     959              :    * left alone (both are valid ciphertexts, the choice is the user's).
     960              :    * Whatever needs a human is reported in one critical(), the list capped.
     961              :    * @param dir Directory to scan, recursively.
     962              :    * @return false when something was reported that needs a human first.
     963              :    */
     964              :   auto recoverReencryptLeftovers(const QString &dir) -> bool;
     965              :   /**
     966              :    * @brief Remove a stale temporary a crashed run left, unless it was
     967              :    * modified within the hour: on a shared store it may be another QtPass's
     968              :    * write in flight under the same name.
     969              :    * @param path The temporary, a regular file.
     970              :    */
     971              :   void dropStaleTemporary(const QString &path);
     972              :   /**
     973              :    * @brief Put a 1.8.x backup back in its entry's place when the entry is
     974              :    * missing; report it when both exist (both are valid ciphertexts, the
     975              :    * choice is the user's) or when the rename fails.
     976              :    * @param path The `<entry>.reencrypt.bak` file.
     977              :    * @param problems Gets what to tell the user, if anything.
     978              :    * @return Whether nothing needs a human first.
     979              :    */
     980              :   auto restoreBackup(const QString &path, QStringList &problems) -> bool;
     981              :   /**
     982              :    * @brief Note for the user that a leftover is not a regular file and was
     983              :    * left.
     984              :    * @param path The leftover.
     985              :    * @param problems Gets the sentence for it.
     986              :    */
     987              :   void reportUnrestorable(const QString &path, QStringList &problems);
     988              :   /**
     989              :    * @brief Report the outcome of a run and emit endReencryptPath().
     990              :    * @param result Outcome produced by reencryptFiles().
     991              :    */
     992              :   void finishReencrypt(const ReencryptResult &result);
     993              :   /**
     994              :    * @brief Tell the user which entries a run could not re-encrypt, the
     995              :    * first few by name.
     996              :    * @param failed The entries that failed; nothing is shown when empty.
     997              :    */
     998              :   void reportFailedEntries(const QStringList &failed);
     999              :   /**
    1000              :    * @brief Bring the record of entries a removed recipient still reads up
    1001              :    * to date with a run, and hold the automatic push for the run's folder
    1002              :    * when the change is not done there, or release it after a full, clean
    1003              :    * run.
    1004              :    * @param result The run's outcome.
    1005              :    * @param agreedRun Whether the run took only entries the user agreed to,
    1006              :    *        which settles those, not the folder's other holds.
    1007              :    * @return Whether an entry in the run's folder is still read by someone
    1008              :    *         the change removed.
    1009              :    */
    1010              :   auto settleAutoPushHold(const ReencryptResult &result, bool agreedRun)
    1011              :       -> bool;
    1012              :   /**
    1013              :    * @brief The status line for a run, and the push after it when one is
    1014              :    * due and nothing holds it.
    1015              :    * @param result The run's outcome.
    1016              :    * @param stillRead Whether a removed recipient still reads an entry in
    1017              :    *        the run's folder (settleAutoPushHold()).
    1018              :    */
    1019              :   void reportReencryptOutcome(const ReencryptResult &result, bool stillRead);
    1020              :   /**
    1021              :    * @brief Keep what the run named in unexpectedRecipients(), with the
    1022              :    * bytes and readers it was named for: reencryptAlso() takes the user's
    1023              :    * yes from there.
    1024              :    * @param result The run's outcome.
    1025              :    */
    1026              :   void rememberUnexpected(const ReencryptResult &result);
    1027              : 
    1028              :   /**
    1029              :    * @brief A `.gpg-id` Init() wrote but could not commit.
    1030              :    */
    1031            8 :   struct UncommittedGpgId {
    1032              :     QString folder;   ///< The folder whose recipients changed.
    1033              :     QString gitError; ///< What Git said when the commit failed.
    1034              :   };
    1035              :   /// Set by reencryptWithoutGit() for the run it starts and cleared by
    1036              :   /// finishReencrypt(): that run does no Git at all (no pull, backup
    1037              :   /// commit, per-entry commit or push) and ends with
    1038              :   /// reportUncommittedGpgId(). Written only on the owning thread while no
    1039              :   /// worker runs; the worker only reads it, through reencryptUsesGit().
    1040              :   std::optional<UncommittedGpgId> m_uncommittedGpgId;
    1041              :   /**
    1042              :    * @brief The `.gpg-id` Init() wrote for the run it starts: the recipients
    1043              :    * the user ticked, as written.
    1044              :    */
    1045           40 :   struct WrittenGpgId {
    1046              :     QString file;     ///< The list's path.
    1047              :     QByteArray bytes; ///< What Init() wrote there.
    1048              :   };
    1049              :   /// Set by Init() for the run it starts and cleared by finishReencrypt(),
    1050              :   /// or at once when that run is refused before it starts. After its pull
    1051              :   /// the worker stops when the list no longer holds these bytes: a merge
    1052              :   /// changed the recipients the user chose. Written only on the owning
    1053              :   /// thread while no worker runs; the worker only reads it.
    1054              :   std::optional<WrittenGpgId> m_writtenGpgId;
    1055              :   /**
    1056              :    * @brief The list a folder had before Init() replaced it, for the run it
    1057              :    * starts. It tells whom the change added (who then gains every entry, as
    1058              :    * adding someone means) and whom it removed (who may still read an entry
    1059              :    * left alone). An entry is not compared with it: the worker asks before
    1060              :    * an entry gains anyone on the new list other than those added.
    1061              :    */
    1062           26 :   struct PreviousList {
    1063              :     QString gpgIdFile;      ///< The list Init() wrote, which now applies.
    1064              :     QStringList recipients; ///< The lines that applied there before.
    1065              :   };
    1066              :   /// Set by Init() for the run it starts and cleared by finishReencrypt().
    1067              :   /// Written only on the owning thread while no worker runs.
    1068              :   std::optional<PreviousList> m_previousList;
    1069              :   /**
    1070              :    * @brief The checks Init() runs before it writes anything: no
    1071              :    * re-encryption running, the signing key's secret key available, the
    1072              :    * list and its signature free or regular files, and the list unchanged
    1073              :    * since the users dialog read it. Each refusal is shown.
    1074              :    * @param gpgIdFile The `.gpg-id` Init() is to write.
    1075              :    * @param signer The store's signer.
    1076              :    * @return true when Init() must stop.
    1077              :    */
    1078              :   auto refuseInitBeforeWrite(const QString &gpgIdFile,
    1079              :                              const GpgIdSigner &signer) -> bool;
    1080              :   /**
    1081              :    * @brief The verified list the entries of @p path were encrypted to
    1082              :    * before Init() replaces it, as the PreviousList of the run it starts.
    1083              :    * @param path The folder, in the store's own spelling, with a trailing
    1084              :    *        separator.
    1085              :    * @param gpgIdFile The `.gpg-id` Init() writes there.
    1086              :    * @return That list, or nothing when there was none or it was empty or
    1087              :    *         unverified.
    1088              :    */
    1089              :   auto previousListOf(const QString &path, const QString &gpgIdFile)
    1090              :       -> std::optional<PreviousList>;
    1091              :   /**
    1092              :    * @brief Take @p previous as the PreviousList of the run Init() starts
    1093              :    * for @p gpgIdFile, unless a run is active or an earlier, unfinished run
    1094              :    * of the same list left one: that one still tells whom the changes
    1095              :    * removed.
    1096              :    * @param gpgIdFile The `.gpg-id` Init() wrote.
    1097              :    * @param previous The list it replaced, if verified.
    1098              :    */
    1099              :   void keepPreviousList(const QString &gpgIdFile,
    1100              :                         const std::optional<PreviousList> &previous);
    1101              :   /**
    1102              :    * @brief After Init() wrote the new list but could not commit it: report
    1103              :    * Git's failure and re-encrypt without Git all the same, so nobody just
    1104              :    * removed can still read the entries.
    1105              :    * @param path The folder, in the store's own spelling.
    1106              :    * @param gitExit Git's exit code.
    1107              :    * @param gitOut Git's standard output.
    1108              :    * @param gitErr Git's error output, shown as the reason when not empty.
    1109              :    * @param gpgIdFile The `.gpg-id` Init() wrote.
    1110              :    * @param previous The list it replaced, if verified.
    1111              :    */
    1112              :   void reencryptAfterFailedCommit(const QString &path, int gitExit,
    1113              :                                   const QString &gitOut, const QString &gitErr,
    1114              :                                   const QString &gpgIdFile,
    1115              :                                   const std::optional<PreviousList> &previous);
    1116              :   /// Entries or folders the current run re-encrypts whatever they are
    1117              :   /// encrypted to: what the user moved or copied there. Cleared by
    1118              :   /// finishReencrypt(); written only on the owning thread while no worker
    1119              :   /// runs.
    1120              :   QStringList m_reencryptTrusted;
    1121              :   /// What the user was shown for an entry: its bytes and its folder's keys.
    1122           14 :   struct Agreed {
    1123              :     QByteArray hash;       ///< SHA-256 of the entry's bytes.
    1124              :     QSet<QString> readers; ///< The primary keys its list encrypted to.
    1125              :   };
    1126              :   /// The entries the user agreed to in reencryptAlso(), with what they were
    1127              :   /// shown: the run takes only these, and each only while its bytes and its
    1128              :   /// folder's keys are unchanged. Same lifetime as m_reencryptTrusted.
    1129              :   QHash<QString, Agreed> m_reencryptAgreed;
    1130              :   /// What the last run named (unexpectedRecipients()), with what was shown;
    1131              :   /// reencryptAlso() takes the user's yes from here.
    1132              :   QHash<QString, Agreed> m_lastUnexpected;
    1133              :   /// Entries left alone that a recipient taken off their folder's list
    1134              :   /// still reads, by whom: the automatic push for their folder waits until
    1135              :   /// a run re-encrypts them, finds nobody removed reading them, or they are
    1136              :   /// gone. Kept across runs; written only on the owning thread while no
    1137              :   /// worker runs.
    1138              :   QHash<QString, QSet<QString>> m_removedReaders;
    1139              :   /**
    1140              :    * @brief gitConfigured(), unless the current run is one
    1141              :    * reencryptWithoutGit() started.
    1142              :    * @return Whether the re-encryption run may call Git.
    1143              :    */
    1144              :   auto reencryptUsesGit() const -> bool;
    1145              :   /**
    1146              :    * @brief Re-encrypt @p dir to the `.gpg-id` Init() wrote although its
    1147              :    * commit failed, without any Git step (they would fail the same way), and
    1148              :    * tell the user afterwards that the change is not committed.
    1149              :    * @param dir The folder whose recipients changed.
    1150              :    * @param gitError What Git said when the commit failed.
    1151              :    */
    1152              :   void reencryptWithoutGit(const QString &dir, const QString &gitError);
    1153              :   /**
    1154              :    * @brief Tell the user that the recipients of @p dir changed on disk but
    1155              :    * the change is not committed, and whether the entries were re-encrypted.
    1156              :    * @param dir The folder whose recipients changed.
    1157              :    * @param gitError What Git said when the commit failed.
    1158              :    * @param reencrypted Whether every entry was re-encrypted to the new
    1159              :    *        recipients; false means some or all are still encrypted to the
    1160              :    *        previous ones.
    1161              :    */
    1162              :   void reportUncommittedGpgId(const QString &dir, const QString &gitError,
    1163              :                               bool reencrypted);
    1164              : 
    1165              :   /**
    1166              :    * @brief Translate @p path for the given @p exe when WSL-routed: wraps in
    1167              :    * wslpath substitution, otherwise returns @p path unchanged.
    1168              :    * @param path Native filesystem path.
    1169              :    * @param exe Executable path (checked for "wsl " prefix).
    1170              :    * @return Path suitable for the given executable.
    1171              :    */
    1172              :   auto translatePathForWsl(const QString &path, const QString &exe) const
    1173              :       -> QString;
    1174              :   /**
    1175              :    * @brief Translate @p path for git when WSL-routed: wraps in wslpath
    1176              :    * substitution, otherwise returns @p path unchanged.
    1177              :    * @param path Native filesystem path.
    1178              :    * @return Path suitable for the configured git executable.
    1179              :    */
    1180              :   auto pgit(const QString &path) const -> QString;
    1181              :   /**
    1182              :    * @brief Translate @p path for gpg when WSL-routed: wraps in wslpath
    1183              :    * substitution, otherwise returns @p path unchanged.
    1184              :    * @param path Native filesystem path.
    1185              :    * @return Path suitable for the configured gpg executable.
    1186              :    */
    1187              :   auto pgpg(const QString &path) const -> QString;
    1188              : };
    1189              : 
    1190              : #endif // SRC_IMITATEPASS_H_
        

Generated by: LCOV version 2.0-1