QtPass Developer documentation
QtPass test coverage
Current view: top level - src/gpgidgeneration.cpp (source / functions) Coverage Total Hit
Test: QtPass Lines: 94.4 % 426 402
Test Date: 2026-12-03 23:34:20 Functions: 100.0 % 47 47
Branches: 83.4 % 295 246

             Branch data     Line data    Source code
       1                 :             : // SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
       2                 :             : // SPDX-License-Identifier: GPL-3.0-or-later
       3                 :             : /**
       4                 :             :  * @file
       5                 :             :  * @brief Implements the `.gpg-id` generation header and the per-store record
       6                 :             :  * of accepted generations.
       7                 :             :  */
       8                 :             : #include "gpgidgeneration.h"
       9                 :             : #include "qtpasslogging.h"
      10                 :             : #include <QCoreApplication>
      11                 :             : #include <QCryptographicHash>
      12                 :             : #include <QDir>
      13                 :             : #include <QFile>
      14                 :             : #include <QFileInfo>
      15                 :             : #include <QJsonDocument>
      16                 :             : #include <QJsonObject>
      17                 :             : #include <QLockFile>
      18                 :             : #include <QMap>
      19                 :             : #include <QMutex>
      20                 :             : #include <QMutexLocker>
      21                 :             : #include <QSaveFile>
      22                 :             : #include <QSettings>
      23                 :             : #include <QStringDecoder>
      24                 :             : #include <QUuid>
      25                 :             : #include <algorithm>
      26                 :             : #include <utility>
      27                 :             : 
      28                 :             : const QByteArray GpgIdGeneration::kGenerationPrefix =
      29                 :             :     QByteArrayLiteral("# QtPass-GpgId-Generation: ");
      30                 :             : const QByteArray GpgIdGeneration::kFolderPrefix =
      31                 :             :     QByteArrayLiteral("# QtPass-GpgId-Folder: ");
      32                 :             : const QByteArray GpgIdGeneration::kStorePrefix =
      33                 :             :     QByteArrayLiteral("# QtPass-GpgId-Store: ");
      34                 :             : const qint64 GpgIdGeneration::kMaxGeneration = 999999999999999999LL;
      35                 :             : 
      36                 :             : namespace {
      37                 :             : constexpr int kMaxDigits = 18;
      38                 :             : constexpr QByteArrayView kOurComment("# QtPass-GpgId-");
      39                 :             : 
      40                 :             : // Not a QObject: messages live under the class name. lupdate gets that context
      41                 :             : // from the class's own methods, but drops strings in the free functions and
      42                 :             : // structs here, so those spell it out with QCoreApplication::translate().
      43                 :             : auto tr(const char *text) -> QString {
      44                 :          73 :   return QCoreApplication::translate("GpgIdGeneration", text);
      45                 :             : }
      46                 :             : 
      47                 :             : /// Serialises read-compare-write on the record in this process (the
      48                 :             : /// re-encryption worker reads while the UI may write); see Transaction for
      49                 :             : /// the cross-process lock file.
      50                 :         718 : QMutex &recordLock() {
      51                 :         718 :   static QMutex mutex;
      52                 :         718 :   return mutex;
      53                 :             : }
      54                 :             : 
      55                 :             : /// How long a transaction waits for another process to let go of the record.
      56                 :             : constexpr int kRecordLockTimeoutMs = 3000;
      57                 :             : 
      58                 :             : /// Per list: the highest generation accepted or written, and the SHA-256 of
      59                 :             : /// its exact bytes once known (empty after a reservation).
      60                 :       39593 : struct Entry {
      61                 :             :   qint64 generation = 0;
      62                 :             :   QString digest;
      63                 :             : };
      64                 :             : using Entries = QMap<QString, Entry>;
      65                 :             : /// Per store, by GpgIdGeneration::key() of its root: the store id this
      66                 :             : /// device knows it by.
      67                 :             : using Stores = QMap<QString, QString>;
      68                 :             : 
      69                 :             : /// Everything the record holds.
      70                 :         706 : struct Record {
      71                 :             :   Entries lists;
      72                 :             :   Stores stores;
      73                 :             : };
      74                 :             : 
      75                 :             : /// Whether @p id is a store id as QtPass writes it: 32 lowercase hex digits.
      76                 :        6097 : auto isStoreId(const QByteArray &id) -> bool {
      77         [ +  + ]:        6097 :   return id.size() == 32 && std::all_of(id.cbegin(), id.cend(), [](char c) {
      78         [ +  + ]:      194891 :            return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f');
      79                 :        6097 :          });
      80                 :             : }
      81                 :             : 
      82                 :             : constexpr QLatin1StringView kRecordName("QtPass-gpgid-generations.json");
      83                 :             : /// The store ids live in a file of their own, under the record's lock: a
      84                 :             : /// QtPass from before store ids rewrites the record whole, and would drop
      85                 :             : /// anything it does not know from it.
      86                 :             : constexpr QLatin1StringView kStoresName("QtPass-gpgid-stores.json");
      87                 :             : constexpr int kRecordFormat = 1;
      88                 :             : 
      89                 :             : /// A file QtPass reads and writes itself, not QSettings: no cache between
      90                 :             : /// read and write, no registry (on Windows a QSettings "file" is a registry
      91                 :             : /// path). Placed where QSettings would put an ini file, so the platform
      92                 :             : /// convention and the tests' redirection of that path both apply.
      93                 :        2242 : auto recordPath() -> QString {
      94                 :             :   const QSettings probe(QSettings::IniFormat, QSettings::UserScope,
      95                 :        2242 :                         QCoreApplication::organizationName().isEmpty()
      96   [ +  -  -  +  :        4484 :                             ? QStringLiteral("IJHack")
                -  -  - ]
      97                 :             :                             : QCoreApplication::organizationName(),
      98         [ +  + ]:        4484 :                         QStringLiteral("QtPass-gpgid-generations"));
      99                 :        6726 :   return QFileInfo(probe.fileName()).absolutePath() + QLatin1Char('/') +
     100                 :        4484 :          kRecordName;
     101                 :        2242 : }
     102                 :             : 
     103                 :             : /// The store ids' file, next to the record.
     104                 :         719 : auto storesPath() -> QString {
     105                 :        2157 :   return QFileInfo(recordPath()).absolutePath() + QLatin1Char('/') +
     106                 :        1438 :          kStoresName;
     107                 :             : }
     108                 :             : 
     109                 :             : /// One list's entry in the record, or nothing when it is malformed. The
     110                 :             : /// generation travels as a string: JSON numbers are doubles, and the grammar
     111                 :             : /// admits 18 digits.
     112                 :        9236 : auto recordEntry(const QJsonValue &value) -> std::optional<Entry> {
     113         [ -  + ]:        9236 :   if (!value.isObject()) {
     114                 :           0 :     return std::nullopt;
     115                 :             :   }
     116                 :        9236 :   const QJsonObject item = value.toObject();
     117                 :        9236 :   const QString generation = item.value(QLatin1String("generation")).toString();
     118   [ +  +  -  + ]:        9236 :   if (generation.isEmpty() || generation.size() > kMaxDigits) {
     119                 :           1 :     return std::nullopt;
     120                 :             :   }
     121         [ +  + ]:       18811 :   for (const QChar c : generation) {
     122   [ +  -  +  - ]:        9576 :     if (c < QLatin1Char('0') || c > QLatin1Char('9')) {
     123                 :           0 :       return std::nullopt;
     124                 :             :     }
     125                 :             :   }
     126                 :        9235 :   Entry entry;
     127                 :        9235 :   entry.generation = generation.toLongLong();
     128                 :       18470 :   entry.digest = item.value(QLatin1String("sha256")).toString();
     129                 :             :   return entry;
     130                 :        9236 : }
     131                 :             : 
     132                 :             : /// The JSON object a record file holds, when it is one of @p format and
     133                 :             : /// carries an object under @p name.
     134                 :        1300 : auto recordObject(const QByteArray &bytes, const QString &name)
     135                 :             :     -> std::optional<QJsonObject> {
     136                 :        1300 :   QJsonParseError parse{};
     137                 :        1300 :   const QJsonDocument doc = QJsonDocument::fromJson(bytes, &parse);
     138   [ +  +  +  -  :        1300 :   if (parse.error != QJsonParseError::NoError || !doc.isObject()) {
                      + ]
     139                 :           4 :     return std::nullopt;
     140                 :             :   }
     141                 :        1296 :   const QJsonObject root = doc.object();
     142                 :        1296 :   const QJsonValue inner = root.value(name);
     143   [ +  +  +  -  :        2592 :   if (root.value(QLatin1String("format")).toInt() != kRecordFormat ||
             -  +  -  + ]
     144                 :             :       !inner.isObject()) {
     145                 :           0 :     return std::nullopt;
     146                 :             :   }
     147                 :        2592 :   return inner.toObject();
     148                 :        1300 : }
     149                 :             : 
     150                 :             : /// The record's entries from its bytes, or nothing when any part of it is
     151                 :             : /// not what QtPass writes.
     152                 :         701 : auto parseRecord(const QByteArray &bytes) -> std::optional<Entries> {
     153                 :             :   const std::optional<QJsonObject> byKey =
     154                 :        1402 :       recordObject(bytes, QStringLiteral("lists"));
     155         [ +  + ]:         701 :   if (!byKey) {
     156                 :           4 :     return std::nullopt;
     157                 :             :   }
     158                 :         697 :   Entries entries;
     159         [ +  + ]:       10629 :   for (auto it = byKey->constBegin(); it != byKey->constEnd(); ++it) {
     160                 :        9236 :     const std::optional<Entry> entry = recordEntry(it.value());
     161         [ +  + ]:        9236 :     if (!entry) {
     162                 :           1 :       return std::nullopt;
     163                 :             :     }
     164                 :       18470 :     entries.insert(it.key(), *entry);
     165                 :             :   }
     166                 :             :   return entries;
     167                 :             : }
     168                 :             : 
     169                 :             : /// The store ids from their file's bytes, or nothing when any part of it is
     170                 :             : /// not what QtPass writes.
     171                 :         599 : auto parseStores(const QByteArray &bytes) -> std::optional<Stores> {
     172                 :             :   const std::optional<QJsonObject> byKey =
     173                 :        1198 :       recordObject(bytes, QStringLiteral("stores"));
     174         [ -  + ]:         599 :   if (!byKey) {
     175                 :           0 :     return std::nullopt;
     176                 :             :   }
     177                 :         599 :   Stores stores;
     178         [ +  + ]:        7185 :   for (auto it = byKey->constBegin(); it != byKey->constEnd(); ++it) {
     179                 :             :     const QString id =
     180                 :        5989 :         it.value().toObject().value(QLatin1String("id")).toString();
     181   [ +  -  +  +  :       17967 :     if (!it.value().isObject() || !isStoreId(id.toLatin1())) {
                   +  + ]
     182                 :           2 :       return std::nullopt;
     183                 :             :     }
     184                 :       11974 :     stores.insert(it.key(), id);
     185                 :             :   }
     186                 :             :   return stores;
     187                 :             : }
     188                 :             : 
     189                 :             : /// A record file as on disk, parsed by @p parse: empty where there is no
     190                 :             : /// file yet; nothing with @p error set when the file cannot be read or does
     191                 :             : /// not parse ("unknown", never "never seen").
     192                 :             : template <typename T, typename Parse>
     193                 :        1421 : auto loadFile(const QString &path, Parse parse, QString *error)
     194                 :             :     -> std::optional<T> {
     195         [ +  + ]:        1421 :   if (!QFileInfo::exists(path)) {
     196                 :         121 :     return T{};
     197                 :             :   }
     198                 :        1300 :   QFile file(path);
     199      [ +  -  + ]:        1300 :   if (!file.open(QIODevice::ReadOnly)) {
     200         [ #  # ]:           0 :     if (error)
     201                 :           0 :       *error = QCoreApplication::translate(
     202                 :             :                    "GpgIdGeneration",
     203                 :             :                    "The generation record of the recipient lists, %1, cannot "
     204                 :             :                    "be accessed.")
     205                 :           0 :                    .arg(path);
     206                 :           0 :     return std::nullopt;
     207                 :             :   }
     208                 :        2600 :   std::optional<T> value = parse(file.readAll());
     209   [ +  +  +  - ]:        1300 :   if (!value && error) {
     210                 :           7 :     *error = QCoreApplication::translate(
     211                 :             :                  "GpgIdGeneration",
     212                 :             :                  "The generation record of the recipient lists, %1, is not "
     213                 :             :                  "readable. Signed recipient lists are not accepted until "
     214                 :             :                  "it is repaired or removed (which forgets what was accepted "
     215                 :             :                  "before).")
     216                 :          14 :                  .arg(path);
     217                 :             :   }
     218                 :             :   return value;
     219                 :        1300 : }
     220                 :             : 
     221                 :             : /// A record file written through, whole, in place: `format` and @p inner
     222                 :             : /// under @p name. Nothing is cached: a failed write leaves the next
     223                 :             : /// transaction reading what is on disk.
     224                 :         155 : auto saveFile(const QString &path, const QString &name,
     225                 :             :               const QJsonObject &inner, QString *error) -> bool {
     226                 :         155 :   QJsonObject root;
     227                 :         155 :   root.insert(QLatin1String("format"), kRecordFormat);
     228                 :         155 :   root.insert(name, inner);
     229                 :         155 :   QSaveFile file(path);
     230      [ +  -  + ]:         155 :   if (!file.open(QIODevice::WriteOnly)) {
     231         [ #  # ]:           0 :     if (error)
     232                 :           0 :       *error = QCoreApplication::translate(
     233                 :             :                    "GpgIdGeneration",
     234                 :             :                    "The generation record of the recipient lists, %1, cannot "
     235                 :             :                    "be written.")
     236                 :           0 :                    .arg(path);
     237                 :           0 :     return false;
     238                 :             :   }
     239                 :         155 :   file.setPermissions(QFile::ReadOwner | QFile::WriteOwner);
     240                 :         155 :   const QByteArray bytes = QJsonDocument(root).toJson(QJsonDocument::Indented);
     241   [ +  +  -  +  :         155 :   if (file.write(bytes) != bytes.size() || !file.commit()) {
                   -  + ]
     242                 :           0 :     qCWarning(lcQtPass) << "Could not write the .gpg-id generation record"
     243                 :           0 :                         << path << file.errorString();
     244         [ #  # ]:           0 :     if (error)
     245                 :           0 :       *error = QCoreApplication::translate(
     246                 :             :                    "GpgIdGeneration",
     247                 :             :                    "The generation record of the recipient lists, %1, cannot "
     248                 :             :                    "be written.")
     249                 :           0 :                    .arg(path);
     250                 :           0 :     return false;
     251                 :             :   }
     252                 :             :   return true;
     253                 :         155 : }
     254                 :             : 
     255                 :         123 : auto saveRecord(const QString &path, const Entries &entries, QString *error)
     256                 :             :     -> bool {
     257                 :         123 :   QJsonObject lists;
     258         [ +  + ]:         995 :   for (auto it = entries.constBegin(); it != entries.constEnd(); ++it) {
     259                 :         872 :     QJsonObject item;
     260                 :         872 :     item.insert(QLatin1String("generation"),
     261   [ +  +  +  + ]:        2616 :                 QString::number(it.value().generation));
     262         [ +  + ]:         872 :     if (!it.value().digest.isEmpty()) {
     263                 :         671 :       item.insert(QLatin1String("sha256"), it.value().digest);
     264                 :             :     }
     265                 :         872 :     lists.insert(it.key(), item);
     266                 :         872 :   }
     267                 :         369 :   return saveFile(path, QStringLiteral("lists"), lists, error);
     268                 :         123 : }
     269                 :             : 
     270                 :          32 : auto saveStores(const QString &path, const Stores &stores, QString *error)
     271                 :             :     -> bool {
     272                 :          32 :   QJsonObject byKey;
     273         [ +  + ]:         206 :   for (auto it = stores.constBegin(); it != stores.constEnd(); ++it) {
     274                 :         174 :     QJsonObject item;
     275                 :         174 :     item.insert(QLatin1String("id"), it.value());
     276                 :         174 :     byKey.insert(it.key(), item);
     277                 :         174 :   }
     278                 :          96 :   return saveFile(path, QStringLiteral("stores"), byKey, error);
     279                 :          32 : }
     280                 :             : 
     281                 :             : /// Process mutex, then a lock file against a second QtPass (no single-instance
     282                 :             : /// guard, a Flatpak next to a native one), then a fresh read of the record and
     283                 :             : /// the store ids. When `ok()` is false (no lock, or a file that does not
     284                 :             : /// parse) the caller neither uses nor writes them: RecordUnavailable.
     285                 :             : struct Transaction {
     286                 :             :   QMutexLocker<QMutex> mutex{&recordLock()};
     287                 :             :   QString path{recordPath()};
     288                 :             :   // The record's folder may not exist before its first write; the lock file
     289                 :             :   // needs it now.
     290                 :             :   bool haveFolder{QDir().mkpath(QFileInfo(path).absolutePath())};
     291                 :             :   QLockFile lock{path + QStringLiteral(".lock")};
     292                 :             :   bool locked{haveFolder && lock.tryLock(kRecordLockTimeoutMs)};
     293                 :             :   QString problem;
     294                 :             :   QString storesFile{storesPath()};
     295                 :             :   std::optional<Record> entries;
     296                 :             : 
     297                 :        2877 :   Transaction() {
     298         [ +  + ]:         718 :     if (!locked) {
     299                 :           5 :       problem = QCoreApplication::translate(
     300                 :             :                     "GpgIdGeneration",
     301                 :             :                     "The generation record of the recipient lists, %1, could "
     302                 :             :                     "not be locked: another QtPass may be using it, or its "
     303                 :             :                     "folder cannot be written.")
     304                 :          10 :                     .arg(path);
     305                 :          12 :       return;
     306                 :             :     }
     307                 :             :     std::optional<Entries> lists =
     308                 :         713 :         loadFile<Entries>(path, parseRecord, &problem);
     309         [ +  + ]:         713 :     if (!lists) {
     310                 :             :       return;
     311                 :             :     }
     312                 :             :     std::optional<Stores> stores =
     313                 :         708 :         loadFile<Stores>(storesFile, parseStores, &problem);
     314         [ +  + ]:         708 :     if (!stores) {
     315                 :             :       return;
     316                 :             :     }
     317                 :        1412 :     entries = Record{std::move(*lists), std::move(*stores)};
     318                 :           0 :   }
     319                 :             : 
     320                 :         718 :   [[nodiscard]] auto ok(QString *error) const -> bool {
     321         [ +  + ]:         718 :     if (entries) {
     322                 :             :       return true;
     323                 :             :     }
     324         [ +  + ]:          12 :     if (error)
     325                 :           9 :       *error = problem;
     326                 :             :     return false;
     327                 :             :   }
     328                 :             : 
     329                 :             :   /// The record read when the transaction began. Only after ok() said it
     330                 :             :   /// was read: every Transaction in this file checks ok() first.
     331                 :             :   [[nodiscard]] auto record() -> Record & {
     332                 :             :     // NOLINTNEXTLINE(bugprone-unchecked-optional-access): ok() checked it.
     333                 :             :     return *entries;
     334                 :             :   }
     335                 :             :   /// The record, read-only; as record().
     336                 :             :   [[nodiscard]] auto record() const -> const Record & {
     337                 :             :     // NOLINTNEXTLINE(bugprone-unchecked-optional-access): ok() checked it.
     338                 :             :     return *entries;
     339                 :             :   }
     340                 :             : 
     341                 :             :   /// Whether anything is recorded for @p key, a generation 0 included.
     342                 :             :   [[nodiscard]] auto known(const QString &key) const -> bool {
     343                 :         438 :     return record().lists.contains(key);
     344                 :             :   }
     345                 :             : 
     346                 :             :   /// The remembered generation for @p key, 0 when never seen.
     347                 :         267 :   [[nodiscard]] auto generation(const QString &key) const -> qint64 {
     348                 :         267 :     return record().lists.value(key).generation;
     349                 :             :   }
     350                 :             : 
     351                 :             :   /// The store id this device knows the store by, for @p key of its root;
     352                 :             :   /// nothing before the first one.
     353                 :         259 :   [[nodiscard]] auto store(const QString &key) const -> std::optional<QString> {
     354                 :         259 :     const auto it = record().stores.constFind(key);
     355         [ +  + ]:         259 :     if (it == record().stores.constEnd()) {
     356                 :         162 :       return std::nullopt;
     357                 :             :     }
     358                 :             :     return it.value();
     359                 :             :   }
     360                 :             : 
     361                 :             :   /// Remember @p id for the store with @p key, through to disk.
     362                 :          32 :   auto pinStore(const QString &key, const QString &id, QString *error) -> bool {
     363                 :             :     Stores updated = record().stores;
     364                 :          32 :     updated.insert(key, id);
     365      [ +  +  - ]:          32 :     if (!saveStores(storesFile, updated, error)) {
     366                 :             :       return false;
     367                 :             :     }
     368                 :             :     record().stores = std::move(updated);
     369                 :          32 :     return true;
     370                 :             :   }
     371                 :             : 
     372                 :             :   /// The remembered digest for @p key; nothing when none was recorded (a
     373                 :             :   /// reservation not yet written, or a record from before digests).
     374                 :          94 :   [[nodiscard]] auto digest(const QString &key) const
     375                 :             :       -> std::optional<QString> {
     376                 :          94 :     QString value = record().lists.value(key).digest;
     377         [ +  + ]:          94 :     if (value.isEmpty()) {
     378                 :           4 :       return std::nullopt;
     379                 :             :     }
     380                 :             :     return value;
     381                 :             :   }
     382                 :             : 
     383                 :             :   /// Write @p generation with @p digest (empty: none) for @p key through
     384                 :             :   /// to disk.
     385                 :         123 :   auto remember(const QString &key, qint64 generation, const QString &digest,
     386                 :             :                 QString *error) -> bool {
     387                 :             :     Entries updated = record().lists;
     388                 :         123 :     updated[key] = Entry{generation, digest};
     389      [ +  +  - ]:         123 :     if (!saveRecord(path, updated, error)) {
     390                 :             :       return false;
     391                 :             :     }
     392                 :             :     record().lists = std::move(updated);
     393                 :         123 :     return true;
     394                 :             :   }
     395                 :             : 
     396                 :             :   /// Whether @p generation with @p digest is what is recorded for @p key:
     397                 :             :   /// the list this device accepted last for it.
     398                 :          45 :   [[nodiscard]] auto accepted(const QString &key, qint64 generation,
     399                 :             :                               const QString &digest) const -> bool {
     400         [ +  + ]:          45 :     return this->generation(key) == generation && this->digest(key) == digest;
     401                 :             :   }
     402                 :             : 
     403                 :             :   /// Note @p key at generation 0, once: a later removal of its list is
     404                 :             :   /// then told apart from a folder that never had one.
     405                 :           6 :   auto noteOnce(const QString &key, QString *error) -> bool {
     406      [ +  +  + ]:          11 :     return known(key) || remember(key, 0, QString(), error);
     407                 :             :   }
     408                 :             : 
     409                 :             :   /// Pin @p id for the store with @p key on first sight of it: nothing to
     410                 :             :   /// do when an id is pinned already or @p id is none.
     411                 :          87 :   auto pinOnFirstSight(const QString &key, const std::optional<QString> &id,
     412                 :             :                        QString *error) -> bool {
     413   [ +  +  +  +  :         174 :     if (store(key) || !id) {
                   +  + ]
     414                 :             :       return true;
     415                 :             :     }
     416                 :           5 :     return pinStore(key, *id, error);
     417                 :             :   }
     418                 :             : };
     419                 :             : 
     420                 :             : /// Whether @p value holds a control character (a line break, a tab, a NUL,
     421                 :             : /// DEL): the folder line can carry none of them, so parse() refuses a line
     422                 :             : /// with one and folderOf() a folder whose name has one.
     423                 :         242 : auto hasControl(const QByteArray &value) -> bool {
     424                 :             :   return std::any_of(value.cbegin(), value.cend(), [](const char c) {
     425                 :        1099 :     const auto u = static_cast<unsigned char>(c);
     426         [ +  + ]:        1099 :     return u < 0x20 || u == 0x7f;
     427                 :         242 :   });
     428                 :             : }
     429                 :             : 
     430                 :             : /// Store-relative, `/`-separated, canonical, `.` for the root; nothing when
     431                 :             : /// @p path is not under @p root, or the name holds a control character.
     432                 :         170 : auto relativeFolder(const QString &path, const QString &root)
     433                 :             :     -> std::optional<QString> {
     434                 :         170 :   QString folder = QFileInfo(path).absoluteDir().canonicalPath();
     435         [ -  + ]:         170 :   if (folder.isEmpty()) {
     436                 :           0 :     folder = QFileInfo(path).absolutePath();
     437                 :             :   }
     438                 :         170 :   QString store = QFileInfo(root).canonicalFilePath();
     439         [ -  + ]:         170 :   if (store.isEmpty()) {
     440                 :           0 :     store = QDir::cleanPath(QFileInfo(root).absoluteFilePath());
     441                 :             :   }
     442                 :         170 :   folder = QDir::fromNativeSeparators(QDir::cleanPath(folder));
     443                 :         340 :   store = QDir::fromNativeSeparators(QDir::cleanPath(store));
     444                 :             : #ifdef Q_OS_WIN
     445                 :             :   folder = folder.toLower();
     446                 :             :   store = store.toLower();
     447                 :             : #endif
     448         [ +  + ]:         170 :   if (folder == store) {
     449                 :         127 :     return QStringLiteral(".");
     450                 :             :   }
     451                 :          43 :   const QString prefix = store.endsWith(QLatin1Char('/'))
     452         [ -  + ]:          43 :                              ? std::move(store)
     453                 :          43 :                              : store + QLatin1Char('/');
     454      [ +  +  + ]:          43 :   if (!folder.startsWith(prefix)) {
     455                 :           2 :     return std::nullopt;
     456                 :             :   }
     457                 :          82 :   folder = folder.mid(prefix.size());
     458                 :             :   // The folder line is one line: a name with a line break in it would end
     459                 :             :   // it, and what follows would be read as a recipient of the signed list.
     460                 :             :   // Any other control character parse() refuses: the list written would be
     461                 :             :   // one that cannot be read back.
     462         [ +  + ]:          41 :   if (hasControl(folder.toUtf8())) {
     463                 :           4 :     return std::nullopt;
     464                 :             :   }
     465                 :             :   return folder;
     466                 :             : }
     467                 :             : } // namespace
     468                 :             : 
     469                 :             : namespace {
     470                 :             : 
     471                 :             : /// The digits of a generation line, or nothing when the line does not hold
     472                 :             : /// one ASCII decimal number of at most kMaxDigits digits and nothing else.
     473                 :         209 : auto generationDigits(const QByteArray &digits) -> std::optional<qint64> {
     474   [ +  +  +  + ]:         209 :   if (digits.isEmpty() || digits.size() > kMaxDigits) {
     475                 :           2 :     return std::nullopt;
     476                 :             :   }
     477         [ +  + ]:         503 :   for (const char c : digits) {
     478         [ +  + ]:         302 :     if (c < '0' || c > '9') {
     479                 :           6 :       return std::nullopt;
     480                 :             :     }
     481                 :             :   }
     482                 :         201 :   return digits.toLongLong();
     483                 :             : }
     484                 :             : 
     485                 :             : /// Takes one line of ours into @p generation or @p folder. Returns why it
     486                 :             : /// cannot be taken (a second line of the kind, a malformed one, an unknown
     487                 :             : /// kind), or an empty string when it was.
     488                 :         523 : auto takeHeaderLine(const QByteArray &line, std::optional<qint64> &generation,
     489                 :             :                     std::optional<QString> &folder,
     490                 :             :                     std::optional<QString> &store) -> QString {
     491         [ +  + ]:         523 :   if (line.startsWith(GpgIdGeneration::kStorePrefix)) {
     492         [ +  + ]:         107 :     if (store) {
     493                 :             :       //: The store ID line is the line of a signed recipient list (.gpg-id)
     494                 :             :       //: that names the password store by its ID. "Store" is the password
     495                 :             :       //: store, not a shop.
     496                 :             :       return QCoreApplication::translate(
     497                 :           1 :           "GpgIdGeneration", "The list carries more than one store ID line.");
     498                 :             :     }
     499                 :         106 :     const QByteArray value = line.mid(GpgIdGeneration::kStorePrefix.size());
     500         [ +  + ]:         106 :     if (isStoreId(value)) {
     501                 :         101 :       store = QString::fromLatin1(value);
     502                 :         101 :       return {};
     503                 :             :     }
     504                 :             :     //: The store ID line is the line of a signed recipient list (.gpg-id)
     505                 :             :     //: that names the password store by its ID. "Store" is the password
     506                 :             :     //: store, not a shop.
     507                 :          10 :     return QCoreApplication::translate("GpgIdGeneration",
     508                 :             :                                        "The store ID line is malformed: %1")
     509                 :          10 :         .arg(QString::fromUtf8(line));
     510                 :             :   }
     511         [ +  + ]:         416 :   if (line.startsWith(GpgIdGeneration::kGenerationPrefix)) {
     512         [ +  + ]:         210 :     if (generation) {
     513                 :             :       return QCoreApplication::translate(
     514                 :           1 :           "GpgIdGeneration", "The list carries more than one generation line.");
     515                 :             :     }
     516                 :             :     generation =
     517                 :         418 :         generationDigits(line.mid(GpgIdGeneration::kGenerationPrefix.size()));
     518         [ +  + ]:         209 :     if (generation) {
     519                 :         201 :       return {};
     520                 :             :     }
     521                 :          16 :     return QCoreApplication::translate("GpgIdGeneration",
     522                 :             :                                        "The generation line is malformed: %1")
     523                 :          16 :         .arg(QString::fromUtf8(line));
     524                 :             :   }
     525         [ +  + ]:         206 :   if (line.startsWith(GpgIdGeneration::kFolderPrefix)) {
     526         [ +  + ]:         203 :     if (folder) {
     527                 :             :       return QCoreApplication::translate(
     528                 :           1 :           "GpgIdGeneration", "The list carries more than one folder line.");
     529                 :             :     }
     530                 :         202 :     const QByteArray value = line.mid(GpgIdGeneration::kFolderPrefix.size());
     531                 :             :     // A control character (a second \r of "\r\r\n", a tab, a NUL) is not
     532                 :             :     // part of a folder name QtPass writes, and would not survive being
     533                 :             :     // written back: header() ends the line, parse() strips one \r.
     534                 :             :     // The name is the bytes signed, nothing else: QString::fromUtf8() drops
     535                 :             :     // a leading byte order mark and turns bytes that are not UTF-8 into
     536                 :             :     // U+FFFD, so a list signed for "\uFEFFfinance" or "fin\xFF" would read
     537                 :             :     // as bound to finance/ or to a folder really named "fin\uFFFD".
     538                 :         202 :     QStringDecoder utf8(QStringDecoder::Utf8,
     539                 :             :                         QStringDecoder::Flag::Stateless |
     540                 :             :                             QStringDecoder::Flag::ConvertInitialBom);
     541                 :         202 :     const QString name = utf8(value);
     542   [ +  +  +  +  :         596 :     if (!value.isEmpty() && !hasControl(value) && name.toUtf8() == value) {
                   +  + ]
     543                 :         195 :       folder = name;
     544                 :         195 :       return {};
     545                 :             :     }
     546                 :          14 :     return QCoreApplication::translate("GpgIdGeneration",
     547                 :             :                                        "The folder line is malformed: %1")
     548                 :          14 :         .arg(QString::fromUtf8(line));
     549                 :             :   }
     550                 :           6 :   return QCoreApplication::translate("GpgIdGeneration",
     551                 :             :                                      "The header line is malformed: %1")
     552                 :           6 :       .arg(QString::fromUtf8(line));
     553                 :             : }
     554                 :             : 
     555                 :             : } // namespace
     556                 :             : 
     557                 :         229 : auto GpgIdGeneration::parse(const QByteArray &contents, QString *error)
     558                 :             :     -> std::optional<Header> {
     559                 :         229 :   std::optional<qint64> generation;
     560                 :         229 :   std::optional<QString> folder;
     561                 :         229 :   std::optional<QString> store;
     562   [ +  +  +  + ]:        1415 :   for (const QByteArray &rawLine : contents.split('\n')) {
     563                 :             :     QByteArray line = rawLine;
     564                 :             :     if (line.endsWith('\r')) {
     565                 :           3 :       line.chop(1);
     566                 :             :     }
     567                 :             :     // Only a line under our name is ours; any other comment is somebody
     568                 :             :     // else's. But a near miss under the same name is suspicious, not
     569                 :             :     // ignorable.
     570         [ +  + ]:         983 :     if (!line.startsWith(kOurComment)) {
     571                 :         460 :       continue;
     572                 :             :     }
     573                 :         523 :     const QString complaint = takeHeaderLine(line, generation, folder, store);
     574         [ +  + ]:         523 :     if (complaint.isEmpty()) {
     575                 :             :       continue;
     576                 :             :     }
     577         [ +  - ]:          26 :     if (error)
     578                 :          26 :       *error = complaint;
     579                 :          26 :     return std::nullopt;
     580                 :             :   }
     581   [ +  +  +  + ]:         203 :   if (generation && !folder) {
     582         [ +  - ]:           1 :     if (error)
     583                 :           1 :       *error = tr("The list carries a generation line but no folder line.");
     584                 :           1 :     return std::nullopt;
     585                 :             :   }
     586                 :             :   // QtPass writes the store line only with the other two.
     587   [ +  +  +  + ]:         202 :   if (store && !generation) {
     588         [ +  - ]:           1 :     if (error)
     589                 :             :       //: The store ID line names the password store by its ID; see the
     590                 :             :       //: other store ID line messages.
     591                 :           1 :       *error = tr("The list carries a store ID line but no generation line.");
     592                 :           1 :     return std::nullopt;
     593                 :             :   }
     594                 :         201 :   Header header;
     595                 :         201 :   header.generation = generation.value_or(0);
     596                 :             :   header.folder = std::move(folder);
     597                 :             :   header.store = std::move(store);
     598                 :             :   return header;
     599                 :             : }
     600                 :             : 
     601                 :         123 : auto GpgIdGeneration::header(qint64 generation, const QString &folder,
     602                 :             :                              const QString &store) -> QByteArray {
     603                 :         246 :   QByteArray lines = kGenerationPrefix + QByteArray::number(generation) + '\n' +
     604                 :         246 :                      kFolderPrefix + folder.toUtf8() + '\n';
     605         [ +  + ]:         123 :   if (!store.isEmpty()) {
     606                 :          96 :     lines += kStorePrefix + store.toLatin1() + '\n';
     607                 :             :   }
     608                 :         123 :   return lines;
     609                 :             : }
     610                 :             : 
     611                 :         123 : auto GpgIdGeneration::withHeader(qint64 generation, const QString &folder,
     612                 :             :                                  const QByteArray &recipients,
     613                 :             :                                  const QString &store) -> QByteArray {
     614                 :         246 :   return header(generation, folder, store) + recipients;
     615                 :             : }
     616                 :             : 
     617                 :         170 : auto GpgIdGeneration::folderOf(const QString &gpgIdFile,
     618                 :             :                                const QString &storeRoot)
     619                 :             :     -> std::optional<QString> {
     620                 :         170 :   return relativeFolder(gpgIdFile, storeRoot);
     621                 :             : }
     622                 :             : 
     623                 :        1194 : auto GpgIdGeneration::key(const QString &gpgIdFile) -> QString {
     624                 :        1194 :   const QFileInfo info(gpgIdFile);
     625                 :             :   // canonicalFilePath() is empty for a file that does not exist (a new
     626                 :             :   // profile's list, or one whose folder was removed with it): canonicalise
     627                 :             :   // the nearest folder that does exist and append the rest, so that the
     628                 :             :   // key is the one the list had while it was there.
     629                 :        1194 :   QString canonical = info.canonicalFilePath();
     630         [ +  + ]:        1194 :   if (canonical.isEmpty()) {
     631                 :         506 :     QString existing = QDir::cleanPath(info.absolutePath());
     632                 :         506 :     QString rest = info.fileName();
     633   [ +  +  +  + ]:         520 :     while (!QFileInfo(existing).isDir()) {
     634                 :          14 :       const QFileInfo up(existing);
     635                 :          28 :       const QString parent = QDir::cleanPath(up.absolutePath());
     636         [ +  - ]:          14 :       if (parent == existing) {
     637                 :             :         break;
     638                 :             :       }
     639                 :          14 :       rest = up.fileName() + QLatin1Char('/') + rest;
     640                 :          14 :       existing = parent;
     641                 :          14 :     }
     642                 :         506 :     QString dir = QDir(existing).canonicalPath();
     643         [ -  + ]:         506 :     if (dir.isEmpty()) {
     644                 :             :       dir = std::move(existing);
     645                 :             :     }
     646                 :        1012 :     canonical = QDir::cleanPath(dir + QLatin1Char('/') + rest);
     647                 :             :   }
     648                 :        2388 :   canonical = QDir::fromNativeSeparators(canonical);
     649                 :             : #ifdef Q_OS_WIN
     650                 :             :   canonical = canonical.toLower();
     651                 :             : #endif
     652                 :             :   return QString::fromLatin1(
     653                 :        1194 :       QCryptographicHash::hash(canonical.toUtf8(), QCryptographicHash::Sha256)
     654                 :        3582 :           .toHex());
     655                 :        1194 : }
     656                 :             : 
     657                 :         805 : auto GpgIdGeneration::recordFile() -> QString { return recordPath(); }
     658                 :             : 
     659                 :           1 : auto GpgIdGeneration::storeRecordFile() -> QString { return storesPath(); }
     660                 :             : 
     661                 :         160 : auto GpgIdGeneration::digest(const QByteArray &contents) -> QString {
     662                 :             :   return QString::fromLatin1(
     663                 :         320 :       QCryptographicHash::hash(contents, QCryptographicHash::Sha256).toHex());
     664                 :             : }
     665                 :             : 
     666                 :          16 : auto GpgIdGeneration::remembered(const QString &gpgIdFile, QString *error)
     667                 :             :     -> std::optional<qint64> {
     668                 :          16 :   Transaction t;
     669         [ +  + ]:          16 :   if (!t.ok(error)) {
     670                 :           2 :     return std::nullopt;
     671                 :             :   }
     672                 :          14 :   return t.generation(key(gpgIdFile));
     673                 :          16 : }
     674                 :             : 
     675                 :         439 : auto GpgIdGeneration::seen(const QString &gpgIdFile, QString *error)
     676                 :             :     -> std::optional<bool> {
     677                 :         439 :   Transaction t;
     678         [ +  + ]:         439 :   if (!t.ok(error)) {
     679                 :           1 :     return std::nullopt;
     680                 :             :   }
     681                 :         438 :   return t.known(key(gpgIdFile));
     682                 :         439 : }
     683                 :             : 
     684                 :         141 : auto GpgIdGeneration::boundToItsFolder(const QString &gpgIdFile,
     685                 :             :                                        const Header &header,
     686                 :             :                                        const QString &storeRoot, QString *error)
     687                 :             :     -> bool {
     688         [ +  + ]:         141 :   if (!header.folder) {
     689                 :             :     return true;
     690                 :             :   }
     691                 :         132 :   const std::optional<QString> here = folderOf(gpgIdFile, storeRoot);
     692   [ +  +  +  + ]:         132 :   if (here && *here == *header.folder) {
     693                 :             :     return true;
     694                 :             :   }
     695         [ +  + ]:           9 :   if (error)
     696                 :             :     *error =
     697                 :           7 :         tr("The signed recipient list %1 was written for the folder "
     698                 :             :            "\"%2\" of the store, not for \"%3\", and is not used. It "
     699                 :             :            "may have been copied here by someone else; if the folder "
     700                 :             :            "was moved or renamed instead, a holder of the signing key "
     701                 :             :            "opens Users on it and saves the recipients, which binds "
     702                 :             :            "the list to where it is now.")
     703                 :          14 :             .arg(gpgIdFile, *header.folder, here.value_or(QStringLiteral("?")));
     704                 :             :   return false;
     705                 :             : }
     706                 :             : 
     707                 :          28 : auto GpgIdGeneration::wayThrough(qint64 last, const QString &recordPath,
     708                 :             :                                  const QString &saving) -> QString {
     709         [ +  + ]:          28 :   if (last >= kMaxGeneration) {
     710                 :           2 :     return tr("Generation %1 is the highest there is, so no newer list "
     711                 :             :               "can be written here: removing %2 forgets what this device "
     712                 :             :               "accepted before, after which a holder of the signing key "
     713                 :             :               "gets through by opening Users and %3.")
     714                 :           4 :         .arg(last)
     715                 :           2 :         .arg(recordPath, saving);
     716                 :             :   }
     717                 :          26 :   return tr("A holder of the signing key gets through by opening Users "
     718                 :             :             "and %1, which writes generation %2. Removing %3 forgets what "
     719                 :             :             "this device accepted before.")
     720                 :          52 :       .arg(saving)
     721                 :          78 :       .arg(last + 1)
     722                 :          26 :       .arg(recordPath);
     723                 :             : }
     724                 :             : 
     725                 :          21 : auto GpgIdGeneration::staleList(const QString &gpgIdFile, const Header &header,
     726                 :             :                                 qint64 last, const QString &recordPath,
     727                 :             :                                 QString *error) -> Verdict {
     728         [ +  + ]:          21 :   if (!header.folder) {
     729                 :             :     // Below what was accepted here and with no folder line to say it was
     730                 :             :     // written here at all: an authentic headerless pair from any folder's
     731                 :             :     // history would pass as this folder's rollback otherwise.
     732         [ +  - ]:           3 :     if (error)
     733                 :             :       *error =
     734                 :           3 :           tr("The signed recipient list %1 carries no generation line, "
     735                 :             :              "while generation %2 was accepted here before. pass writes no "
     736                 :             :              "generation line (also through QtPass's pass backend), nor did "
     737                 :             :              "QtPass before 2.0; without one the list may also have been "
     738                 :             :              "written for another folder of the store and copied here. %3")
     739                 :           6 :               .arg(gpgIdFile)
     740                 :           6 :               .arg(last)
     741                 :           9 :               .arg(
     742                 :           3 :                   wayThrough(last, recordPath,
     743                 :           3 :                              tr("selecting the recipients afresh and saving")));
     744                 :           3 :     return Verdict::Unbound;
     745                 :             :   }
     746         [ +  + ]:          18 :   if (error)
     747                 :             :     *error =
     748                 :          17 :         tr("The signed recipient list %1 is generation %2, older than "
     749                 :             :            "generation %3, the last one QtPass accepted here. It may have "
     750                 :             :            "been put back by someone else. %4")
     751                 :          34 :             .arg(gpgIdFile)
     752                 :          34 :             .arg(header.generation)
     753                 :          34 :             .arg(last)
     754                 :          34 :             .arg(wayThrough(last, recordPath,
     755                 :          17 :                             tr("saving the recipients: the preselected "
     756                 :             :                                "recipients there are this list's, so remove "
     757                 :             :                                "anyone who should no longer have access "
     758                 :             :                                "first")));
     759                 :             :   return Verdict::Rollback;
     760                 :             : }
     761                 :             : 
     762                 :         144 : auto GpgIdGeneration::accept(const QString &gpgIdFile,
     763                 :             :                              const QByteArray &contents,
     764                 :             :                              const QString &storeRoot, QString *error)
     765                 :             :     -> Verdict {
     766                 :         144 :   QString why;
     767                 :         144 :   const std::optional<Header> header = parse(contents, &why);
     768         [ +  + ]:         144 :   if (!header) {
     769         [ +  + ]:           3 :     if (error)
     770                 :           2 :       *error = tr("The signed recipient list %1 is not one to trust: %2")
     771                 :           4 :                    .arg(gpgIdFile, why);
     772                 :           3 :     return Verdict::Malformed;
     773                 :             :   }
     774                 :             :   // A pair is only valid where it was written for: copied into another
     775                 :             :   // folder it is a rollback in disguise (that folder's first list).
     776      [ +  +  + ]:         141 :   if (!boundToItsFolder(gpgIdFile, *header, storeRoot, error)) {
     777                 :             :     return Verdict::WrongFolder;
     778                 :             :   }
     779                 :         132 :   return acceptAgainstRecord(gpgIdFile, *header, contents, storeRoot, error);
     780                 :             : }
     781                 :             : 
     782                 :         132 : auto GpgIdGeneration::acceptAgainstRecord(const QString &gpgIdFile,
     783                 :             :                                           const Header &header,
     784                 :             :                                           const QByteArray &contents,
     785                 :             :                                           const QString &storeRoot,
     786                 :             :                                           QString *error) -> Verdict {
     787                 :         132 :   Transaction t;
     788         [ +  + ]:         132 :   if (!t.ok(error)) {
     789                 :             :     return Verdict::RecordUnavailable;
     790                 :             :   }
     791                 :         126 :   const QString k = key(gpgIdFile);
     792                 :         126 :   const qint64 last = t.generation(k);
     793                 :         126 :   const qint64 generation = header.generation;
     794                 :         126 :   const QString bytes = digest(contents);
     795                 :             :   // Before anything that could preselect the list's recipients (a rollback
     796                 :             :   // is recovered through the Users dialog): a list of another store is no
     797                 :             :   // history of this one.
     798                 :         126 :   const QString storeKey = key(storeRoot);
     799                 :         126 :   const std::optional<QString> pinned = t.store(storeKey);
     800   [ +  +  +  + ]:         171 :   if (pinned &&
     801                 :          45 :       !ofThisStore(gpgIdFile, header, *pinned, t.accepted(k, generation, bytes),
     802                 :             :                    t.storesFile, error)) {
     803                 :             :     return Verdict::WrongStore;
     804                 :             :   }
     805         [ +  + ]:         121 :   if (generation < last) {
     806                 :          21 :     return staleList(gpgIdFile, header, last, t.path, error);
     807                 :             :   }
     808         [ +  + ]:         100 :   if (generation == 0) {
     809                 :             :     // pass writes headerless lists on every change, so differing bytes here
     810                 :             :     // are normal, not a conflict. Generation 0 has no freshness to keep
     811                 :             :     // (SECURITY.md). Still noted, once, so that a removal of the list is
     812                 :             :     // told apart from a folder that never had one (Pass::skippedGpgId()).
     813      [ +  -  + ]:           6 :     if (!t.noteOnce(k, error)) {
     814                 :             :       return Verdict::RecordUnavailable;
     815                 :             :     }
     816                 :             :     // First sight of the store's id, on a list that is otherwise accepted.
     817                 :           6 :     return t.pinOnFirstSight(storeKey, header.store, error)
     818         [ -  + ]:           6 :                ? Verdict::Accepted
     819                 :             :                : Verdict::RecordUnavailable;
     820                 :             :   }
     821         [ +  + ]:          94 :   if (generation == last) {
     822                 :             :     // Same generation, different bytes: two devices both made 19 from 18
     823                 :             :     // (Git's conflict), or a swap. A record without a digest (an unrecorded
     824                 :             :     // reservation) takes these bytes as the ones.
     825                 :          58 :     const std::optional<QString> known = t.digest(k);
     826         [ +  + ]:          58 :     if (known) {
     827         [ +  + ]:          55 :       if (*known != bytes) {
     828                 :          13 :         return conflictingList(gpgIdFile, generation, last, t.path, error);
     829                 :             :       }
     830                 :          42 :       return t.pinOnFirstSight(storeKey, header.store, error)
     831         [ -  + ]:          42 :                  ? Verdict::Accepted
     832                 :             :                  : Verdict::RecordUnavailable;
     833                 :             :     }
     834                 :             :   }
     835                 :             :   // The pin first: a generation recorded with the pin's write failing would
     836                 :             :   // leave the store unpinned for the next list, another store's included.
     837   [ +  +  -  +  :          78 :   if (!t.pinOnFirstSight(storeKey, header.store, error) ||
                      - ]
     838                 :          39 :       !t.remember(k, generation, bytes, error)) {
     839                 :           0 :     return Verdict::RecordUnavailable;
     840                 :             :   }
     841                 :             :   return Verdict::Accepted;
     842                 :         132 : }
     843                 :             : 
     844                 :          13 : auto GpgIdGeneration::conflictingList(const QString &gpgIdFile,
     845                 :             :                                       qint64 generation, qint64 last,
     846                 :             :                                       const QString &recordPath, QString *error)
     847                 :             :     -> Verdict {
     848         [ +  + ]:          13 :   if (error)
     849                 :           8 :     *error = tr("The signed recipient list %1 is generation %2, the same "
     850                 :             :                 "generation as a different list this device accepted "
     851                 :             :                 "before. Either two devices saved recipients at the same "
     852                 :             :                 "time (Git will have shown the conflict), or an authentic "
     853                 :             :                 "list of that generation was swapped in. %3")
     854                 :          16 :                  .arg(gpgIdFile)
     855                 :          16 :                  .arg(generation)
     856                 :          16 :                  .arg(wayThrough(last, recordPath,
     857                 :           8 :                                  tr("checking the recipients and saving")));
     858                 :          13 :   return Verdict::Conflict;
     859                 :             : }
     860                 :             : 
     861                 :          45 : auto GpgIdGeneration::ofThisStore(const QString &gpgIdFile,
     862                 :             :                                   const Header &header, const QString &pinned,
     863                 :             :                                   bool alreadyAccepted,
     864                 :             :                                   const QString &recordPath, QString *error)
     865                 :             :     -> bool {
     866         [ +  + ]:          45 :   if (header.store) {
     867         [ +  + ]:          42 :     if (*header.store == pinned) {
     868                 :             :       return true;
     869                 :             :     }
     870         [ +  + ]:           4 :     if (error)
     871                 :             :       *error =
     872                 :           2 :           tr("The signed recipient list %1 was written for another password "
     873                 :             :              "store (store ID %2; this device knows this store as %3) and is "
     874                 :             :              "not used. It may have been copied here from a store signed "
     875                 :             :              "with the same key. If this store was set up again instead, "
     876                 :             :              "removing %4 forgets the store IDs this device knows.")
     877                 :           4 :               .arg(gpgIdFile, *header.store, pinned, recordPath);
     878                 :           4 :     return false;
     879                 :             :   }
     880                 :             :   // No store line: a list without a generation (pass) has none to carry,
     881                 :             :   // and one this device accepted before it had a store id still is what it
     882                 :             :   // was. Anything new must say which store it is for.
     883   [ +  +  +  + ]:           3 :   if (header.generation == 0 || alreadyAccepted) {
     884                 :             :     return true;
     885                 :             :   }
     886         [ -  + ]:           1 :   if (error)
     887                 :             :     *error =
     888                 :             :         //: The store ID line is the line of a signed recipient list that
     889                 :             :         //: names the password store by its ID (%2 here).
     890                 :           1 :         tr("The signed recipient list %1 carries no store ID line, while this "
     891                 :             :            "device knows this store by its ID %2: it may have been written "
     892                 :             :            "for another store and copied here, or by an older QtPass. A "
     893                 :             :            "holder of the signing key gets through by opening Users, "
     894                 :             :            "selecting the recipients afresh and saving, which writes the "
     895                 :             :            "store ID line.")
     896                 :           2 :             .arg(gpgIdFile, pinned);
     897                 :             :   return false;
     898                 :             : }
     899                 :             : 
     900                 :          47 : auto GpgIdGeneration::storeIdFor(const QString &storeRoot,
     901                 :             :                                  const std::optional<QString> &onDisk,
     902                 :             :                                  QString *error) -> std::optional<QString> {
     903                 :          47 :   Transaction t;
     904         [ +  + ]:          47 :   if (!t.ok(error)) {
     905                 :           1 :     return std::nullopt;
     906                 :             :   }
     907                 :          46 :   const QString storeKey = key(storeRoot);
     908         [ +  + ]:          46 :   if (const std::optional<QString> pinned = t.store(storeKey)) {
     909                 :             :     return pinned;
     910                 :             :   }
     911                 :             :   // Joining a store that has an id already: take it over, rather than
     912                 :             :   // giving the store a second one every other device would refuse.
     913         [ +  + ]:           2 :   QString id = onDisk && isStoreId(onDisk->toLatin1())
     914         [ +  + ]:          27 :                    ? *onDisk
     915                 :          53 :                    : QUuid::createUuid().toString(QUuid::Id128).toLower();
     916      [ +  -  + ]:          27 :   if (!t.pinStore(storeKey, id, error)) {
     917                 :           0 :     return std::nullopt;
     918                 :             :   }
     919                 :             :   return id;
     920                 :          47 : }
     921                 :             : 
     922                 :          49 : auto GpgIdGeneration::reserveNext(const QString &gpgIdFile,
     923                 :             :                                   std::optional<qint64> verifiedOnDisk,
     924                 :             :                                   QString *error) -> std::optional<qint64> {
     925                 :          49 :   Transaction t;
     926         [ +  + ]:          49 :   if (!t.ok(error)) {
     927                 :           2 :     return std::nullopt;
     928                 :             :   }
     929                 :          47 :   const QString k = key(gpgIdFile);
     930                 :          47 :   const qint64 last = t.generation(k);
     931                 :             :   const qint64 base = qMax(last, verifiedOnDisk.value_or(0));
     932         [ +  + ]:          47 :   if (base >= kMaxGeneration) {
     933         [ +  - ]:           2 :     if (error)
     934                 :           2 :       *error = tr("The recipient list %1 has reached generation %2, the "
     935                 :             :                   "highest there is; the list cannot be written.")
     936                 :           4 :                    .arg(gpgIdFile)
     937                 :           6 :                    .arg(base);
     938                 :           2 :     return std::nullopt;
     939                 :             :   }
     940                 :          45 :   const qint64 generation = base + 1;
     941                 :             :   // No digest until the bytes are written: the previous generation's must
     942                 :             :   // not pass for this one's.
     943      [ +  -  + ]:          90 :   if (!t.remember(k, generation, QString(), error)) {
     944                 :           0 :     return std::nullopt;
     945                 :             :   }
     946                 :          45 :   return generation;
     947                 :          49 : }
     948                 :             : 
     949                 :          35 : auto GpgIdGeneration::recordWritten(const QString &gpgIdFile,
     950                 :             :                                     const QByteArray &contents, QString *error)
     951                 :             :     -> bool {
     952                 :          35 :   const std::optional<Header> header = parse(contents, error);
     953         [ +  - ]:          35 :   if (!header) {
     954                 :             :     return false;
     955                 :             :   }
     956                 :          35 :   Transaction t;
     957         [ +  - ]:          35 :   if (!t.ok(error)) {
     958                 :             :     return false;
     959                 :             :   }
     960                 :          35 :   const QString k = key(gpgIdFile);
     961                 :          35 :   const qint64 last = t.generation(k);
     962         [ +  + ]:          35 :   if (header->generation != last) {
     963                 :             :     // Not the generation reserved last: something else moved the record in
     964                 :             :     // between; whatever is there is not overwritten with these bytes.
     965         [ +  - ]:           1 :     if (error)
     966                 :           1 :       *error = tr("The generation record of the recipient lists, %1, has "
     967                 :             :                   "moved on to generation %2 while generation %3 was being "
     968                 :             :                   "written.")
     969                 :           2 :                    .arg(t.path)
     970                 :           2 :                    .arg(last)
     971                 :           3 :                    .arg(header->generation);
     972                 :           1 :     return false;
     973                 :             :   }
     974                 :          68 :   return t.remember(k, last, digest(contents), error);
     975                 :          35 : }
        

Generated by: LCOV version 2.0-1