QtPass Developer documentation
QtPass test coverage
Current view: top level - src/templateio.cpp (source / functions) Coverage Total Hit
Test: QtPass Lines: 100.0 % 107 107
Test Date: 2026-12-03 23:34:20 Functions: 100.0 % 11 11
Branches: 87.7 % 106 93

             Branch data     Line data    Source code
       1                 :             : // SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
       2                 :             : // SPDX-License-Identifier: GPL-3.0-or-later
       3                 :             : /**
       4                 :             :  * @file
       5                 :             :  * @brief Implements TemplateIO; template files are read through
       6                 :             :  * readTemplateFile(), which refuses anything but a small regular file.
       7                 :             :  */
       8                 :             : #include "templateio.h"
       9                 :             : #include "filecontent.h"
      10                 :             : #include "util.h"
      11                 :             : 
      12                 :             : #include <QDebug>
      13                 :             : #include <QDir>
      14                 :             : #include <QFile>
      15                 :             : #include <QRegularExpression>
      16                 :             : #include <QSaveFile>
      17                 :             : #include <QStringConverter>
      18                 :             : #include <QTextStream>
      19                 :             : #include <algorithm>
      20                 :             : #include <optional>
      21                 :             : #include <utility>
      22                 :             : 
      23                 :             : namespace {
      24                 :             : 
      25                 :             : /// The template files are a few lines each; anything larger is not one.
      26                 :             : constexpr qint64 kMaxTemplateFileBytes = qint64{64} * 1024;
      27                 :             : 
      28                 :             : /**
      29                 :             :  * Reads a template file of the store. Store contents are written by whoever
      30                 :             :  * shares the store, so it has to be the regular file it claims to be (not a
      31                 :             :  * link to a device or a FIFO, which would never end) and of a template
      32                 :             :  * file's size, as read from the open handle: a file that grows after the
      33                 :             :  * open is cut off at the limit there, not read on.
      34                 :             :  * @return The contents, or nothing when the file is absent, not a regular
      35                 :             :  *         file or too large.
      36                 :             :  */
      37                 :          31 : auto readTemplateFile(const QString &path) -> std::optional<QString> {
      38                 :          31 :   QFile file;
      39      [ +  +  + ]:          31 :   if (!Util::openRegularFile(path, file)) {
      40                 :          14 :     return std::nullopt;
      41                 :             :   }
      42                 :          17 :   const QByteArray bytes = file.read(kMaxTemplateFileBytes + 1);
      43         [ +  + ]:          17 :   if (bytes.size() > kMaxTemplateFileBytes) {
      44                 :           2 :     qWarning() << "Ignoring" << path << "; a template file is at most"
      45                 :           1 :                << kMaxTemplateFileBytes << "bytes";
      46                 :           1 :     return std::nullopt;
      47                 :             :   }
      48                 :             :   // QTextStream skipped a UTF-8 byte order mark (older Notepad writes one);
      49                 :             :   // fromUtf8() keeps it as U+FEFF, which trimmed() leaves in place.
      50                 :          16 :   const QByteArray bom("\xEF\xBB\xBF");
      51      [ +  +  + ]:          32 :   return QString::fromUtf8(bytes.startsWith(bom) ? bytes.mid(bom.size())
      52                 :             :                                                  : bytes);
      53                 :          31 : }
      54                 :             : 
      55                 :             : /// The name of a `[section]` header line; nothing for any other line, and
      56                 :             : /// an empty name for `[]`.
      57                 :          48 : auto sectionHeader(const QString &line) -> std::optional<QString> {
      58   [ +  +  -  + ]:          48 :   if (!line.startsWith('[') || !line.endsWith(']')) {
      59                 :          36 :     return std::nullopt;
      60                 :             :   }
      61                 :          24 :   return line.mid(1, line.length() - 2).trimmed();
      62                 :             : }
      63                 :             : 
      64                 :             : /// The first line of @p dir's .default_template, when it names a template.
      65                 :          15 : auto defaultTemplateIn(const QDir &dir) -> QString {
      66                 :             :   const std::optional<QString> contents =
      67                 :          30 :       readTemplateFile(dir.filePath(".default_template"));
      68         [ +  + ]:          15 :   if (!contents) {
      69                 :          10 :     return {};
      70                 :             :   }
      71                 :           5 :   const QString name = contents->section(QLatin1Char('\n'), 0, 0).trimmed();
      72      [ +  +  + ]:           9 :   return name.startsWith('#') ? QString() : name;
      73                 :             : }
      74                 :             : 
      75                 :             : } // namespace
      76                 :             : 
      77                 :          10 : auto TemplateIO::readTemplates(const QString &storePath)
      78                 :             :     -> QHash<QString, QStringList> {
      79                 :          10 :   QHash<QString, QStringList> result;
      80                 :             :   std::optional<QString> contents =
      81                 :          20 :       readTemplateFile(QDir(storePath).filePath(".templates"));
      82         [ +  + ]:          10 :   if (!contents) {
      83                 :             :     return result;
      84                 :             :   }
      85                 :           8 :   QTextStream in(&*contents, QIODevice::ReadOnly);
      86                 :             :   // No section before the first header, nor for an empty `[]`: fields there
      87                 :             :   // belong to nothing and are dropped.
      88                 :           8 :   std::optional<QString> section;
      89                 :           8 :   QStringList fields;
      90                 :          20 :   const auto flush = [&] {
      91         [ +  + ]:          20 :     if (section) {
      92                 :          11 :       result.insert(*section, fields);
      93                 :             :     }
      94                 :          20 :     fields.clear();
      95                 :          28 :   };
      96      [ +  +  + ]:          56 :   while (!in.atEnd()) {
      97                 :          48 :     const QString line = in.readLine().trimmed();
      98      [ +  +  + ]:          48 :     if (const std::optional<QString> header = sectionHeader(line)) {
      99                 :          12 :       flush();
     100   [ +  +  +  + ]:          24 :       section = header->isEmpty() ? std::nullopt : header;
     101         [ +  + ]:          12 :       if (!section) {
     102                 :           2 :         qWarning()
     103                 :           1 :             << "Empty template section in .templates file, ignoring fields";
     104                 :             :       }
     105   [ +  +  +  +  :          36 :     } else if (section && !line.isEmpty() && !line.startsWith('#')) {
             +  +  +  + ]
     106                 :             :       fields.append(line);
     107                 :             :     }
     108                 :             :   }
     109                 :           8 :   flush();
     110                 :             :   return result;
     111                 :           8 : }
     112                 :             : 
     113                 :           9 : auto TemplateIO::secretFieldsIn(const QString &templateText) -> QStringList {
     114                 :             :   static const QRegularExpression marker(
     115                 :           2 :       QStringLiteral("^#\\s*secret\\s*:(.*)$"),
     116   [ +  +  +  -  :          11 :       QRegularExpression::CaseInsensitiveOption);
                      + ]
     117                 :           9 :   QStringList names;
     118                 :           9 :   const QStringList lines = templateText.split(QLatin1Char('\n'));
     119         [ +  + ]:          47 :   for (const QString &line : lines) {
     120                 :          38 :     const QRegularExpressionMatch match = marker.match(line.trimmed());
     121      [ +  +  + ]:          38 :     if (!match.hasMatch()) {
     122                 :             :       continue;
     123                 :             :     }
     124                 :          11 :     const QStringList listed = match.captured(1).split(QLatin1Char(','));
     125         [ +  + ]:          26 :     for (const QString &name : listed) {
     126                 :             :       const QString trimmed = name.trimmed();
     127         [ +  + ]:          15 :       if (!trimmed.isEmpty()) {
     128                 :             :         names << trimmed;
     129                 :             :       }
     130                 :             :     }
     131                 :          38 :   }
     132                 :           9 :   return names;
     133                 :             : }
     134                 :             : 
     135                 :           6 : auto TemplateIO::readSecretFields(const QString &storePath) -> QStringList {
     136                 :             :   const std::optional<QString> contents =
     137                 :          12 :       readTemplateFile(QDir(storePath).filePath(".templates"));
     138      [ +  +  + ]:          12 :   return contents ? secretFieldsIn(*contents) : QStringList();
     139                 :             : }
     140                 :             : 
     141                 :         161 : auto TemplateIO::fieldsIn(const QString &templateText) -> QStringList {
     142                 :             :   // Every field becomes a row of widgets in the password dialog, built with
     143                 :             :   // a focus chain that grows quadratically: a store's 64 KiB .templates of
     144                 :             :   // one-letter lines froze Add password for half a minute. A template gets
     145                 :             :   // as many fields as an entry may have.
     146                 :         161 :   QStringList fields;
     147                 :             :   int named = 0;
     148                 :         161 :   const QStringList lines = templateText.split(QLatin1Char('\n'));
     149         [ +  + ]:        4349 :   for (const QString &line : lines) {
     150      [ +  +  + ]:        4190 :     if (line.trimmed().startsWith(QLatin1Char('#'))) {
     151                 :           8 :       continue;
     152                 :             :     }
     153                 :             :     // Counted as setTemplate() builds rows: for every line not empty, a
     154                 :             :     // line of blanks too.
     155         [ +  + ]:        4182 :     if (!line.isEmpty()) {
     156         [ +  + ]:        3090 :       if (named == FileContent::kMaxNamedFields) {
     157                 :           4 :         qWarning() << "Template has more than" << FileContent::kMaxNamedFields
     158                 :           2 :                    << "fields; ignoring the rest";
     159                 :           2 :         break;
     160                 :             :       }
     161                 :        3088 :       ++named;
     162                 :             :     }
     163                 :             :     fields.append(line);
     164                 :             :   }
     165                 :         161 :   return fields;
     166                 :             : }
     167                 :             : 
     168                 :           3 : auto TemplateIO::writeTemplates(const QString &storePath,
     169                 :             :                                 const QHash<QString, QStringList> &templates)
     170                 :             :     -> bool {
     171                 :           6 :   QSaveFile saveFile(QDir(storePath).filePath(".templates"));
     172      [ +  +  - ]:           3 :   if (!saveFile.open(QIODevice::WriteOnly | QIODevice::Text)) {
     173                 :             :     return false;
     174                 :             :   }
     175                 :           3 :   QTextStream out(&saveFile);
     176                 :           3 :   out.setEncoding(QStringConverter::Utf8);
     177                 :           3 :   out << "# QtPass templates configuration\n";
     178                 :           3 :   out << "# Format: INI-style with [template_name] sections,\n";
     179                 :           3 :   out << "# followed by field names (one per line)\n\n";
     180                 :             : 
     181                 :           3 :   QStringList sortedKeys = templates.keys();
     182                 :           6 :   std::sort(sortedKeys.begin(), sortedKeys.end());
     183         [ +  + ]:           7 :   for (const QString &key : std::as_const(sortedKeys)) {
     184                 :           4 :     out << "[" << key << "]\n";
     185      [ +  +  + ]:          14 :     for (const QString &field : templates.value(key)) {
     186                 :           6 :       out << field << "\n";
     187                 :             :     }
     188                 :           4 :     out << "\n";
     189                 :             :   }
     190                 :           3 :   out.flush();
     191      [ +  +  - ]:           3 :   if (out.status() != QTextStream::Ok) {
     192                 :             :     return false;
     193                 :             :   }
     194                 :           3 :   return saveFile.commit();
     195                 :           3 : }
     196                 :             : 
     197                 :           9 : auto TemplateIO::getFolderTemplate(const QString &folderPath,
     198                 :             :                                    const QString &storePath) -> QString {
     199                 :          18 :   const QString store = QDir::cleanPath(QDir(storePath).absolutePath());
     200                 :             :   // Only the store root and its descendants are probed for
     201                 :             :   // .default_template; a path outside the store opens nothing.
     202                 :          15 :   const auto inStore = [&store](const QString &path) {
     203   [ +  +  +  - ]:          25 :     return path == store ||
     204   [ +  -  +  - ]:          20 :            (path.startsWith(store) && path.length() > store.length() &&
     205                 :          15 :             path.at(store.length()) == QChar('/'));
     206                 :           9 :   };
     207                 :           9 :   QDir dir(folderPath);
     208   [ +  +  +  +  :          30 :   while (inStore(QDir::cleanPath(dir.absolutePath()))) {
                      - ]
     209                 :          15 :     const QString name = defaultTemplateIn(dir);
     210         [ +  + ]:          15 :     if (!name.isEmpty()) {
     211                 :             :       return name;
     212                 :             :     }
     213   [ +  +  +  +  :          22 :     if (QDir::cleanPath(dir.absolutePath()) == store || !dir.cdUp()) {
          +  -  +  +  +  
             -  -  -  - ]
     214                 :             :       break;
     215                 :             :     }
     216                 :             :   }
     217                 :           5 :   return {};
     218                 :           9 : }
        

Generated by: LCOV version 2.0-1