• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IJHack / QtPass / 44267478585

18 Nov 2026 08:29AM UTC coverage: 96.338% (+0.06%) from 96.28%
44267478585

Pull #2261

github

web-flow
Merge 8e91fa749 into ba6b598d3
Pull Request #2261: Git set-up refuses a FIFO and times out; a half-done pull stops re-encryption

58 of 62 new or added lines in 2 files covered. (93.55%)

4 existing lines in 2 files now uncovered.

9156 of 9504 relevant lines covered (96.34%)

1287.43 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.44
/src/profileinit.cpp
1
// SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
/**
4
 * @file
5
 * @brief Implements ProfileInit; the environments its gpg and git processes
6
 * run in are built by withGpgHome() and gitEnvironment() here.
7
 */
8
#include "profileinit.h"
9
#include "appsettings.h"
10
#include "executor.h"
11
#include "gpgidgeneration.h"
12
#include "gpgidsigner.h"
13
#include "qtpasslogging.h"
14
#include "userinfo.h"
15
#include "util.h"
16
#include <QDir>
17
#include <QElapsedTimer>
18
#include <QFile>
19
#include <QFileInfo>
20
#include <QProcess>
21
#include <QSet>
22
#include <algorithm>
23

24
namespace {
25
/// @p env with the configured GPG home applied as Pass::init() applies it:
26
/// GNUPGHOME is that folder when it exists; otherwise the inherited one
27
/// stays. The new store's .gpg-id is signed, and a signed commit made, with
28
/// the keyring QtPass uses everywhere else, where the signing key may be
29
/// the only place it is.
30
auto withGpgHome(QProcessEnvironment env, const AppSettings &s)
279 ✔
31
    -> QProcessEnvironment {
32
  if (!s.gpgHome.isEmpty()) {
279 ✔
33
    QDir home(s.gpgHome);
11 ✔
34
    home.makeAbsolute();
11 ✔
35
    if (home.exists()) {
11 ✔
36
      env.insert(QStringLiteral("GNUPGHOME"), home.path());
16 ✔
37
    }
38
  }
11 ✔
39
  return env;
279 ✔
40
}
41

42
/// As Pass::updateEnv() sets it for the active store: git in @p dir does not
43
/// look above it, so neither the identity check nor a commit reads or uses a
44
/// repository the new store merely lies in (a dotfiles one in the home
45
/// folder), unless the user opted into that; and paths are names to it, not
46
/// patterns.
47
auto gitEnvironment(const QString &dir, const AppSettings &s)
34 ✔
48
    -> QProcessEnvironment {
49
  QProcessEnvironment env =
50
      withGpgHome(QProcessEnvironment::systemEnvironment(), s);
34 ✔
51
  // As for the active store: the paths handed to git are names, not
52
  // patterns (see Pass::updateEnv()).
53
  env.insert(QStringLiteral("GIT_LITERAL_PATHSPECS"), QStringLiteral("1"));
68 ✔
54
  if (!s.gitUseParentRepository) {
34 ✔
55
    for (const auto &[name, value] :
56
         Util::gitStoreVariables(dir, s.gitExecutable)) {
99 ✔
57
      env.insert(name, value);
33 ✔
58
    }
59
  }
60
  return env;
34 ✔
61
}
×
62
/// "commit", and "-S" when git config pass.signcommits is true for the
63
/// repository @p git runs in (a new one: so the user's own git config), as
64
/// pass signs its commits.
65
/// Time a set-up git command may take while the window waits: init, add
66
/// and an unsigned commit. A signed one waits for the passphrase instead.
67
constexpr int kGitSetupTimeoutMs = 2 * 60 * 1000;
68

69
/**
70
 * @brief The first thing git would open while staging @p files in @p dir
71
 * that it could wait on for good, or empty.
72
 *
73
 * git add opens the .gitattributes and .gitignore of each folder it stages
74
 * from, by name: a FIFO there, planted in a shared folder, kept it waiting
75
 * in open() with the window waiting on it. A link to one counts as one:
76
 * older git follows it. A sub-folder with a .git of its own is a repository git
77
 * looks into (its HEAD, say).
78
 * @param dir The store.
79
 * @param files Paths relative to @p dir that git is to stage.
80
 * @return That path, or empty.
81
 */
82
auto blocksGit(const QString &dir, const QStringList &files) -> QString {
18 ✔
83
  QSet<QString> folders{QStringLiteral(".")};
36 ✔
84
  for (const QString &file : files) {
44 ✔
85
    for (QString folder = QFileInfo(file).path();
26 ✔
86
         folder != QLatin1String(".") && !folders.contains(folder);
37 ✔
87
         folder = QFileInfo(folder).path()) {
22 ✔
88
      folders.insert(folder);
11 ✔
89
    }
90
  }
91
  const QDir base(dir);
18 ✔
92
  for (const QString &folder : std::as_const(folders)) {
93
    const QDir here(base.filePath(folder));
25 ✔
94
    for (const char *name : {".gitattributes", ".gitignore"}) {
70 ✔
95
      const QFileInfo info(here.filePath(QLatin1String(name)));
49 ✔
96
      if (info.exists() && !info.isFile()) {
49 ✔
97
        return info.filePath();
4 ✔
98
      }
99
    }
49 ✔
100
    const QFileInfo nested(here.filePath(QStringLiteral(".git")));
42 ✔
101
    if (folder != QLatin1String(".") &&
26 ✔
102
        (nested.exists() || nested.isSymLink())) {
9 ✔
103
      return nested.filePath();
1 ✔
104
    }
105
  }
25 ✔
106
  return {};
13 ✔
107
}
18 ✔
108

109
auto commitArgs(QProcess &git, const AppSettings &s) -> QStringList {
9 ✔
110
  QString out;
9 ✔
111
  const bool sign =
112
      Executor::executeBlocking(
54 ✔
113
          git, s.gitExecutable,
9 ✔
114
          {QStringLiteral("config"), QStringLiteral("--bool"),
9 ✔
115
           QStringLiteral("--get"), QStringLiteral("pass.signcommits")},
9 ✔
116
          QString(), &out, nullptr, nullptr, kGitSetupTimeoutMs) == 0 &&
18 ✔
117
      out.trimmed() == QLatin1String("true");
13 ✔
118
  return sign ? QStringList{QStringLiteral("commit"), QStringLiteral("-S")}
18 ✔
119
              : QStringList{QStringLiteral("commit")};
27 ✔
120
}
121
} // namespace
122

123
auto ProfileInit::gpgEnvironment(const AppSettings &s) -> QProcessEnvironment {
236 ✔
124
  return withGpgHome(QProcessEnvironment::systemEnvironment(), s);
236 ✔
125
}
126

127
auto ProfileInit::needsInit(const QString &path) -> bool {
11 ✔
128
  if (path.isEmpty()) {
11 ✔
129
    return false;
130
  }
131
  QDir dir(path);
10 ✔
132
  if (!dir.exists()) {
10 ✔
133
    return false;
134
  }
135
  return !dir.exists(".gpg-id");
9 ✔
136
}
10 ✔
137

138
auto ProfileInit::initialise(const QString &dir, const QList<UserInfo> &users,
27 ✔
139
                             const AppSettings &s, bool useGit, QString *note)
140
    -> bool {
141
  QString scratch;
27 ✔
142
  QString &out = note != nullptr ? *note : scratch;
27 ✔
143
  out.clear();
27 ✔
144

145
  const QDir folder(dir);
27 ✔
146
  if (!folder.exists() && !Util::mkpathForStore(folder.absolutePath())) {
33 ✔
147
    out = tr("Could not create %1.").arg(folder.absolutePath());
2 ✔
148
    return false;
1 ✔
149
  }
150
  const QString gpgIdFile = folder.filePath(QStringLiteral(".gpg-id"));
52 ✔
151
  QByteArray written;
26 ✔
152
  if (!writeGpgId(gpgIdFile, users, !s.passSigningKey.trimmed().isEmpty(), &out,
52 ✔
153
                  &written)) {
154
    return false;
155
  }
156
  QString sigFile;
23 ✔
157
  if (!s.passSigningKey.trimmed().isEmpty()) {
23 ✔
158
    if (!signGpgId(gpgIdFile, written, s, &out)) {
6 ✔
159
      return false;
160
    }
161
    sigFile = gpgIdFile + QStringLiteral(".sig");
4 ✔
162
  }
163
  if (useGit &&
25 ✔
164
      !commitGpgId(folder.absolutePath(), gpgIdFile, sigFile, s, &out)) {
25 ✔
165
    return false;
166
  }
167

168
  // Entries in sub-folders too: a store taken over whole has most of them
169
  // there. Visible regular files only, not through links, .git not walked.
170
  // Not those under a sub-folder with a .gpg-id of its own: its recipients
171
  // did not change here, and Users on the profile's root leaves it alone,
172
  // as pass does.
173
  const QString root = QDir::cleanPath(folder.absolutePath());
16 ✔
174
  const bool viaPass = s.usePass;
16 ✔
175
  const QString rootList =
176
      QFileInfo(QDir(root).filePath(QStringLiteral(".gpg-id")))
48 ✔
177
          .canonicalFilePath();
16 ✔
178
  const auto underSubStore = [&root, &rootList, viaPass](const QString &entry) {
17 ✔
179
    QString dir = QFileInfo(entry).absolutePath();
17 ✔
180
    while (dir != root && dir.startsWith(root + QLatin1Char('/'))) {
36 ✔
181
      // A list of its own: a regular file. A linked .gpg-id is no list to
182
      // the native backend, as everywhere in QtPass, so its folder's
183
      // entries still count; pass follows the link (`-f`) and keeps that
184
      // folder on the linked list, so with it they do not, unless the link
185
      // leads to the root's own list: that folder follows the root, and
186
      // Users on it re-encrypts them.
187
      const QFileInfo list(QDir(dir).filePath(QStringLiteral(".gpg-id")));
24 ✔
188
      if (viaPass && list.isFile() && !rootList.isEmpty() &&
12 ✔
189
          list.canonicalFilePath() == rootList) {
15 ✔
190
        return false;
191
      }
192
      if (list.isFile() &&
11 ✔
193
          (viaPass || (!list.isSymLink() && !list.isJunction()))) {
5 ✔
194
        return true;
4 ✔
195
      }
196
      dir = QFileInfo(dir).absolutePath();
14 ✔
197
    }
12 ✔
198
    return false;
199
  };
16 ✔
200
  QStringList existing =
201
      Util::regularFilesUnder(root, {QStringLiteral("*.gpg")});
48 ✔
202
  existing.erase(
16 ✔
203
      std::remove_if(existing.begin(), existing.end(), underSubStore),
32 ✔
204
      existing.end());
16 ✔
205
  if (!existing.isEmpty()) {
16 ✔
206
    out = tr("%1 already contains %n encrypted file(s); they were not "
9 ✔
207
             "re-encrypted. Switch to the profile and open Users to do that.",
208
             nullptr, static_cast<int>(existing.size()))
209
              .arg(folder.absolutePath());
18 ✔
210
  }
211
  return true;
212
}
27 ✔
213

214
auto ProfileInit::writeGpgId(const QString &gpgIdFile,
26 ✔
215
                             const QList<UserInfo> &users, bool signed_,
216
                             QString *note, QByteArray *written) -> bool {
217
  QStringList ids;
26 ✔
218
  for (const UserInfo &user : users) {
74 ✔
219
    if (user.enabled) {
48 ✔
220
      ids << user.key_id;
25 ✔
221
    }
222
  }
223
  if (ids.isEmpty()) {
26 ✔
224
    *note = tr("No recipient selected; %1 was not written.").arg(gpgIdFile);
2 ✔
225
    return false;
1 ✔
226
  }
227
  // As ImitatePass::writeGpgIdFile: renamed into place whole, so an
228
  // interrupted write leaves no half .gpg-id to sign or use. Owner-only: the
229
  // list leaks which keys the store is encrypted to.
230
  QByteArray contents =
231
      (ids.join(QLatin1Char('\n')) + QLatin1Char('\n')).toUtf8();
25 ✔
232
  if (signed_) {
25 ✔
233
    // Same rule as ImitatePass::writeGpgIdFile: reserved and recorded
234
    // before the write, bound to the store root (GpgIdGeneration). A new
235
    // profile has no list on disk to take a generation from.
236
    QString why;
7 ✔
237
    const std::optional<QString> store = GpgIdGeneration::storeIdFor(
238
        QFileInfo(gpgIdFile).absolutePath(), std::nullopt, &why);
14 ✔
239
    if (!store) {
7 ✔
UNCOV
240
      *note = why;
×
UNCOV
241
      return false;
×
242
    }
243
    const std::optional<qint64> generation =
244
        GpgIdGeneration::reserveNext(gpgIdFile, std::nullopt, &why);
7 ✔
245
    if (!generation) {
7 ✔
246
      *note = why;
1 ✔
247
      return false;
1 ✔
248
    }
249
    contents = GpgIdGeneration::withHeader(*generation, QStringLiteral("."),
12 ✔
250
                                           contents, *store);
251
  }
252
  QString why;
24 ✔
253
  if (!Util::writeFileReplacing(gpgIdFile, contents, true, &why)) {
24 ✔
254
    *note = why;
1 ✔
255
    return false;
1 ✔
256
  }
257
  if (written != nullptr) {
23 ✔
258
    *written = contents;
23 ✔
259
  }
260
  if (signed_) {
23 ✔
261
    // Same as ImitatePass::writeGpgIdFile: the bytes written are the ones
262
    // recognised; not fatal, the first read digests them otherwise.
263
    QString why;
6 ✔
264
    if (!GpgIdGeneration::recordWritten(gpgIdFile, contents, &why)) {
6 ✔
UNCOV
265
      qCWarning(lcQtPass) << "Could not record the written .gpg-id:" << why;
×
266
    }
267
  }
268
  return true;
269
}
270

271
auto ProfileInit::signGpgId(const QString &gpgIdFile,
6 ✔
272
                            const QByteArray &contents, const AppSettings &s,
273
                            QString *note) -> bool {
274
  // In the configured GPG home, as ImitatePass's signer runs in the store's
275
  // environment.
276
  const GpgIdSigner signer(
277
      s.gpgExecutable, GpgIdSigner::keysFromSetting(s.passSigningKey),
12 ✔
278
      [&s](const QString &app, const QStringList &args, const QString &input,
15 ✔
279
           QString *out, QString *err) {
280
        QProcess gpg;
9 ✔
281
        gpg.setProcessEnvironment(
9 ✔
282
            withGpgHome(QProcessEnvironment::systemEnvironment(), s));
18 ✔
283
        return Executor::executeBlocking(gpg, app, args, input, out, err);
18 ✔
284
      });
21 ✔
285
  QString err;
6 ✔
286
  if (!signer.sign(gpgIdFile, contents, &err)) {
6 ✔
287
    *note = err.trimmed().isEmpty()
4 ✔
288
                ? tr("Could not sign %1 with %2.")
12 ✔
289
                      .arg(gpgIdFile, signer.keys().first())
290
                : tr("Could not sign %1 with %2: %3")
4 ✔
291
                      .arg(gpgIdFile, signer.keys().first(), err.trimmed());
7 ✔
292
    // withGpgHome() fell back to the inherited home: gpg's "no secret key"
293
    // would not say that the configured one is missing.
294
    if (!s.gpgHome.isEmpty()) {
4 ✔
295
      QDir home(s.gpgHome);
1 ✔
296
      home.makeAbsolute();
1 ✔
297
      if (!home.exists()) {
1 ✔
298
        *note +=
299
            QLatin1Char(' ') +
1 ✔
300
            tr("The configured GPG home %1 does not exist.").arg(home.path());
3 ✔
301
      }
302
    }
1 ✔
303
    return false;
4 ✔
304
  }
305
  return true;
306
}
6 ✔
307

308
auto ProfileInit::runGit(QProcess &git, const AppSettings &s,
31 ✔
309
                         const QString &dir, const QStringList &args,
310
                         QString *note) -> bool {
311
  const bool signs = args.contains(QStringLiteral("-S"));
31 ✔
312
  QElapsedTimer clock;
31 ✔
313
  clock.start();
31 ✔
314
  QString err;
31 ✔
315
  const int rc =
316
      Executor::executeBlocking(git, s.gitExecutable, args, QString(), nullptr,
62 ✔
317
                                &err, nullptr, signs ? -1 : kGitSetupTimeoutMs);
318
  if (rc == 0) {
31 ✔
319
    return true;
320
  }
321
  if (!signs && clock.hasExpired(kGitSetupTimeoutMs)) {
6 ✔
NEW
322
    *note = tr("git %1 did not finish within %2 minutes in %3, and was "
×
323
               "stopped.")
NEW
324
                .arg(args.first())
×
NEW
325
                .arg(kGitSetupTimeoutMs / 60000)
×
NEW
326
                .arg(dir);
×
327
  } else {
328
    *note = tr("git %1 failed in %2: %3").arg(args.first(), dir, err.trimmed());
12 ✔
329
  }
330
  return false;
331
}
332

333
auto ProfileInit::refusedForGit(const QString &dir, const QStringList &files,
18 ✔
334
                                QString *note) -> bool {
335
  const QString path = blocksGit(dir, files);
18 ✔
336
  if (path.isEmpty()) {
18 ✔
337
    return false;
338
  }
339
  *note = QFileInfo(path).fileName() == QLatin1String(".git")
10 ✔
340
              ? tr("%1 is a Git repository inside the store. Move it out of "
15 ✔
341
                   "the store, then try again.")
342
                    .arg(QDir::toNativeSeparators(QFileInfo(path).path()))
7 ✔
343
              : tr("%1 is not a regular file, and Git could wait on it for "
5 ✔
344
                   "good. Remove it or make it a regular file, then try "
345
                   "again.")
346
                    .arg(QDir::toNativeSeparators(path));
13 ✔
347
  return true;
5 ✔
348
}
349

350
auto ProfileInit::commitGpgId(const QString &dir, const QString &gpgIdFile,
6 ✔
351
                              const QString &sigFile, const AppSettings &s,
352
                              QString *note) -> bool {
353
  // A process of our own in the profile directory: nothing here may touch
354
  // the shared Executor or PASSWORD_STORE_DIR of the active store.
355
  QProcess git;
6 ✔
356
  git.setWorkingDirectory(dir);
6 ✔
357
  git.setProcessEnvironment(gitEnvironment(dir, s));
6 ✔
358
  auto run = [&](const QStringList &args) -> bool {
11 ✔
359
    return runGit(git, s, dir, args, note);
11 ✔
360
  };
6 ✔
361
  QStringList files{QFileInfo(gpgIdFile).fileName()};
18 ✔
362
  if (!sigFile.isEmpty()) {
6 ✔
363
    files << QFileInfo(sigFile).fileName();
4 ✔
364
  }
365
  if (refusedForGit(dir, files, note)) {
6 ✔
366
    return false;
367
  }
368
  const QStringList add =
369
      QStringList{QStringLiteral("add"), QStringLiteral("--")} + files;
20 ✔
370
  if (!run({QStringLiteral("init")}) || !run(add)) {
15 ✔
371
    return false;
372
  }
373
  return run(commitArgs(git, s) +
9 ✔
374
             QStringList{QStringLiteral("-m"),
6 ✔
375
                         QStringLiteral("Added .gpg-id using QtPass."),
3 ✔
376
                         QStringLiteral("--")} +
21 ✔
377
             files);
3 ✔
378
}
12 ✔
379

380
auto ProfileInit::initGit(const QString &dir, const AppSettings &s,
12 ✔
381
                          QString *note) -> bool {
382
  QProcess git;
12 ✔
383
  git.setWorkingDirectory(dir);
12 ✔
384
  git.setProcessEnvironment(gitEnvironment(dir, s));
12 ✔
385
  auto run = [&](const QStringList &args) -> bool {
20 ✔
386
    return runGit(git, s, dir, args, note);
20 ✔
387
  };
12 ✔
388
  // Stage only store files (as the re-encryption backup commit does): an
389
  // existing folder may hold plaintext exports or swap files. Regular files
390
  // only: a link or junction must not have its target staged.
391
  QStringList files;
12 ✔
392
  const QDir base(dir);
12 ✔
393
  // Hidden directories (.git among them) are not walked, hidden files are:
394
  // .gpg-id is one.
395
  const QStringList found = Util::regularFilesUnder(
60 ✔
396
      dir,
397
      {QStringLiteral("*.gpg"), QStringLiteral(".gpg-id"),
12 ✔
398
       QStringLiteral(".gpg-id.sig")},
12 ✔
399
      nullptr, true);
12 ✔
400
  for (const QString &path : found) {
30 ✔
401
    files << base.relativeFilePath(path);
36 ✔
402
  }
403
  if (refusedForGit(dir, files, note)) {
12 ✔
404
    return false;
405
  }
406
  if (!run({QStringLiteral("init")})) {
24 ✔
407
    return false;
408
  }
409
  if (!files.isEmpty() &&
13 ✔
410
      !run(QStringList{QStringLiteral("add"), QStringLiteral("--")} + files)) {
31 ✔
411
    return false;
412
  }
413
  return run(commitArgs(git, s) +
18 ✔
414
             QStringList{QStringLiteral("--allow-empty"), QStringLiteral("-m"),
6 ✔
415
                         QStringLiteral("Added password store using QtPass.")});
42 ✔
416
}
24 ✔
417

418
auto ProfileInit::gitIdentityConfigured(const QString &dir,
16 ✔
419
                                        const AppSettings &s) -> bool {
420
  QProcess git;
16 ✔
421
  git.setWorkingDirectory(dir);
16 ✔
422
  git.setProcessEnvironment(gitEnvironment(dir, s));
16 ✔
423
  for (const char *key : {"user.name", "user.email"}) {
37 ✔
424
    QString out;
27 ✔
425
    if (Executor::executeBlocking(git, s.gitExecutable,
135 ✔
426
                                  {QStringLiteral("config"),
27 ✔
427
                                   QStringLiteral("--get"),
27 ✔
428
                                   QString::fromLatin1(key)},
429
                                  QString(), &out, nullptr) != 0 ||
102 ✔
430
        out.trimmed().isEmpty()) {
27 ✔
431
      return false;
432
    }
433
  }
434
  return true;
435
}
70 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc