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

IJHack / QtPass / 44269343813

18 Nov 2026 08:42AM UTC coverage: 96.308% (+0.03%) from 96.28%
44269343813

Pull #2261

github

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

60 of 64 new or added lines in 3 files covered. (93.75%)

17 existing lines in 2 files now uncovered.

9157 of 9508 relevant lines covered (96.31%)

1286.78 hits per line

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

96.51
/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)
278 ✔
31
    -> QProcessEnvironment {
32
  if (!s.gpgHome.isEmpty()) {
278 ✔
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;
278 ✔
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)
33 ✔
48
    -> QProcessEnvironment {
49
  QProcessEnvironment env =
50
      withGpgHome(QProcessEnvironment::systemEnvironment(), s);
33 ✔
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"));
66 ✔
54
  if (!s.gitUseParentRepository) {
33 ✔
55
    for (const auto &[name, value] :
56
         Util::gitStoreVariables(dir, s.gitExecutable)) {
96 ✔
57
      env.insert(name, value);
32 ✔
58
    }
59
  }
60
  return env;
33 ✔
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 `git init` and `git add` may take while the window waits: the two
66
/// that read what lies in the folder. A commit is not bounded: git may sign
67
/// it (pass.signcommits or commit.gpgSign) and wait for the passphrase.
68
constexpr int kGitSetupTimeoutMs = 2 * 60 * 1000;
69

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

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

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

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

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

146
  const QDir folder(dir);
27 ✔
147
  if (!folder.exists() && !Util::mkpathForStore(folder.absolutePath())) {
33 ✔
148
    out = tr("Could not create %1.").arg(folder.absolutePath());
2 ✔
149
    return false;
1 ✔
150
  }
151
  // Before anything is written: a refusal later would leave a .gpg-id
152
  // behind, and a store that looks finished.
153
  if (useGit &&
26 ✔
154
      refusedForGit(folder.absolutePath(),
50 ✔
155
                    {QStringLiteral(".gpg-id"), QStringLiteral(".gpg-id.sig")},
26 ✔
156
                    &out)) {
157
    return false;
158
  }
159
  const QString gpgIdFile = folder.filePath(QStringLiteral(".gpg-id"));
50 ✔
160
  QByteArray written;
25 ✔
161
  if (!writeGpgId(gpgIdFile, users, !s.passSigningKey.trimmed().isEmpty(), &out,
50 ✔
162
                  &written)) {
163
    return false;
164
  }
165
  QString sigFile;
22 ✔
166
  if (!s.passSigningKey.trimmed().isEmpty()) {
22 ✔
167
    if (!signGpgId(gpgIdFile, written, s, &out)) {
6 ✔
168
      return false;
169
    }
170
    sigFile = gpgIdFile + QStringLiteral(".sig");
4 ✔
171
  }
172
  if (useGit &&
23 ✔
173
      !commitGpgId(folder.absolutePath(), gpgIdFile, sigFile, s, &out)) {
23 ✔
174
    return false;
175
  }
176

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

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

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

317
auto ProfileInit::runGit(QProcess &git, const AppSettings &s,
31 ✔
318
                         const QString &dir, const QStringList &args,
319
                         QString *note) -> bool {
320
  const bool bounded = args.first() == QLatin1String("init") ||
31 ✔
321
                       args.first() == QLatin1String("add");
18 ✔
322
  QElapsedTimer clock;
31 ✔
323
  clock.start();
31 ✔
324
  QString err;
31 ✔
325
  const int rc = Executor::executeBlocking(git, s.gitExecutable, args,
31 ✔
326
                                           QString(), nullptr, &err, nullptr,
31 ✔
327
                                           bounded ? kGitSetupTimeoutMs : -1);
328
  if (rc == 0) {
31 ✔
329
    return true;
330
  }
331
  // -1 is what a stopped run returns; git's own failures are positive.
332
  if (bounded && rc == -1 && clock.elapsed() >= kGitSetupTimeoutMs) {
6 ✔
NEW
333
    *note = tr("git %1 did not finish within %2 minutes in %3, and was "
×
334
               "stopped.")
NEW
335
                .arg(args.first())
×
NEW
336
                .arg(kGitSetupTimeoutMs / 60000)
×
NEW
337
                .arg(dir);
×
338
  } else {
339
    *note = tr("git %1 failed in %2: %3").arg(args.first(), dir, err.trimmed());
12 ✔
340
  }
341
  return false;
342
}
343

344
auto ProfileInit::refusedForGit(const QString &dir, const QStringList &files,
18 ✔
345
                                QString *note) -> bool {
346
  const QString path = blocksGit(dir, files);
18 ✔
347
  if (path.isEmpty()) {
18 ✔
348
    return false;
349
  }
350
  *note = QFileInfo(path).fileName() == QLatin1String(".git")
10 ✔
351
              ? tr("%1 is a Git repository inside the store. Move it out of "
15 ✔
352
                   "the store, then try again.")
353
                    .arg(QDir::toNativeSeparators(QFileInfo(path).path()))
7 ✔
354
              : tr("%1 is not a regular file, and Git could wait on it for "
5 ✔
355
                   "good. Remove it or make it a regular file, then try "
356
                   "again.")
357
                    .arg(QDir::toNativeSeparators(path));
13 ✔
358
  return true;
5 ✔
359
}
360

361
auto ProfileInit::commitGpgId(const QString &dir, const QString &gpgIdFile,
5 ✔
362
                              const QString &sigFile, const AppSettings &s,
363
                              QString *note) -> bool {
364
  // A process of our own in the profile directory: nothing here may touch
365
  // the shared Executor or PASSWORD_STORE_DIR of the active store.
366
  QProcess git;
5 ✔
367
  git.setWorkingDirectory(dir);
5 ✔
368
  git.setProcessEnvironment(gitEnvironment(dir, s));
5 ✔
369
  auto run = [&](const QStringList &args) -> bool {
11 ✔
370
    return runGit(git, s, dir, args, note);
11 ✔
371
  };
5 ✔
372
  QStringList files{QFileInfo(gpgIdFile).fileName()};
15 ✔
373
  if (!sigFile.isEmpty()) {
5 ✔
374
    files << QFileInfo(sigFile).fileName();
4 ✔
375
  }
376
  // initialise() refused what git could wait on before writing these.
377
  const QStringList add =
378
      QStringList{QStringLiteral("add"), QStringLiteral("--")} + files;
20 ✔
379
  if (!run({QStringLiteral("init")}) || !run(add)) {
15 ✔
380
    return false;
381
  }
382
  return run(commitArgs(git, s) +
9 ✔
383
             QStringList{QStringLiteral("-m"),
6 ✔
384
                         QStringLiteral("Added .gpg-id using QtPass."),
3 ✔
385
                         QStringLiteral("--")} +
21 ✔
386
             files);
3 ✔
387
}
10 ✔
388

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

427
auto ProfileInit::gitIdentityConfigured(const QString &dir,
16 ✔
428
                                        const AppSettings &s) -> bool {
429
  QProcess git;
16 ✔
430
  git.setWorkingDirectory(dir);
16 ✔
431
  git.setProcessEnvironment(gitEnvironment(dir, s));
16 ✔
432
  for (const char *key : {"user.name", "user.email"}) {
37 ✔
433
    QString out;
27 ✔
434
    if (Executor::executeBlocking(git, s.gitExecutable,
135 ✔
435
                                  {QStringLiteral("config"),
27 ✔
436
                                   QStringLiteral("--get"),
27 ✔
437
                                   QString::fromLatin1(key)},
438
                                  QString(), &out, nullptr) != 0 ||
102 ✔
439
        out.trimmed().isEmpty()) {
27 ✔
440
      return false;
441
    }
442
  }
443
  return true;
444
}
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