Branch data 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 Pass, the abstract password-store backend that RealPass and
6 : : * ImitatePass implement, and gpgErrorMessage(), which turns gpg's stderr into
7 : : * a message for the user.
8 : : */
9 : : #ifndef SRC_PASS_H_
10 : : #define SRC_PASS_H_
11 : :
12 : : #include "appsettings.h"
13 : : #include "enums.h"
14 : : #include "executor.h"
15 : : #include "gpgidgeneration.h"
16 : : #include "userinfo.h"
17 : :
18 : : #include <QProcess>
19 : : #include <QProcessEnvironment>
20 : : #include <QQueue>
21 : : #include <QSet>
22 : : #include <QString>
23 : : #include <QStringList>
24 : :
25 : : class GpgIdSigner;
26 : : #include <QHash>
27 : : #include <cassert>
28 : : #include <map>
29 : : #include <optional>
30 : :
31 : : /**
32 : : * @struct ResolvedGpgconfCommand
33 : : * @ingroup backend
34 : : * @brief Represents a command invocation for gpgconf operations.
35 : : *
36 : : * On Unix this is typically just the gpgconf binary; on Windows/WSL it may be
37 : : * a wrapper such as wsl.exe with gpgconf as a prefixed argument.
38 : : */
39 : 2 : struct ResolvedGpgconfCommand {
40 : : /**
41 : : * @brief Executable to run — may be a bare name resolved via PATH or a
42 : : * wrapper (e.g. wsl.exe) rather than a direct gpgconf path.
43 : : */
44 : : QString program;
45 : : /**
46 : : * @brief Full argv list, including any wrapper/prefix args followed by the
47 : : * actual gpgconf operation flags (e.g. ["--kill", "gpg-agent"]).
48 : : */
49 : : QStringList arguments;
50 : : };
51 : :
52 : : /**
53 : : * @class Pass
54 : : * @ingroup backend
55 : : * @brief Abstract base class for password store operations.
56 : : *
57 : : * Pass provides an abstraction layer for password management, supporting both
58 : : * the native 'pass' utility and gopass/imitation backends. It handles:
59 : : * - Password file operations (show, insert, remove, move, copy)
60 : : * - GPG key management and Git integration
61 : : * - OTP generation
62 : : * - Random password generation
63 : : *
64 : : * Subclasses must implement Git and password operations.
65 : : *
66 : : * Paths: the operations take a path relative to the store, or an absolute
67 : : * path spelled from the store as configured (`passStore`), as the store
68 : : * tree and the dialogs build them. The link checks, `pass` names and Git
69 : : * paths are worked out against that spelling. A path spelled through the
70 : : * target of a store root that is itself a link is not under the store as
71 : : * named. Init() places such a folder from its canonical path; the other
72 : : * operations would check only the entry itself for a link and give `pass`
73 : : * and Git `../` names, so callers must not hand one over. Resolving every
74 : : * link instead is no way out: a removal would then reach a link's target,
75 : : * not the link.
76 : : */
77 : : class Pass : public QObject {
78 : 579 : Q_OBJECT
79 : :
80 : : /** @brief Unused; kept from the time Pass tracked the running wrapper. */
81 : : bool wrapperRunning{false};
82 : : /**
83 : : * @brief The environment the store's processes run in: the system
84 : : * environment plus what updateEnv() sets (PASSWORD_STORE_ variables,
85 : : * GNUPGHOME, PATH additions, WSLENV). Read through storeEnvironment().
86 : : */
87 : : QProcessEnvironment env;
88 : :
89 : : protected:
90 : : /**
91 : : * @brief The whole public keyring as keyLinesHeldTwice() reads it.
92 : : * @param listing Receives the colon listing.
93 : : * @return gpg's exit code; -1 when it did not start.
94 : : */
95 : : virtual auto fullKeyListing(QString *listing) -> int;
96 : : /**
97 : : * @brief Refuse, with critical(), a recipient list with a line that more
98 : : * than one key block holds (keyLinesHeldTwice()).
99 : : * @param lines The lines of the list.
100 : : * @return true when refused.
101 : : */
102 : : auto refuseKeyLinesHeldTwice(const QStringList &lines) -> bool;
103 : : /**
104 : : * @brief The enabled users' key IDs, as Init() writes them to `.gpg-id`.
105 : : * @param users The users the dialog handed over.
106 : : * @return Their lines.
107 : : */
108 : : static auto enabledKeyLines(const QList<UserInfo> &users) -> QStringList;
109 : : /**
110 : : * @brief gpg's stderr without its machine-readable `[GNUPG:]` lines (and
111 : : * without carriage returns), as a person reads it.
112 : : * @param err gpg's (or pass's) standard error.
113 : : * @return The remaining lines, joined with "\n".
114 : : */
115 : : static auto withoutStatusLines(const QString &err) -> QString;
116 : : /**
117 : : * @brief The environment QtPass runs the store's processes in.
118 : : *
119 : : * What updateEnv() made: the git ceiling and the PASSWORD_STORE_ variables
120 : : * QtPass's own environment does not carry. For blocking calls that start
121 : : * their own process.
122 : : * @return A copy of the environment.
123 : : */
124 : 1029 : [[nodiscard]] auto storeEnvironment() const -> QProcessEnvironment {
125 : 1029 : return withCurrentGitPin(env);
126 : : }
127 : :
128 : : /**
129 : : * @brief @p base with GIT_DIR and GIT_WORK_TREE as the store is now
130 : : * (Util::gitStoreVariables()), not as it was at updateEnv(): a `.git` that
131 : : * appeared or changed hands since then is judged when Git runs.
132 : : * @param base The environment to update.
133 : : * @return @p base, the two variables recomputed (left as they are when
134 : : * the store keeps to a parent repository or there is none).
135 : : */
136 : : [[nodiscard]] auto withCurrentGitPin(QProcessEnvironment base) const
137 : : -> QProcessEnvironment;
138 : :
139 : : /**
140 : : * @brief Application settings snapshot injected at init() time.
141 : : *
142 : : * Populated by init(AppSettings) and valid for the lifetime of this backend
143 : : * instance. Subclasses read it in place of calling QtPassSettings directly.
144 : : */
145 : : AppSettings m_settings;
146 : : /**
147 : : * @brief Internal command executor for queuing and running subprocesses.
148 : : */
149 : : Executor exec;
150 : :
151 : : /**
152 : : * @brief Alias for Enums::PROCESS used throughout this class.
153 : : */
154 : : using PROCESS = Enums::PROCESS;
155 : :
156 : : public:
157 : : /// What skippedGpgId() found on its way up from one folder.
158 : 252 : struct SkippedWalk {
159 : : /// The skipped `.gpg-id`, if any.
160 : : std::optional<QString> skipped;
161 : : /// The generation record's error, when that is why it was named.
162 : : QString recordError;
163 : : };
164 : : /// SkippedWalk per absolute folder, for one check of many folders.
165 : : using SkippedWalks = QHash<QString, SkippedWalk>;
166 : : /// What linkedGpgId() found on its way up, per absolute folder, for one
167 : : /// check of many folders.
168 : : using LinkedWalks = QHash<QString, std::optional<QString>>;
169 : :
170 : : /**
171 : : * @brief Construct a Pass instance.
172 : : */
173 : : Pass();
174 : : /**
175 : : * @brief Initialize the Pass instance with a settings snapshot.
176 : : * @param settings Application settings to use for this backend lifetime.
177 : : */
178 : : void init(const AppSettings &settings);
179 : : /**
180 : : * @brief Check if GPG supports Ed25519 encryption.
181 : : * @param gpgExecutable Path to the gpg binary (defaults to "gpg").
182 : : * @return true if Ed25519 is supported.
183 : : */
184 : : static bool gpgSupportsEd25519(const QString &gpgExecutable = {});
185 : : /**
186 : : * @brief Get default key template for new GPG keys.
187 : : * @param gpgExecutable Path to the gpg binary (defaults to "gpg").
188 : : * @return Default template string.
189 : : */
190 : : static QString getDefaultKeyTemplate(const QString &gpgExecutable = {});
191 : :
192 : 708 : ~Pass() override = default;
193 : :
194 : : // Git operations
195 : : /**
196 : : * @brief Initialize Git repository in password store.
197 : : */
198 : : virtual void GitInit() = 0;
199 : : /**
200 : : * @brief Pull changes from remote Git repository.
201 : : */
202 : : virtual void GitPull() = 0;
203 : : /**
204 : : * @brief Pull from the remote and wait for it, at most @p timeoutMs: the
205 : : * pull before an edit, on the GUI thread.
206 : : *
207 : : * A remote that never answers froze the window, autoclear timers
208 : : * included, until git gave up, which it may never do. Past the deadline
209 : : * git is stopped and the status bar says the pull did not finish.
210 : : * @param timeoutMs Most milliseconds to wait (kBlockingPullMs from the
211 : : * window).
212 : : */
213 : : virtual void GitPull_b(int timeoutMs) = 0;
214 : :
215 : : /** @brief How long the pull before an edit may block the window. */
216 : : static constexpr int kBlockingPullMs = 30000;
217 : : /**
218 : : * @brief Push changes to remote Git repository.
219 : : */
220 : : virtual void GitPush() = 0;
221 : :
222 : : // Password operations
223 : : /**
224 : : * @brief Show decrypted password file.
225 : : * @param file Path to password file relative to store root.
226 : : */
227 : : virtual void Show(QString file) = 0;
228 : : /**
229 : : * @brief Insert or update password.
230 : : * @param file Path to password file.
231 : : * @param value Password content to store.
232 : : * @param force Overwrite existing file.
233 : : */
234 : : virtual void Insert(QString file, QString value, bool force) = 0;
235 : : /**
236 : : * @brief How many inserts have started queueing but not yet reported.
237 : : *
238 : : * One Insert() still in the command queue, or running, counts here until its
239 : : * PASS_INSERT result goes out. A PasswordDialog reads this just before its
240 : : * own Insert() so it can tell an earlier insert's report (which it is also
241 : : * connected to, once a hanging queue let it open while its save was still
242 : : * pending) from its own.
243 : : * @return The number of inserts awaiting their report.
244 : : */
245 : 38 : [[nodiscard]] auto insertsPending() const -> int { return m_insertsPending; }
246 : : /**
247 : : * @brief What saving over an existing entry would change about who reads
248 : : * it (readersAnEditWouldAdd()).
249 : : */
250 : 6 : struct EditReaders {
251 : : /** @brief Who would read the entry after the save and the question is
252 : : * about, as "name (key ID)"; empty for no question. */
253 : : QStringList names;
254 : : /** @brief The entry's path was never saved from this device and its
255 : : * folder takes a parent's list, so its current readers cannot
256 : : * be told: names lists everyone it would be encrypted to. */
257 : : bool notSavedHere = false;
258 : : /**
259 : : * @brief Equal when both say the same.
260 : : * @param other The other answer.
261 : : * @return Whether names and notSavedHere match.
262 : : */
263 : 5 : auto operator==(const EditReaders &other) const -> bool {
264 [ + + - + ]: 5 : return names == other.names && notSavedHere == other.notSavedHere;
265 : : }
266 : : };
267 : : /**
268 : : * @brief Who saving over an existing entry would let read it who may not
269 : : * now.
270 : : *
271 : : * Asked by the edit dialog before Insert(), so a list that changed under
272 : : * the entry (a folder renamed past its own signed list, say) does not
273 : : * widen it unasked. Those who read it now come from the entry's recipient
274 : : * IDs, which whoever can push can write; so with a signing key, an entry
275 : : * at a path this device never saved (EntryRecord) whose folder takes a
276 : : * parent's list is asked about whatever its IDs say. None by default;
277 : : * the native backend tells.
278 : : * @param file The entry, relative to the store, without ".gpg".
279 : : * @return The answer; empty names when nothing needs asking or it cannot
280 : : * be told (new entry, unreadable list).
281 : : */
282 : 0 : virtual auto readersAnEditWouldAdd(const QString &file) -> EditReaders {
283 : : Q_UNUSED(file)
284 : 0 : return {};
285 : : }
286 : : /**
287 : : * @brief Entries a `pass init` of @p dir with @p users would hand to
288 : : * someone who cannot read them now (an entry copied in from a
289 : : * folder they are not on), less whom the change adds. pass
290 : : * re-encrypts every entry itself, so the caller asks before it
291 : : * runs. None by default; the pass backend tells.
292 : : * @param dir The folder, as Init() gets it.
293 : : * @param users The recipients Init() would write.
294 : : * @return The entries' absolute paths.
295 : : */
296 : 6 : virtual auto entriesInitWouldWiden(const QString &dir,
297 : : const QList<UserInfo> &users)
298 : : -> QStringList {
299 : : Q_UNUSED(dir)
300 : : Q_UNUSED(users)
301 : 6 : return {};
302 : : }
303 : : /**
304 : : * @brief Entries already in the place a `pass mv` or `pass cp` of @p src
305 : : * to @p dest re-encrypts (the whole destination folder) that would
306 : : * gain a reader they do not have. What is moved or copied itself is
307 : : * the user's own and not counted. None by default.
308 : : * @param src The entry or folder moved or copied.
309 : : * @param dest Where it goes.
310 : : * @return The entries' absolute paths.
311 : : */
312 : 6 : virtual auto entriesMoveWouldWiden(const QString &src, const QString &dest)
313 : : -> QStringList {
314 : : Q_UNUSED(src)
315 : : Q_UNUSED(dest)
316 : 6 : return {};
317 : : }
318 : : /**
319 : : * @brief The long key IDs an entry is encrypted to, as gpg lists them
320 : : * without anyone's secret key (ENC_TO).
321 : : * @param path The entry.
322 : : * @return The IDs in upper case; empty when gpg could not tell.
323 : : */
324 : : auto entryReaders(const QString &path) -> QStringList;
325 : : /**
326 : : * @brief The entry whose insert is reporting now: set while
327 : : * finishedInsert() or insertFailed() goes out, empty otherwise.
328 : : *
329 : : * Inserts report in the order they were queued, so each report is matched
330 : : * to the entry its Insert() named. A window refreshing after a save shows
331 : : * only that entry again, not whatever row is selected by then.
332 : : * @return Absolute path of the entry file (with `.gpg`), as the backend
333 : : * wrote it; empty outside a report, or for a report no queued
334 : : * insert accounts for.
335 : : */
336 : : [[nodiscard]] auto reportedInsert() const -> QString {
337 : : return m_reportedInsert;
338 : : }
339 : : /**
340 : : * @brief Remove password file or directory.
341 : : * @param file Path to remove.
342 : : * @param isDir true if removing a directory.
343 : : */
344 : : virtual void Remove(QString file, bool isDir) = 0;
345 : : /**
346 : : * @brief Move password file or directory.
347 : : * @param srcDir Source path.
348 : : * @param dest Destination path.
349 : : * @param force Overwrite existing.
350 : : */
351 : : virtual void Move(const QString srcDir, const QString dest,
352 : : const bool force) = 0;
353 : : /**
354 : : * @brief Copy password file or directory.
355 : : * @param srcDir Source path.
356 : : * @param dest Destination path.
357 : : * @param force Overwrite existing.
358 : : */
359 : : virtual void Copy(const QString srcDir, const QString dest,
360 : : const bool force) = 0;
361 : : /**
362 : : * @brief Initialize new password store.
363 : : * @param path Root of password store.
364 : : * @param users List of recipient GPG keys.
365 : : */
366 : : virtual void Init(QString path, const QList<UserInfo> &users) = 0;
367 : : /**
368 : : * @brief Search password content for a pattern.
369 : : *
370 : : * Both backends decrypt each entry with gpg and match it in-process
371 : : * (NativeGrep), never through `pass grep`, so the pattern is one dialect
372 : : * for both: QRegularExpression, Perl-compatible (PCRE).
373 : : *
374 : : * @param pattern Search pattern, a Perl-compatible regular expression.
375 : : * @param caseInsensitive true for case-insensitive search.
376 : : */
377 : : virtual void Grep(QString pattern, bool caseInsensitive) = 0;
378 : :
379 : : /**
380 : : * @brief Stop a running Grep(): the walk ends at the next entry and the gpg
381 : : * decrypting one is terminated. Its (partial) result still arrives through
382 : : * finishedGrep(). Does nothing when no search runs.
383 : : */
384 : 0 : virtual void CancelGrep() {}
385 : :
386 : : /**
387 : : * @brief Generate random password.
388 : : * @param length Password length.
389 : : * @param charset Character set to use.
390 : : * @return Generated password.
391 : : */
392 : : virtual auto generatePassword(unsigned int length, const QString &charset)
393 : : -> QString;
394 : :
395 : : // GPG operations
396 : : /**
397 : : * @brief Generate GPG keys using batch script.
398 : : * @param batch GPG batch script content.
399 : : */
400 : : void GenerateGPGKeys(QString batch);
401 : : /**
402 : : * @brief List GPG keys matching patterns.
403 : : * @param keystrings List of search patterns.
404 : : * @param secret Include secret keys.
405 : : * @return List of matching keys.
406 : : */
407 : : auto listKeys(QStringList keystrings, bool secret = false) -> QList<UserInfo>;
408 : : /**
409 : : * @brief The keys a gpg encryption to @p recipients reaches: a throwaway
410 : : * encryption outside the store, read back for whom it went to.
411 : : *
412 : : * What `-r` makes of each line, where listKeys() searches: a key that
413 : : * only resembles a recipient (a user ID that contains its address, a
414 : : * subkey bound to its key) is not reached. No key lookups over the
415 : : * network (`--no-auto-key-locate`), so opening a dialog fetches nothing.
416 : : * @param recipients The lines of a recipient list.
417 : : * @return The long key IDs (upper case) of the keys and subkeys encrypted
418 : : * to, possibly empty when gpg did not say; nothing when gpg could
419 : : * not encrypt to the list.
420 : : */
421 : : virtual auto encryptionReaches(const QStringList &recipients)
422 : : -> std::optional<QStringList>;
423 : : /**
424 : : * @brief The `-r` argument for one recipient line, as this backend's
425 : : * encryption hands it to gpg: the probe (encryptionReaches()) must
426 : : * reach what the encryption will. The native backend matches a
427 : : * bare address exactly (exactRecipientArg()).
428 : : * @param line One recipient line.
429 : : * @return The argument.
430 : : */
431 : : [[nodiscard]] virtual auto recipientArgument(const QString &line) const
432 : : -> QString;
433 : : /**
434 : : * @brief A bare mail address in gpg's exact form, `<address>`; any other
435 : : * line as written.
436 : : *
437 : : * gpg reads a bare address as a case-insensitive substring of the user
438 : : * ID: `bob@example.com` also matches `notbob@example.com`, and once Bob's
439 : : * key is unusable gpg takes that one without a word. In angle brackets
440 : : * only that address matches. Lines with their own gpg prefix (`=`, `<`,
441 : : * `@`, `*`, `+`, `#`, `&`), spaces, or no `@` are left alone.
442 : : * @param line One recipient line.
443 : : * @return The argument.
444 : : */
445 : : static auto exactRecipientArg(const QString &line) -> QString;
446 : : /**
447 : : * @brief The key ID and fingerprint lines of a recipient list that more
448 : : * than one key block holds, with those blocks.
449 : : *
450 : : * gpg resolves `-r <fingerprint>` among primary keys and subkeys, and
451 : : * anyone can bind another person's public key to their own as a subkey:
452 : : * after importing such a key, a line meant for one person may encrypt to
453 : : * the other. Such a line is refused, not guessed at.
454 : : * @param lines The lines of a recipient list.
455 : : * @return Each such line, mapped to its holders as "name (key ID)";
456 : : * nothing when the keyring could not be listed, so a failed
457 : : * listing is not taken for a clean one.
458 : : */
459 : : auto keyLinesHeldTwice(const QStringList &lines)
460 : : -> std::optional<QHash<QString, QStringList>>;
461 : : /**
462 : : * @brief `gpg --armor --export` of @p keys, in the store's environment:
463 : : * the keyring keyLinesHeldTwice() reads.
464 : : * @param gpg The gpg executable.
465 : : * @param keys The key IDs or fingerprints.
466 : : * @param out Receives the armoured keys.
467 : : * @param err Receives gpg's messages.
468 : : * @return gpg's exit code.
469 : : */
470 : : auto exportPublicKeys(const QString &gpg, const QStringList &keys,
471 : : QString *out, QString *err) -> int;
472 : : /**
473 : : * @brief keyLinesHeldTwice() on a listing already made.
474 : : * @param lines The lines of a recipient list.
475 : : * @param listing Output of `gpg --with-colons --with-fingerprint
476 : : * --with-subkey-fingerprint --list-keys`.
477 : : * @return As keyLinesHeldTwice().
478 : : */
479 : : static auto keyLinesHeldTwiceIn(const QStringList &lines,
480 : : const QString &listing)
481 : : -> QHash<QString, QStringList>;
482 : : /**
483 : : * @brief A message naming each line keyLinesHeldTwice() found and what
484 : : * the user can do about it.
485 : : * @param held As keyLinesHeldTwice() returned it: not empty, or nothing
486 : : * for a keyring that could not be listed.
487 : : * @return The message.
488 : : */
489 : : static auto describeKeyLinesHeldTwice(
490 : : const std::optional<QHash<QString, QStringList>> &held) -> QString;
491 : : /**
492 : : * @brief List GPG keys.
493 : : * @param keystring Search pattern.
494 : : * @param secret Include secret keys.
495 : : * @return List of matching keys.
496 : : */
497 : 146 : auto listKeys(const QString &keystring = "", bool secret = false)
498 : : -> QList<UserInfo>;
499 : : /**
500 : : * @brief Update environment for subprocesses.
501 : : */
502 : : void updateEnv();
503 : :
504 : : /**
505 : : * @brief Most bytes of plaintext a gpg decryption may produce.
506 : : *
507 : : * An OpenPGP message is compressed, so a small entry in a shared store can
508 : : * decompress to gigabytes; gpg stops at this many (--max-output) instead of
509 : : * filling QtPass's memory. Far above any real entry.
510 : : */
511 : : static constexpr qint64 kMaxPlaintextBytes = 64LL * 1024 * 1024;
512 : :
513 : : /**
514 : : * @brief The status-bar text for a blocking pull stopped at its deadline.
515 : : * @param timeoutMs The deadline that passed.
516 : : * @return The message.
517 : : */
518 : : [[nodiscard]] static auto pullTimedOut(int timeoutMs) -> QString;
519 : :
520 : : /**
521 : : * @brief The gpg options that enforce kMaxPlaintextBytes.
522 : : * @return "--max-output" and the limit, for a gpg decryption's arguments.
523 : : */
524 : : static auto maxOutputArgs() -> QStringList;
525 : :
526 : : // Static helpers
527 : : /**
528 : : * @brief Resolve the gpgconf command to kill agents.
529 : : * @param gpgPath Path to gpg executable.
530 : : * @return Resolved command with program and arguments.
531 : : */
532 : : static auto resolveGpgconfCommand(const QString &gpgPath)
533 : : -> ResolvedGpgconfCommand;
534 : : /**
535 : : * @brief Get .gpg-id file path for a password file.
536 : : * @param for_file Path to password file.
537 : : * @param passStore Root directory of the password store.
538 : : * @return Path to .gpg-id file.
539 : : */
540 : : static auto getGpgIdPath(const QString &for_file, const QString &passStore)
541 : : -> QString;
542 : : /**
543 : : * @brief The folder list getGpgIdPath() passed over on its way up to the
544 : : * one it returns, if it passed one over that a signed store must not.
545 : : *
546 : : * getGpgIdPath() skips a `.gpg-id` that is missing, a link or a junction
547 : : * and falls back to a parent folder's list, as `pass` does. In a signed
548 : : * store that lets anyone who can write to it, without the signing key,
549 : : * move a folder's entries to the parent's (also validly signed)
550 : : * recipients by removing or linking the folder's own list. This names the
551 : : * first such list between the start and the folder of the list found
552 : : * (that folder and the store root excluded): one that is under the name
553 : : * but not a regular file, or one that is gone although this device has
554 : : * accepted a list at that path before (GpgIdGeneration::remembered()).
555 : : * When the generation record cannot be read, whether a list was accepted
556 : : * at a path cannot be told: the first folder without its own list is
557 : : * named then too (fail closed), and @p recordError says why.
558 : : * @param forFile Entry or folder, as for getGpgIdPath().
559 : : * @param passStore Root directory of the password store.
560 : : * @param recordError Receives the record's error when it could not be
561 : : * read, if not null; left untouched otherwise.
562 : : * @param walks What earlier calls found per folder, for one check of many
563 : : * folders (RealPass::refuseUnverifiedTree()); read and extended, so
564 : : * each folder is looked up once. Null for none.
565 : : * @return The skipped `.gpg-id` path, or nothing when the list found is
566 : : * the one that applies.
567 : : */
568 : : static auto skippedGpgId(const QString &forFile, const QString &passStore,
569 : : QString *recordError = nullptr,
570 : : SkippedWalks *walks = nullptr)
571 : : -> std::optional<QString>;
572 : : /**
573 : : * @brief The link or junction under the name `.gpg-id` that getGpgIdPath()
574 : : * skips on its way up from @p forFile, if it skips one before the list it
575 : : * returns.
576 : : *
577 : : * `pass` follows such a link and encrypts to the recipients of the file it
578 : : * points to, while QtPass shows and checks the list of a folder above it.
579 : : * Unlike skippedGpgId(), this asks no generation record and includes the
580 : : * store root, so it applies with or without a signing key.
581 : : * @param forFile Entry or folder, as for getGpgIdPath().
582 : : * @param passStore Root directory of the password store.
583 : : * @param walks What earlier calls found per folder, for one check of many
584 : : * folders (RealPass::refuseUnverifiedTree()); read and extended, so
585 : : * each folder is looked at once. Null for none.
586 : : * @return The linked `.gpg-id` path, or nothing when the walk meets none.
587 : : */
588 : : static auto linkedGpgId(const QString &forFile, const QString &passStore,
589 : : LinkedWalks *walks = nullptr)
590 : : -> std::optional<QString>;
591 : : /**
592 : : * @brief Get list of recipients for a password file.
593 : : * @param for_file Path to password file.
594 : : * @param passStore Root directory of the password store.
595 : : * @return List of recipient key IDs.
596 : : */
597 : : static auto getRecipientList(const QString &for_file,
598 : : const QString &passStore) -> QStringList;
599 : :
600 : : /**
601 : : * @brief What a dialog may do with the list of a folder
602 : : * (recipientsForEditing()).
603 : : */
604 : 168 : struct RecipientsForEditing {
605 : : /** @brief How the list on disk stood up. */
606 : : enum class State {
607 : : /** @brief No signing key: the list as it is. */
608 : : Unsigned,
609 : : /** @brief Signature and generation and folder all accepted. */
610 : : Verified,
611 : : /**
612 : : * @brief Signed, authentic and bound to this folder, but older than a
613 : : * generation this device has accepted: preselected for the recovery,
614 : : * flagged for review.
615 : : */
616 : : VerifiedRollback,
617 : : /**
618 : : * @brief Not to be used: signature invalid, written for another folder
619 : : * or for no folder in particular while a generation was accepted here,
620 : : * malformed header, or no freshness record to judge by.
621 : : */
622 : : Rejected,
623 : : };
624 : : /** @brief How the list on disk stood up. */
625 : : State state = State::Unsigned;
626 : : /** @brief The recipients to preselect; empty when Rejected. */
627 : : QStringList recipients;
628 : : /** @brief What the dialog should show, if anything. */
629 : : QString warning;
630 : : };
631 : :
632 : : /**
633 : : * @brief The recipients a dialog may preselect for editing the list of
634 : : * @p dir.
635 : : *
636 : : * With a signing key configured, only a list whose signature, generation
637 : : * and folder binding are all accepted: the Users dialog preselects what it
638 : : * loads and OK writes and signs the selection, so a list read
639 : : * unauthenticated would turn an attacker's unsigned edit into a genuinely
640 : : * signed one with one click. The one exception is an authentic list the
641 : : * generation record calls older (the recovery from a rollback goes through
642 : : * this dialog): preselected, with the reason shown for review. Anything
643 : : * else that fails preselects nothing and says why. Without a signing key,
644 : : * the list as it is.
645 : : * @param dir Folder whose list is edited; empty for the store root.
646 : : * @param passStore The store the folder belongs to: the dialog's, which
647 : : * for a profile being set up is not this backend's.
648 : : * @return The state, the recipients to preselect and the warning to show.
649 : : */
650 : : auto recipientsForEditing(const QString &dir, const QString &passStore)
651 : : -> RecipientsForEditing;
652 : : /**
653 : : * @brief Init(), but only while the list of @p dir still reads as the
654 : : * caller read it with recipientsForEditing().
655 : : *
656 : : * The users dialog ticks its selection from the list it read, and writes
657 : : * the whole selection: a newer list that arrived meanwhile (a pull in a
658 : : * terminal, a sync) would be replaced by the old one plus the change. The
659 : : * backend reads the list again at the last point before it writes (or
660 : : * starts `pass init`) and refuses with refuseChangedList() when it differs.
661 : : * @param path Folder to initialize, as for Init().
662 : : * @param users Recipients, as for Init().
663 : : * @param dir The folder the list was read for, as given to
664 : : * recipientsForEditing().
665 : : * @param passStore The store root given to recipientsForEditing().
666 : : * @param read What recipientsForEditing() returned then; its warning is
667 : : * not compared.
668 : : * @return false when refuseChangedList() or refuseBusyForExpectedList()
669 : : * refused, so the caller can keep its selection; true otherwise,
670 : : * also when Init() refused for another reason it reported itself.
671 : : */
672 : : auto initIfUnchanged(const QString &path, const QList<UserInfo> &users,
673 : : const QString &dir, const QString &passStore,
674 : : const RecipientsForEditing &read) -> bool;
675 : : /**
676 : : * @brief Parse the contents of a .gpg-id: one recipient per line, `#`
677 : : * starts a comment, unusable lines are logged and skipped.
678 : : * @param contents The file's bytes.
679 : : * @param sourceName Where they came from, for the log.
680 : : * @return The recipient key IDs in file order.
681 : : */
682 : : static auto parseRecipients(const QByteArray &contents,
683 : : const QString &sourceName) -> QStringList;
684 : : /**
685 : : * @brief Why pass would read a `.gpg-id` differently from
686 : : * parseRecipients(), if it would.
687 : : *
688 : : * pass reads the list with `while read -r`, which keeps NUL-free bytes as
689 : : * they are, strips only blanks and tabs, and drops a last line without a
690 : : * line feed; parseRecipients() decodes UTF-8 (losing a byte-order mark and
691 : : * invalid bytes), trims every kind of whitespace and skips a line that
692 : : * starts with a dash. Where the two differ, the Users dialog shows other
693 : : * recipients than pass encrypts to.
694 : : * @param contents The file's bytes.
695 : : * @return The first difference, as a phrase for a message; empty when
696 : : * both read the same recipients.
697 : : */
698 : : static auto passReadsDifferently(const QByteArray &contents) -> QString;
699 : : /**
700 : : * @brief The arguments as they may appear in the debug log: the value of
701 : : * `--passphrase` and friends, and otpauth URIs, are replaced.
702 : : * @param args The argv about to be run.
703 : : * @return The same list with secret-shaped values redacted.
704 : : */
705 : : static auto loggableArgs(const QStringList &args) -> QStringList;
706 : :
707 : : /**
708 : : * @brief Whether no gpg, git or pass of this backend runs or waits.
709 : : * @return true when its executor is idle.
710 : : */
711 : : [[nodiscard]] auto isIdle() const -> bool { return exec.isIdle(); }
712 : : /**
713 : : * @brief Stop the queued command that is running now
714 : : * (Executor::stopRunning()); it then ends as a failed run.
715 : : * @return Whether one was running.
716 : : */
717 : 4 : auto stopRunning() -> bool { return exec.stopRunning(); }
718 : : /**
719 : : * @brief Which run is going (Executor::runningSerial()).
720 : : * @return A number no other run had, or 0 when nothing runs.
721 : : */
722 : : [[nodiscard]] auto runningSerial() const -> quint64 {
723 : : return exec.runningSerial();
724 : : }
725 : : /**
726 : : * @brief What kind of command is running now.
727 : : * @return Its Enums::PROCESS, or Enums::INVALID when nothing runs.
728 : : */
729 : : [[nodiscard]] auto runningProcess() const -> Enums::PROCESS {
730 : : const int id = exec.runningId();
731 : 14 : return id >= 0 && id < Enums::PROCESS_COUNT
732 [ - + - + : 14 : ? static_cast<Enums::PROCESS>(id)
- + ]
733 : : : Enums::INVALID;
734 : : }
735 : :
736 : : /**
737 : : * @brief Whether a Git push of this backend is queued or running.
738 : : * @return true while one waits or runs.
739 : : */
740 : : [[nodiscard]] auto isPushing() const -> bool {
741 : : return exec.hasQueued(Enums::GIT_PUSH);
742 : : }
743 : :
744 : : /**
745 : : * @brief Whether automatic pushes of the current store are held because
746 : : * its last re-encryption did not finish cleanly.
747 : : *
748 : : * The recipients change is committed locally first, so after a failed or
749 : : * cancelled re-encryption the next automatic push (after any later edit)
750 : : * would publish a .gpg-id whose entries are partly still encrypted to the
751 : : * previous recipients. Held while any folder of the store has such a run
752 : : * outstanding, until a clean re-encryption covers it; a push the user asks
753 : : * for is not held. Shared by both backends, so switching between them
754 : : * keeps it; kept for this session only.
755 : : * @return true when an automatic push of the current store should not run.
756 : : */
757 : : [[nodiscard]] auto autoPushHeld() const -> bool;
758 : :
759 : : /**
760 : : * @brief GitPush() for an automatic push, the one after a change. A
761 : : * backend that has to make the push later drops it then if the
762 : : * store is held by that time (autoPushHeld()); a push by hand
763 : : * (GitPush()) still goes.
764 : : */
765 : : void GitPushAutomatic();
766 : :
767 : : protected:
768 : : /**
769 : : * @brief Whether the GitPush() running now is an automatic one.
770 : : * @return true inside GitPushAutomatic().
771 : : */
772 : : [[nodiscard]] auto pushIsAutomatic() const -> bool;
773 : :
774 : : /**
775 : : * @brief Hold automatic pushes of the store that holds @p scope
776 : : * (autoPushHeld()): its re-encryption did not finish cleanly.
777 : : * @param scope The folder (or entry) the run re-encrypted, absolute or
778 : : * relative to the current store.
779 : : */
780 : : void holdAutoPush(const QString &scope);
781 : :
782 : : /**
783 : : * @brief Release the holds a clean re-encryption of @p folder covers:
784 : : * those for @p folder itself and everything under it. Holds for
785 : : * other folders stay.
786 : : * @param folder The folder the clean run re-encrypted, absolute or
787 : : * relative to the current store.
788 : : */
789 : : void releaseAutoPush(const QString &folder);
790 : :
791 : : /**
792 : : * @brief With signing on, refuse to encrypt @p file when the lookup passed
793 : : * over its folder's own list (skippedGpgId()): the parent's list is not
794 : : * what was signed for it.
795 : : * @param file The entry or folder about to be encrypted to.
796 : : * @param signing Whether a signing key is set (signed lists in use).
797 : : * @param except A list about to be written (by `pass init`), which may
798 : : * be missing now without that being refused.
799 : : * @param walks Passed on to skippedGpgId(); null for none.
800 : : * @return Whether it was refused (and the user told).
801 : : */
802 : : auto refuseSkippedGpgId(const QString &file, bool signing,
803 : : const QString &except = QString(),
804 : : SkippedWalks *walks = nullptr) -> bool;
805 : :
806 : : /**
807 : : * @brief Whether @p gpgIdFile is a signed list QtPass accepts: its
808 : : * signature verifies (GpgIdSigner::verifyFile()), and it is current and
809 : : * bound to the folder it lies in (GpgIdGeneration::accept()), so an older
810 : : * authentic list put back, or one signed for another folder, is refused.
811 : : * @param signer The verifier, with the configured signing keys.
812 : : * @param gpgIdFile The `.gpg-id`.
813 : : * @param contents Receives the verified bytes.
814 : : * @param why Receives why a current-and-bound check refused the list;
815 : : * left as it is when the signature itself does not verify.
816 : : * @return Whether the list may be encrypted to.
817 : : */
818 : : auto verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile,
819 : : QByteArray *contents, QString *why) const -> bool;
820 : :
821 : : /**
822 : : * @brief Whether the insert that just failed had put its entry in the
823 : : * store before a later step failed. The backend that writes the entry
824 : : * knows; this default says no.
825 : : * @param err What the failed insert reported on stderr.
826 : : * @return true when the failed insert's entry was written.
827 : : */
828 : 0 : [[nodiscard]] virtual auto insertWritten(const QString &err) const -> bool {
829 : : Q_UNUSED(err);
830 : 0 : return false;
831 : : }
832 : :
833 : : /**
834 : : * @brief Remember what a Show() asked for, so its completion can say so.
835 : : *
836 : : * Backends call this first thing in Show(); Pass::finished() pops the
837 : : * entry again on success or failure. The Executor runs one queue in
838 : : * order, so the two stay aligned.
839 : : * @param file The Show() argument.
840 : : */
841 : : void queueShow(const QString &file) { m_pendingShows.enqueue(file); }
842 : : /**
843 : : * @brief Count one insert that has started queueing but not yet reported.
844 : : *
845 : : * Backends call this where Insert() queues its work, past every refusal;
846 : : * Pass::finished() counts it off again when the insert reports. Each queued
847 : : * insert reports once, as a PASS_INSERT, so the count tracks the inserts in
848 : : * flight. A dialog reads insertsPending() before its own Insert() to learn
849 : : * how many earlier reports are not its own.
850 : : * @param entry Absolute path of the entry file the insert writes, handed
851 : : * out by reportedInsert() while its report goes out.
852 : : */
853 : : void queueInsert(const QString &entry = QString()) {
854 : 127 : ++m_insertsPending;
855 : : m_insertedEntries.enqueue(entry);
856 : 127 : }
857 : : /** @brief What refuseLinkedPath() judges. */
858 : : enum class LinkScope {
859 : : /** @brief The entry itself and every folder above it in the store. */
860 : : EntryAndParents,
861 : : /**
862 : : * @brief Only the folders above it: a removal unlinks a link and
863 : : * touches nothing behind it.
864 : : */
865 : : ParentsOnly,
866 : : };
867 : : /** @brief How a path handed to refuseLinkedPath() is spelled. */
868 : : enum class PathSpelling {
869 : : /**
870 : : * @brief As the store is configured or relative to it, the class's path
871 : : * rule. A path spelled through the target of a linked store root is
872 : : * then logged as a warning, so tests catch a caller that hands one over.
873 : : */
874 : : Configured,
875 : : /**
876 : : * @brief Through the target of a linked store root, by a caller that
877 : : * places such a folder itself (Init()): not logged.
878 : : */
879 : : PlacedByCaller,
880 : : };
881 : : /**
882 : : * @brief Refuse an operation on something that is, or lies behind, a
883 : : * symbolic link or NTFS junction inside the store.
884 : : *
885 : : * The store tree shows a linked entry or folder like any other, and gpg,
886 : : * pass and QFile all follow links, so without this a planted link would
887 : : * have an entry shown, edited, copied or written outside the store, with
888 : : * the store's recipients. The configured store root itself may be a link
889 : : * (a synced folder); that is not judged.
890 : : * @param path Store-relative (as Show/Insert/Remove get it, `.gpg`
891 : : * included where it applies) or absolute (as Move/Copy get it).
892 : : * @param scope Whether the entry itself counts, or only the folders it
893 : : * lies in (a removal).
894 : : * @param spelling Whether @p path follows the class's path rule, or the
895 : : * caller places a target-spelled path itself (Init()).
896 : : * @return true when critical() and processErrorExit() were emitted and
897 : : * the caller must stop.
898 : : */
899 : : auto refuseLinkedPath(const QString &path,
900 : : LinkScope scope = LinkScope::EntryAndParents,
901 : : PathSpelling spelling = PathSpelling::Configured)
902 : : -> bool;
903 : : /**
904 : : * @brief Refuse recipients for a folder outside the store, as pass
905 : : * refuses a path with `..` in it.
906 : : *
907 : : * ImitatePass would write a `.gpg-id` that the store never reads, and
908 : : * `pass init --path` would take the folder's absolute path as a folder
909 : : * under the store. Links on the way are resolved, as for the store root.
910 : : * @param folder The folder, absolute.
911 : : * @param relative Where the folder lies in the store, as
912 : : * PathValidator::storeRelativePath() gives it (empty for the root),
913 : : * when it is not refused; may be null.
914 : : * @return true when critical() and processErrorExit() were emitted and
915 : : * the caller must stop.
916 : : */
917 : : auto refuseFolderOutsideStore(const QString &folder,
918 : : QString *relative = nullptr) -> bool;
919 : :
920 : : /**
921 : : * @brief Run a git command in the store's repository, blocking.
922 : : *
923 : : * The two backends reach git differently: ImitatePass runs the configured
924 : : * git with `-C <store>`, RealPass runs `pass git`. The default (no git)
925 : : * answers false. Used by refuseUnfinishedGitOperation() to ask the
926 : : * repository its state before an operation changes the store.
927 : : * @param args The git arguments (without the executable or `-C`).
928 : : * @param out Receives the command's standard output; may be null.
929 : : * @return true when git ran and exited 0, false otherwise (git off, the
930 : : * store is not a repository, or git failed).
931 : : */
932 : 0 : virtual auto storeGit(const QStringList &args, QString *out) -> bool {
933 : : Q_UNUSED(args);
934 : : Q_UNUSED(out);
935 : 0 : return false;
936 : : }
937 : :
938 : : /**
939 : : * @brief Refuse to change the store while git is mid-rebase, -merge,
940 : : * -cherry-pick or -revert.
941 : : *
942 : : * A pull that stopped in a conflict leaves the repository part-way through
943 : : * an operation. Committing a save or a re-encryption into it lands the
944 : : * change on a detached HEAD (a later `git rebase --abort` drops it) or
945 : : * concludes the merge in favour of the local copy (pushing over a
946 : : * colleague's change). Every store-changing operation calls this at its
947 : : * entry, next to refuseLinkedPath(), so the change is refused before gpg or
948 : : * pass runs and the dialog keeps what was typed. Nothing is refused when git
949 : : * is off, the store is not a repository, or git gives no answer. A HEAD
950 : : * detached by hand (no operation in progress) is deliberately accepted.
951 : : * @return true when critical() and processErrorExit() were emitted and the
952 : : * caller must stop.
953 : : */
954 : : auto refuseUnfinishedGitOperation() -> bool;
955 : :
956 : : /**
957 : : * @brief The unfinished git operation in progress in the store, if any.
958 : : *
959 : : * The detection behind refuseUnfinishedGitOperation(), without emitting a
960 : : * refusal: a backend re-checks it when a save's gpg step has finished (a
961 : : * pull queued before the save, from the asynchronous Update, may have
962 : : * finished and left a conflict meanwhile) so the entry is not placed or
963 : : * committed into the operation.
964 : : * @return A ready-to-show reason naming the operation (rebase, merge,
965 : : * cherry-pick or revert), or an empty string when none is in
966 : : * progress, git is off, or the store is not a repository.
967 : : */
968 : : auto unfinishedGitOperationReason() -> QString;
969 : :
970 : : /**
971 : : * @brief Refuse a store change while a Git pull is still queued or running.
972 : : *
973 : : * An operation checks the repository when it is requested, but a pull queued
974 : : * before it (the asynchronous Update) has not run yet, so a conflict it will
975 : : * cause is not visible. For operations that commit without a later point to
976 : : * re-check (every delete, move and copy, and the `pass` backend, whose
977 : : * single `pass insert` commits by itself), refuse while the pull is in
978 : : * flight so the change cannot land in the conflict it leaves. Nothing is
979 : : * refused when Git is off or no pull is pending.
980 : : * @return true when critical() and processErrorExit() were emitted and the
981 : : * caller must stop.
982 : : */
983 : : auto refusePendingPull() -> bool;
984 : :
985 : : /**
986 : : * @brief Refuse an Init() under initIfUnchanged() when the folder's list no
987 : : * longer reads as the caller read it.
988 : : *
989 : : * Called by each backend at the last point before the list is written or
990 : : * `pass init` is started. Outside initIfUnchanged() nothing is compared.
991 : : * @return true when critical() and processErrorExit() were emitted and the
992 : : * caller must stop.
993 : : */
994 : : auto refuseChangedList() -> bool;
995 : :
996 : : /**
997 : : * @brief Refuse an Init() under initIfUnchanged() while the executor has
998 : : * work queued or running, for a backend whose external tool writes
999 : : * the list only when its process runs.
1000 : : *
1001 : : * refuseChangedList() can only compare when the request is made. With
1002 : : * nothing ahead of it, `pass init` starts right away and the gap stays
1003 : : * that of a process start.
1004 : : * @return true when critical() and processErrorExit() were emitted and the
1005 : : * caller must stop.
1006 : : */
1007 : : auto refuseBusyForExpectedList() -> bool;
1008 : :
1009 : : /**
1010 : : * @brief Execute external wrapper command.
1011 : : * @param id Process identifier.
1012 : : * @param app Executable path.
1013 : : * @param args Command arguments.
1014 : : * @param readStdout Capture stdout.
1015 : : * @param readStderr Capture stderr.
1016 : : */
1017 : : void executeWrapper(PROCESS id, const QString &app, const QStringList &args,
1018 : : bool readStdout = true, bool readStderr = true);
1019 : : /**
1020 : : * @brief Generate random password from charset.
1021 : : * @param charset Character set.
1022 : : * @param length Password length.
1023 : : * @return Generated password.
1024 : : */
1025 : : auto generateRandomPassword(const QString &charset, unsigned int length)
1026 : : -> QString;
1027 : : /**
1028 : : * @brief Generate random number in range.
1029 : : * @param bound Upper bound (exclusive).
1030 : : * @return Random number.
1031 : : */
1032 : : auto boundedRandom(quint32 bound) -> quint32;
1033 : : /**
1034 : : * @brief Set or remove an environment variable.
1035 : : *
1036 : : * @param name Variable name (e.g. "PASSWORD_STORE_DIR"), no trailing '='.
1037 : : * @param value New value; an empty string removes the variable entirely.
1038 : : */
1039 : : void setEnvVar(const QString &name, const QString &value);
1040 : :
1041 : : /**
1042 : : * @brief Pin byte-for-byte Git attributes for the store's encrypted files.
1043 : : *
1044 : : * Writes override lines for `*.gpg`, `.gpg-id` and `.gpg-id.sig` into the
1045 : : * store repository's private `info/attributes`, which outranks any in-tree
1046 : : * `.gitattributes` a co-writer may push (`*.gpg text`, a
1047 : : * working-tree-encoding or a filter) that would otherwise make Git rewrite
1048 : : * the ciphertext QtPass commits so it no longer decrypts. Written only when
1049 : : * the store is its own Git repository (a `.git` directory); a worktree `.git`
1050 : : * file or a store nested in a larger repository is left untouched.
1051 : : * Idempotent: marked and rewritten only when absent or changed.
1052 : : */
1053 : : void pinStoreGitAttributes();
1054 : :
1055 : : /**
1056 : : * @brief Execute wrapper with input.
1057 : : * @param id Process identifier.
1058 : : * @param app Executable path.
1059 : : * @param args Command arguments.
1060 : : * @param input Input to pass to stdin.
1061 : : * @param readStdout Capture stdout.
1062 : : * @param readStderr Capture stderr.
1063 : : */
1064 : : void executeWrapper(PROCESS id, const QString &app, const QStringList &args,
1065 : : QString input, bool readStdout, bool readStderr);
1066 : : /**
1067 : : * @brief Hook invoked just before a wrapped command is dispatched.
1068 : : *
1069 : : * Default is a no-op; backends override it to wrap execution (e.g.
1070 : : * ImitatePass registers a transaction). Keeps the dispatch surface a
1071 : : * single non-virtual executeWrapper instead of an overridden one.
1072 : : * @param id Process identifier of the command about to run.
1073 : : */
1074 : : virtual void beforeExecute(PROCESS id);
1075 : :
1076 : : protected slots:
1077 : : /**
1078 : : * @brief Handle process completion.
1079 : : * @param id Process identifier.
1080 : : * @param exitCode Process exit code.
1081 : : * @param out Standard output.
1082 : : * @param err Standard error.
1083 : : */
1084 : : virtual void finished(int id, int exitCode, const QString &out,
1085 : : const QString &err);
1086 : :
1087 : : private:
1088 : : /**
1089 : : * @brief What skippedGpgId() concludes at one folder on its way up.
1090 : : * @param dir Absolute folder path.
1091 : : * @return Nothing when the folder has no list and never had one here, so
1092 : : * the walk goes on; else the answer: no skipped list when the
1093 : : * folder has its own, or its `.gpg-id` path when that is a link,
1094 : : * is gone after it was accepted, or the record cannot be read
1095 : : * (with the record's error).
1096 : : */
1097 : : static auto gpgIdVerdictIn(const QString &dir) -> std::optional<SkippedWalk>;
1098 : : /**
1099 : : * @brief The folders (cleaned absolute paths) whose re-encryption did not
1100 : : * finish, for every store and both backends.
1101 : : * @return The shared set, for this session.
1102 : : */
1103 : : static auto heldScopes() -> QSet<QString> &;
1104 : : /**
1105 : : * @brief @p path as an absolute, cleaned path, relative ones taken from
1106 : : * the current store.
1107 : : * @param path A folder or entry.
1108 : : * @return The cleaned absolute path.
1109 : : */
1110 : : [[nodiscard]] auto scopePath(const QString &path) const -> QString;
1111 : : /// Set while GitPushAutomatic() runs GitPush().
1112 : : bool m_pushIsAutomatic = false;
1113 : : /**
1114 : : * @brief What initIfUnchanged() expects the list to read as, for
1115 : : * refuseChangedList(); empty outside it.
1116 : : */
1117 : : struct ExpectedList {
1118 : : /** @brief The folder given to recipientsForEditing(). */
1119 : : QString dir;
1120 : : /** @brief The store root given to recipientsForEditing(). */
1121 : : QString passStore;
1122 : : /** @brief The state read then. */
1123 : : RecipientsForEditing::State state = RecipientsForEditing::State::Unsigned;
1124 : : /** @brief The recipients read then. */
1125 : : QStringList recipients;
1126 : : };
1127 : : /** @brief Set during initIfUnchanged(). */
1128 : : std::optional<ExpectedList> m_expectedList;
1129 : : /** @brief Set when refuseChangedList() or refuseBusyForExpectedList()
1130 : : * refused during initIfUnchanged(). */
1131 : : bool m_expectedListRefused = false;
1132 : : /// Files of the Show() calls still in flight, oldest first.
1133 : : QQueue<QString> m_pendingShows;
1134 : : /// Inserts that have started queueing but not yet reported; see queueInsert.
1135 : : int m_insertsPending = 0;
1136 : : /// The entries of the inserts counted in m_insertsPending, in queue order.
1137 : : QQueue<QString> m_insertedEntries;
1138 : : /// The entry of the insert whose report is going out; see reportedInsert().
1139 : : QString m_reportedInsert;
1140 : : /**
1141 : : * @brief Report a process that exited non-zero; called by finished().
1142 : : *
1143 : : * Always ends in processErrorExit(). A failed insert first emits
1144 : : * insertFailed(), and critical() too when the entry was written and only
1145 : : * a git step after it failed; failed key generation first emits
1146 : : * generateGPGKeysFailed().
1147 : : * @param pid Which kind of process failed.
1148 : : * @param exitCode Its exit code.
1149 : : * @param out Its stdout; not used.
1150 : : * @param err Its stderr, or the Executor's message for a failed start.
1151 : : */
1152 : : void handleProcessError(PROCESS pid, int exitCode, const QString &out,
1153 : : const QString &err);
1154 : : /**
1155 : : * @brief Put the translated reason for a failed insert above what gpg
1156 : : * itself printed, leaving out the machine-readable `[GNUPG:]` lines.
1157 : : * @param friendly Message from gpgErrorMessage().
1158 : : * @param err gpg's stderr.
1159 : : * @return @p friendly, followed by the human-readable rest of @p err when
1160 : : * there is any.
1161 : : */
1162 : : auto formatInsertError(const QString &friendly, const QString &err)
1163 : : -> QString;
1164 : : /**
1165 : : * @brief Emit the signals for a process that exited with 0; called by
1166 : : * finished() for everything but PASS_SHOW.
1167 : : *
1168 : : * finishedAnyWithPid() goes out only for a process whose output cannot
1169 : : * hold a secret (Enums::processInfo()), then the signal of that kind of
1170 : : * process (finishedGitPull() and so on), if it has one.
1171 : : * @param pid Which kind of process finished.
1172 : : * @param out Its stdout.
1173 : : * @param err Its stderr.
1174 : : */
1175 : : void emitProcessFinishedSignal(PROCESS pid, const QString &out,
1176 : : const QString &err);
1177 : : /**
1178 : : * @brief Refuse an operation on something that is not part of the store.
1179 : : *
1180 : : * Emits startingExecuteWrapper(), critical() and processErrorExit(), so
1181 : : * an interface that arms itself when an operation starts is released
1182 : : * again although nothing was started. refuseLinkedPath() and
1183 : : * refuseFolderOutsideStore() say why.
1184 : : * @param why Translated reason, shown to the user.
1185 : : */
1186 : : void refuseAsNotPartOfStore(const QString &why);
1187 : :
1188 : : signals:
1189 : : /**
1190 : : * @brief Nothing of the store's runs or waits any more (isIdle()).
1191 : : *
1192 : : * Emitted when the command queue drains. The main window re-enables the
1193 : : * profile selector on it: switching stores is held back while commands
1194 : : * for the current one are still queued.
1195 : : */
1196 : : void idle();
1197 : : /**
1198 : : * @brief Emitted each time a queued process is about to start, and by
1199 : : * the refusals that go on to emit processErrorExit().
1200 : : *
1201 : : * The main window shows the busy state on it. An operation made of
1202 : : * several processes emits it once per process; the operation then ends
1203 : : * with a `finished...` signal or with processErrorExit().
1204 : : */
1205 : : void startingExecuteWrapper();
1206 : : /**
1207 : : * @brief Progress or a non-fatal problem worth a line in the status bar
1208 : : * ("Creating backup commit", "Git pull failed: ...").
1209 : : *
1210 : : * Nothing depends on it being shown; an error the user must see goes out
1211 : : * as critical() instead.
1212 : : * @param msg Translated status text.
1213 : : * @param timeout How long to show it, in milliseconds.
1214 : : */
1215 : : void statusMsg(const QString &msg, int timeout);
1216 : : /**
1217 : : * @brief Something went wrong that the user has to be told about in a
1218 : : * dialog, such as a refused path or a failed backup commit.
1219 : : *
1220 : : * Says only what happened; it does not by itself mean an operation is
1221 : : * over. Every failure reported through the command queue goes on to
1222 : : * processErrorExit(), and so do some refusals. Other checks made before
1223 : : * anything is queued, such as an entry that already exists or a
1224 : : * recipient list that cannot be used, emit this signal and nothing
1225 : : * else.
1226 : : * @param title Translated dialog title.
1227 : : * @param message Translated description.
1228 : : */
1229 : : void critical(const QString &title, const QString &message);
1230 : :
1231 : : /**
1232 : : * @brief An operation ended in failure: its process exited non-zero,
1233 : : * could not be started or crashed, or the operation was refused.
1234 : : *
1235 : : * The counterpart of the `finished...` signals for an operation that
1236 : : * queued a command: it ends in one or the other. The main window
1237 : : * releases the busy state and shows @p err in the password pane. One
1238 : : * case emits both: when RealPass has removed a linked folder but could
1239 : : * not commit that, this signal is followed by finishedRemove(), because
1240 : : * the store did change.
1241 : : *
1242 : : * Before anything is queued the paths differ, so a caller must not wait
1243 : : * for this signal after every call. A path behind a link and an
1244 : : * unfinished Git operation are refused with startingExecuteWrapper(),
1245 : : * critical() and this signal. Other early checks, such as an entry that
1246 : : * already exists, emit critical() alone and return.
1247 : : *
1248 : : * insertFailed() and generateGPGKeysFailed() are emitted before this
1249 : : * signal whenever their operation fails through a queued command, be it
1250 : : * a non-zero exit, a crash or a process that could not be started, so
1251 : : * their dialogs need not guess whose failure it is.
1252 : : * generateGPGKeysFailed() also comes first when no gpg executable is
1253 : : * configured and nothing is queued at all. A refusal that reaches this
1254 : : * signal without queuing anything emits neither of them.
1255 : : * @param exitCode Exit code of the process; -1 when it did not exit
1256 : : * normally, 1 for a refusal.
1257 : : * @param err What to show the user: stderr, or a translated message.
1258 : : */
1259 : : void processErrorExit(int exitCode, const QString &err);
1260 : :
1261 : : /**
1262 : : * @brief A process of any kind finished successfully and its output
1263 : : * cannot contain a secret.
1264 : : *
1265 : : * Feeds the process output panel. Processes whose output may hold a
1266 : : * decrypted entry (Enums::processInfo()) never emit it, so a receiver
1267 : : * may log or display @p out and @p err as they are.
1268 : : * @param out Standard output from the process.
1269 : : * @param err Standard error from the process.
1270 : : * @param pid Which kind of process it was.
1271 : : */
1272 : : void finishedAnyWithPid(const QString &out, const QString &err,
1273 : : Enums::PROCESS pid);
1274 : : /**
1275 : : * @brief `git init` in the store succeeded; the store is a repository
1276 : : * now and the tree is re-read.
1277 : : * @param out Standard output.
1278 : : * @param err Standard error.
1279 : : */
1280 : : void finishedGitInit(const QString &out, const QString &err);
1281 : : /**
1282 : : * @brief `git pull` succeeded; entries may have changed on disk.
1283 : : * @param out Standard output.
1284 : : * @param err Standard error.
1285 : : */
1286 : : void finishedGitPull(const QString &out, const QString &err);
1287 : : /**
1288 : : * @brief `git push` succeeded.
1289 : : * @param out Standard output.
1290 : : * @param err Standard error.
1291 : : */
1292 : : void finishedGitPush(const QString &out, const QString &err);
1293 : : /**
1294 : : * @brief Emitted when a Show() succeeds.
1295 : : *
1296 : : * Requests complete in the order they were queued, so @p file is the
1297 : : * argument of the Show() this result belongs to. Every receiver checks it
1298 : : * against what it asked for; a failed decrypt emits processErrorExit()
1299 : : * instead and never finishedShow().
1300 : : * @param out Decrypted password file content, as text: fine to show or
1301 : : * copy, but only to write back when @p lossless.
1302 : : * @param file The Show() argument this content is for.
1303 : : * @param lossless false when @p out does not encode back to the entry's
1304 : : * bytes (they are not UTF-8, or begin with a byte order mark), so
1305 : : * saving it would change the entry (Executor::lastOutputLossless()).
1306 : : */
1307 : : void finishedShow(const QString &out, const QString &file,
1308 : : bool lossless = true);
1309 : : /**
1310 : : * @brief An Insert() succeeded: the entry is in the store and, with Git
1311 : : * in use, committed.
1312 : : *
1313 : : * In ImitatePass this ends the whole transaction (gpg, then git add and
1314 : : * commit), not just the gpg step. The password dialog closes on it. A
1315 : : * failure reported through the command queue goes out as insertFailed()
1316 : : * and processErrorExit() instead; an insert refused before anything is
1317 : : * queued emits neither this signal nor insertFailed().
1318 : : * @param out Standard output of the operation's processes.
1319 : : * @param err Standard error.
1320 : : */
1321 : : void finishedInsert(const QString &out, const QString &err);
1322 : : /**
1323 : : * @brief A Remove() succeeded; the entry or folder is gone from the store.
1324 : : * @param out Standard output.
1325 : : * @param err Standard error.
1326 : : */
1327 : : void finishedRemove(const QString &out, const QString &err);
1328 : : /**
1329 : : * @brief An Init() succeeded: the folder's `.gpg-id` holds the new
1330 : : * recipient list.
1331 : : * @param out Standard output.
1332 : : * @param err Standard error.
1333 : : */
1334 : : void finishedInit(const QString &out, const QString &err);
1335 : : /**
1336 : : * @brief A Move() succeeded; the entry or folder is under its new name.
1337 : : * @param out Standard output.
1338 : : * @param err Standard error.
1339 : : */
1340 : : void finishedMove(const QString &out, const QString &err);
1341 : : /**
1342 : : * @brief A Copy() succeeded; the copy exists beside the original.
1343 : : * @param out Standard output.
1344 : : * @param err Standard error.
1345 : : */
1346 : : void finishedCopy(const QString &out, const QString &err);
1347 : : /**
1348 : : * @brief GenerateGPGKeys() succeeded; the new key pair is in the keyring.
1349 : : *
1350 : : * The key generation dialog closes on it. A failure emits
1351 : : * generateGPGKeysFailed() instead.
1352 : : * @param out Standard output.
1353 : : * @param err Standard error.
1354 : : */
1355 : : void finishedGenerateGPGKeys(const QString &out, const QString &err);
1356 : : /**
1357 : : * @brief Emitted when GPG key generation fails, alongside the generic
1358 : : * processErrorExit(); lets the keygen dialog react to its own
1359 : : * failure only, not to any other command failing meanwhile.
1360 : : * @param err What gpg (or the setup) reported.
1361 : : */
1362 : : void generateGPGKeysFailed(const QString &err);
1363 : : /**
1364 : : * @brief Emitted when an Insert() fails through a queued command, before
1365 : : * the generic processErrorExit(): the process exited non-zero,
1366 : : * crashed or could not be started, or the entry could not be put in
1367 : : * place afterwards. Lets the password dialog keep what was typed
1368 : : * and say why, without reacting to any other command failing
1369 : : * meanwhile. An insert refused before anything is queued does not
1370 : : * emit it.
1371 : : * @param err What gpg, pass or the placement of the entry reported.
1372 : : * @param written true when this insert did put the entry in the store and
1373 : : * only a later step (git add or commit) failed.
1374 : : */
1375 : : void insertFailed(const QString &err, bool written);
1376 : : /**
1377 : : * @brief The newest Grep() is over; an empty list means no entry matched.
1378 : : *
1379 : : * Comes from NativeGrep on both backends and bypasses finished(), since
1380 : : * the matching lines are decrypted content. A search superseded by a
1381 : : * newer one never reports.
1382 : : * @param results List of (entry path, matching lines) pairs.
1383 : : */
1384 : : void finishedGrep(const QList<QPair<QString, QStringList>> &results);
1385 : : };
1386 : :
1387 : : /**
1388 : : * @brief Maps GPG stderr (which may include --status-fd 2 tokens) to a
1389 : : * translated user-friendly encryption error string.
1390 : : *
1391 : : * Checks machine-readable [GNUPG:] status tokens first (locale-independent),
1392 : : * then falls back to case-insensitive substring matching for GPG builds that
1393 : : * do not emit status tokens. Returns an empty string when no known pattern
1394 : : * matches.
1395 : : *
1396 : : * Declared here so it can be exercised by unit tests without linking the full
1397 : : * Pass object.
1398 : : * @param err gpg's stderr, with or without `[GNUPG:]` status lines.
1399 : : * @return A translated message, or an empty string for an error it does
1400 : : * not recognise.
1401 : : */
1402 : : QString gpgErrorMessage(const QString &err);
1403 : :
1404 : : #endif // SRC_PASS_H_
|