QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
profileinit.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
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 <QHash>
21#include <QProcess>
22#include <QSet>
23#include <algorithm>
24#include <optional>
25#include <utility>
26
27namespace {
33auto withGpgHome(QProcessEnvironment env, const AppSettings &s)
34 -> QProcessEnvironment {
35 if (!s.gpgHome.isEmpty()) {
36 QDir home(s.gpgHome);
37 home.makeAbsolute();
38 if (home.exists()) {
39 env.insert(QStringLiteral("GNUPGHOME"), home.path());
40 }
41 }
42 return env;
43}
44
50auto gitEnvironment(const QString &dir, const AppSettings &s)
51 -> QProcessEnvironment {
52 QProcessEnvironment env =
53 withGpgHome(QProcessEnvironment::systemEnvironment(), s);
54 // As for the active store: the paths handed to git are names, not
55 // patterns (see Pass::updateEnv()).
56 env.insert(QStringLiteral("GIT_LITERAL_PATHSPECS"), QStringLiteral("1"));
57 // The identity check runs git before `git init` made the folder a
58 // repository, so a pushed bare-repository layout there would be read.
60 if (!s.gitUseParentRepository) {
61 const auto variables = Util::gitStoreVariables(dir, s.gitExecutable);
62 for (const auto &[name, value] : variables) {
63 env.insert(name, value);
64 }
65 }
66 return env;
67}
74constexpr int kGitSetupTimeoutMs = 2 * 60 * 1000;
75
89auto blocksGit(const QString &dir, const QStringList &files) -> QString {
90 QSet<QString> folders{QStringLiteral(".")};
91 for (const QString &file : files) {
92 for (QString folder = QFileInfo(file).path();
93 folder != QLatin1String(".") && !folders.contains(folder);
94 folder = QFileInfo(folder).path()) {
95 folders.insert(folder);
96 }
97 }
98 const QDir base(dir);
99 for (const QString &folder : std::as_const(folders)) {
100 const QDir here(base.filePath(folder));
101 for (const char *name : {".gitattributes", ".gitignore"}) {
102 const QFileInfo info(here.filePath(QLatin1String(name)));
103 if (info.exists() && !info.isFile()) {
104 return info.filePath();
105 }
106 }
107 const QFileInfo nested(here.filePath(QStringLiteral(".git")));
108 if (folder != QLatin1String(".") &&
109 (nested.exists() || nested.isSymLink())) {
110 return nested.filePath();
111 }
112 }
113 return {};
114}
115
123auto signerFor(const AppSettings &s) -> GpgIdSigner {
124 GpgIdSigner signer(
125 s.gpgExecutable, GpgIdSigner::keysFromSetting(s.passSigningKey),
126 [s](const QString &app, const QStringList &args, const QString &input,
127 QString *out, QString *err) {
128 QProcess gpg;
129 gpg.setProcessEnvironment(
130 withGpgHome(QProcessEnvironment::systemEnvironment(), s));
131 return Executor::executeBlocking(gpg, app, args, input, out, err);
132 });
133 signer.setStoreRoot(s.passStore);
134 return signer;
135}
136
137auto commitArgs(QProcess &git, const AppSettings &s) -> QStringList {
138 QString out;
139 const bool sign =
141 git, s.gitExecutable,
142 {QStringLiteral("config"), QStringLiteral("--bool"),
143 QStringLiteral("--get"), QStringLiteral("pass.signcommits")},
144 QString(), &out, nullptr) == 0 &&
145 out.trimmed() == QLatin1String("true");
146 return sign ? QStringList{QStringLiteral("commit"), QStringLiteral("-S")}
147 : QStringList{QStringLiteral("commit")};
148}
149} // namespace
150
151auto ProfileInit::gpgEnvironment(const AppSettings &s) -> QProcessEnvironment {
152 return withGpgHome(QProcessEnvironment::systemEnvironment(), s);
153}
154
155auto ProfileInit::needsInit(const QString &path) -> bool {
156 if (path.isEmpty()) {
157 return false;
158 }
159 QDir dir(path);
160 if (!dir.exists()) {
161 return false;
162 }
163 return !dir.exists(".gpg-id");
164}
165
166auto ProfileInit::initialise(const QString &dir, const QList<UserInfo> &users,
167 const AppSettings &settings, bool useGit,
168 QString *note) -> bool {
169 // A key exported for pass counts when none is set, as in Pass::init().
170 AppSettings s = settings;
172 QString scratch;
173 QString &out = note != nullptr ? *note : scratch;
174 out.clear();
175
176 const QDir folder(dir);
177 if (!folder.exists() && !Util::mkpathForStore(folder.absolutePath())) {
178 out = tr("Could not create %1.").arg(folder.absolutePath());
179 return false;
180 }
181 // Before anything is written: a refusal later would leave a .gpg-id
182 // behind, and a store that looks finished.
183 if (useGit &&
184 refusedForGit(folder.absolutePath(),
185 {QStringLiteral(".gpg-id"), QStringLiteral(".gpg-id.sig")},
186 &out)) {
187 return false;
188 }
189 const QString gpgIdFile = folder.filePath(QStringLiteral(".gpg-id"));
190 // Before the list is written, as ImitatePass::Init() does: writing it
191 // takes the next generation, and a list that then cannot be signed left
192 // this device's record one ahead of the store's own, refused afterwards
193 // as a rollback.
194 if (signingKeyUnavailable(s, &out)) {
195 return false;
196 }
197 QByteArray written;
198 if (!writeGpgId(gpgIdFile, users, !s.passSigningKey.trimmed().isEmpty(), &out,
199 &written)) {
200 return false;
201 }
202 QString sigFile;
203 if (!s.passSigningKey.trimmed().isEmpty()) {
204 if (!signGpgId(gpgIdFile, written, s, &out)) {
205 return false;
206 }
207 sigFile = gpgIdFile + QStringLiteral(".sig");
208 }
209 if (useGit &&
210 !commitGpgId(folder.absolutePath(), gpgIdFile, sigFile, s, &out)) {
211 return false;
212 }
213
214 const QStringList existing =
215 entriesOnThisList(folder.absolutePath(), s.usePass);
216 if (!existing.isEmpty()) {
217 out = tr("%1 already contains %n encrypted file(s); they were not "
218 "re-encrypted. Switch to the profile and open Users to do that.",
219 nullptr, static_cast<int>(existing.size()))
220 .arg(folder.absolutePath());
221 }
222 return true;
223}
224
226 -> bool {
227 if (s.passSigningKey.trimmed().isEmpty() || signerFor(s).haveSecretKey()) {
228 return false;
229 }
230 *note = tr("The secret key of the signing key %1 is not available, so no "
231 "recipient list was written.")
232 .arg(GpgIdSigner::keysFromSetting(s.passSigningKey).constFirst());
233 // withGpgHome() fell back to the inherited home, as for signing.
234 if (!s.gpgHome.isEmpty()) {
235 QDir home(s.gpgHome);
236 home.makeAbsolute();
237 if (!home.exists()) {
238 *note += QLatin1Char(' ') + tr("The configured GPG home %1 does not "
239 "exist.")
240 .arg(home.path());
241 }
242 }
243 return true;
244}
245
246auto ProfileInit::entriesOnThisList(const QString &dir, bool viaPass)
247 -> QStringList {
248 // Entries in sub-folders too: a store taken over whole has most of them
249 // there. Visible regular files only, not through links, .git not walked.
250 // Not those under a sub-folder with a .gpg-id of its own: its recipients
251 // did not change here, and Users on the profile's root leaves it alone,
252 // as pass does.
253 const QString root = QDir::cleanPath(dir);
254 const QString rootList =
255 QFileInfo(QDir(root).filePath(QStringLiteral(".gpg-id")))
256 .canonicalFilePath();
257 // What a folder's own .gpg-id decides, if it has one.
258 const auto ownList = [&rootList,
259 viaPass](const QString &folder) -> std::optional<bool> {
260 // A list of its own: a regular file. A linked .gpg-id is no list to
261 // the native backend, as everywhere in QtPass, so its folder's entries
262 // still count; pass follows the link (`-f`) and keeps that folder on
263 // the linked list, so with it they do not, unless the link leads to the
264 // root's own list: that folder follows the root, and Users on it
265 // re-encrypts them.
266 const QFileInfo list(QDir(folder).filePath(QStringLiteral(".gpg-id")));
267 if (viaPass && list.isFile() && !rootList.isEmpty() &&
268 list.canonicalFilePath() == rootList) {
269 return false;
270 }
271 if (list.isFile() &&
272 (viaPass || (!list.isSymLink() && !list.isJunction()))) {
273 return true;
274 }
275 return std::nullopt;
276 };
277 // Each folder's verdict once: climbing from every entry to the root again
278 // cost entries times depth, and a co-writer's deep chain of folders froze
279 // Finish for tens of minutes.
280 QHash<QString, bool> verdictOf;
281 const auto underSubStore = [&root, &ownList,
282 &verdictOf](const QString &entry) {
283 QStringList climbed;
284 QString at = QFileInfo(entry).absolutePath();
285 bool verdict = false;
286 while (at != root && at.startsWith(root + QLatin1Char('/'))) {
287 if (const auto known = verdictOf.constFind(at);
288 known != verdictOf.constEnd()) {
289 verdict = known.value();
290 break;
291 }
292 climbed << at;
293 if (const std::optional<bool> own = ownList(at)) {
294 verdict = *own;
295 break;
296 }
297 at = QFileInfo(at).absolutePath();
298 }
299 for (const QString &folder : std::as_const(climbed)) {
300 verdictOf.insert(folder, verdict);
301 }
302 return verdict;
303 };
304 QStringList entries =
305 Util::regularFilesUnder(root, {QStringLiteral("*.gpg")});
306 entries.erase(std::remove_if(entries.begin(), entries.end(), underSubStore),
307 entries.end());
308 return entries;
309}
310
311auto ProfileInit::writeGpgId(const QString &gpgIdFile,
312 const QList<UserInfo> &users, bool signed_,
313 QString *note, QByteArray *written) -> bool {
314 QStringList ids;
315 for (const UserInfo &user : users) {
316 if (user.enabled) {
317 ids << user.key_id;
318 }
319 }
320 if (ids.isEmpty()) {
321 *note = tr("No recipient selected; %1 was not written.").arg(gpgIdFile);
322 return false;
323 }
324 // As ImitatePass::writeGpgIdFile: renamed into place whole, so an
325 // interrupted write leaves no half .gpg-id to sign or use. Owner-only: the
326 // list leaks which keys the store is encrypted to.
327 QByteArray contents =
328 (ids.join(QLatin1Char('\n')) + QLatin1Char('\n')).toUtf8();
329 if (signed_) {
330 // Same rule as ImitatePass::writeGpgIdFile: reserved and recorded
331 // before the write, bound to the store root (GpgIdGeneration). A new
332 // profile has no list on disk to take a generation from.
333 QString why;
334 const std::optional<QString> store = GpgIdGeneration::storeIdFor(
335 QFileInfo(gpgIdFile).absolutePath(), std::nullopt, &why);
336 if (!store) {
337 *note = std::move(why);
338 return false;
339 }
340 const std::optional<qint64> generation =
341 GpgIdGeneration::reserveNext(gpgIdFile, std::nullopt, &why);
342 if (!generation) {
343 *note = std::move(why);
344 return false;
345 }
346 contents = GpgIdGeneration::withHeader(*generation, QStringLiteral("."),
347 contents, *store);
348 }
349 QString why;
350 if (!Util::writeFileReplacing(gpgIdFile, contents, true, &why)) {
351 *note = std::move(why);
352 return false;
353 }
354 if (written != nullptr) {
355 *written = contents;
356 }
357 if (signed_) {
358 // Same as ImitatePass::writeGpgIdFile: the bytes written are the ones
359 // recognised; not fatal, the first read digests them otherwise.
360 QString why;
361 if (!GpgIdGeneration::recordWritten(gpgIdFile, contents, &why)) {
362 qCWarning(lcQtPass) << "Could not record the written .gpg-id:" << why;
363 }
364 }
365 return true;
366}
367
368auto ProfileInit::signGpgId(const QString &gpgIdFile,
369 const QByteArray &contents, const AppSettings &s,
370 QString *note) -> bool {
371 const GpgIdSigner signer = signerFor(s);
372 QString err;
373 if (!signer.sign(gpgIdFile, contents, &err)) {
374 *note = err.trimmed().isEmpty()
375 ? tr("Could not sign %1 with %2.")
376 .arg(gpgIdFile, signer.keys().first())
377 : tr("Could not sign %1 with %2: %3")
378 .arg(gpgIdFile, signer.keys().first(), err.trimmed());
379 // withGpgHome() fell back to the inherited home: gpg's "no secret key"
380 // would not say that the configured one is missing.
381 if (!s.gpgHome.isEmpty()) {
382 QDir home(s.gpgHome);
383 home.makeAbsolute();
384 if (!home.exists()) {
385 *note +=
386 QLatin1Char(' ') +
387 tr("The configured GPG home %1 does not exist.").arg(home.path());
388 }
389 }
390 return false;
391 }
392 return true;
393}
394
395auto ProfileInit::runGit(QProcess &git, const AppSettings &s,
396 const QString &dir, const QStringList &args,
397 QString *note) -> bool {
398 const bool bounded = args.first() == QLatin1String("init") ||
399 args.first() == QLatin1String("add");
400 QElapsedTimer clock;
401 clock.start();
402 QString err;
403 const int rc = Executor::executeBlocking(git, s.gitExecutable, args,
404 QString(), nullptr, &err, nullptr,
405 bounded ? kGitSetupTimeoutMs : -1);
406 if (rc == 0) {
407 return true;
408 }
409 // -1 is what a stopped run returns; git's own failures are positive.
410 if (bounded && rc == -1 && clock.elapsed() >= kGitSetupTimeoutMs) {
411 *note = tr("git %1 did not finish within %2 minutes in %3, and was "
412 "stopped.")
413 .arg(args.first())
414 .arg(kGitSetupTimeoutMs / 60000)
415 .arg(dir);
416 } else {
417 *note = tr("git %1 failed in %2: %3").arg(args.first(), dir, err.trimmed());
418 }
419 return false;
420}
421
422auto ProfileInit::refusedForGit(const QString &dir, const QStringList &files,
423 QString *note) -> bool {
424 const QString path = blocksGit(dir, files);
425 if (path.isEmpty()) {
426 return false;
427 }
428 *note = QFileInfo(path).fileName() == QLatin1String(".git")
429 ? tr("%1 is a Git repository inside the store. Move it out of "
430 "the store, then try again.")
431 .arg(QDir::toNativeSeparators(QFileInfo(path).path()))
432 : tr("%1 is not a regular file, and Git could wait on it for "
433 "good. Remove it or make it a regular file, then try "
434 "again.")
435 .arg(QDir::toNativeSeparators(path));
436 return true;
437}
438
439auto ProfileInit::commitGpgId(const QString &dir, const QString &gpgIdFile,
440 const QString &sigFile, const AppSettings &s,
441 QString *note) -> bool {
442 // A process of our own in the profile directory: nothing here may touch
443 // the shared Executor or PASSWORD_STORE_DIR of the active store.
444 QProcess git;
445 git.setWorkingDirectory(dir);
446 git.setProcessEnvironment(gitEnvironment(dir, s));
447 auto run = [&](const QStringList &args) -> bool {
448 return runGit(git, s, dir, args, note);
449 };
450 QStringList files{QFileInfo(gpgIdFile).fileName()};
451 if (!sigFile.isEmpty()) {
452 files << QFileInfo(sigFile).fileName();
453 }
454 // initialise() checked before writing these; again here, as signing can
455 // take a while and the folder is shared.
456 if (refusedForGit(dir, files, note)) {
457 return false;
458 }
459 const QStringList add =
460 QStringList{QStringLiteral("add"), QStringLiteral("--")} + files;
461 if (!run({QStringLiteral("init")}) || !run(add)) {
462 return false;
463 }
464 return run(commitArgs(git, s) +
465 QStringList{QStringLiteral("-m"),
466 QStringLiteral("Added .gpg-id using QtPass."),
467 QStringLiteral("--")} +
468 files);
469}
470
471auto ProfileInit::initGit(const QString &dir, const AppSettings &s,
472 QString *note) -> bool {
473 QProcess git;
474 git.setWorkingDirectory(dir);
475 git.setProcessEnvironment(gitEnvironment(dir, s));
476 auto run = [&](const QStringList &args) -> bool {
477 return runGit(git, s, dir, args, note);
478 };
479 // Stage only store files (as the re-encryption backup commit does): an
480 // existing folder may hold plaintext exports or swap files. Regular files
481 // only: a link or junction must not have its target staged.
482 QStringList files;
483 const QDir base(dir);
484 // Hidden directories (.git among them) are not walked, hidden files are:
485 // .gpg-id is one.
486 const QStringList found = Util::regularFilesUnder(
487 dir,
488 {QStringLiteral("*.gpg"), QStringLiteral(".gpg-id"),
489 QStringLiteral(".gpg-id.sig")},
490 nullptr, true);
491 for (const QString &path : found) {
492 files << base.relativeFilePath(path);
493 }
494 if (refusedForGit(dir, files, note)) {
495 return false;
496 }
497 if (!run({QStringLiteral("init")})) {
498 return false;
499 }
500 if (!files.isEmpty() &&
501 !run(QStringList{QStringLiteral("add"), QStringLiteral("--")} + files)) {
502 return false;
503 }
504 return run(commitArgs(git, s) +
505 QStringList{QStringLiteral("--allow-empty"), QStringLiteral("-m"),
506 QStringLiteral("Added password store using QtPass.")});
507}
508
510 const AppSettings &s) -> bool {
511 QProcess git;
512 git.setWorkingDirectory(dir);
513 git.setProcessEnvironment(gitEnvironment(dir, s));
514 for (const char *key : {"user.name", "user.email"}) {
515 QString out;
516 if (Executor::executeBlocking(git, s.gitExecutable,
517 {QStringLiteral("config"),
518 QStringLiteral("--get"),
519 QString::fromLatin1(key)},
520 QString(), &out, nullptr) != 0 ||
521 out.trimmed().isEmpty()) {
522 return false;
523 }
524 }
525 return true;
526}
AppSettings, the value object holding every flat QtPass setting.
static auto executeBlocking(const QString &app, const QStringList &args, const QString &input=QString(), QString *process_out=nullptr, QString *process_err=nullptr) -> int
Run a command synchronously and return its exit code.
Definition executor.cpp:700
static auto reserveNext(const QString &gpgIdFile, std::optional< qint64 > verifiedOnDisk, QString *error=nullptr) -> std::optional< qint64 >
Reserve the generation to write next for gpgIdFile: one above both what this device remembers and ver...
static auto recordWritten(const QString &gpgIdFile, const QByteArray &contents, QString *error=nullptr) -> bool
Record the bytes just written for gpgIdFile, so that this device recognises its own list afterwards a...
static auto withHeader(qint64 generation, const QString &folder, const QByteArray &recipients, const QString &store={}) -> QByteArray
A complete list: the header in front of the recipients.
static auto storeIdFor(const QString &storeRoot, const std::optional< QString > &onDisk, QString *error=nullptr) -> std::optional< QString >
The store id to write into a list of storeRoot: the one this device knows the store by; else onDisk,...
The detached signature on a store's .gpg-id: whether the configured signing key is usable,...
Definition gpgidsigner.h:29
auto sign(const QString &gpgIdFile, const QByteArray &contents, QString *error=nullptr) const -> bool
Write <file>.sig, a detached signature by the first key over contents, the bytes the caller just wrot...
static auto settingOrExported(const QString &passSigningKey) -> QString
The signing key to use: the setting, or with none set, the PASSWORD_STORE_SIGNING_KEY exported for pa...
auto keys() const -> const QStringList &
The keys this signer was given.
static auto keysFromSetting(const QString &passSigningKey) -> QStringList
Split the settings value into keys, upper-cased the way gpg prints fingerprints.
static auto needsInit(const QString &path) -> bool
Check if a profile path needs initialization.
static auto refusedForGit(const QString &dir, const QStringList &files, QString *note) -> bool
Whether staging files in dir is refused because git could wait on something there for good: a ....
static auto initialise(const QString &dir, const QList< UserInfo > &users, const AppSettings &settings, bool useGit, QString *note) -> bool
Write the recipients and, if wanted, put the folder under git.
static auto entriesOnThisList(const QString &dir, bool viaPass) -> QStringList
The encrypted entries under dir that the new root list covers: visible regular .gpg files,...
static auto initGit(const QString &dir, const AppSettings &s, QString *note) -> bool
Put an existing store under Git: git init, stage the .gpg entries and the .gpg-id files (nothing else...
static auto commitGpgId(const QString &dir, const QString &gpgIdFile, const QString &sigFile, const AppSettings &s, QString *note) -> bool
git init in dir, stage the .gpg-id and its signature, and commit them (signed when pass....
static auto runGit(QProcess &git, const AppSettings &s, const QString &dir, const QStringList &args, QString *note) -> bool
Run one set-up git command on git and wait for it: init and add, which read what lies in the folder,...
static auto signingKeyUnavailable(const AppSettings &s, QString *note) -> bool
Whether the profile has a signing key whose secret key gpg does not hold, so no list may be written: ...
static auto gpgEnvironment(const AppSettings &s) -> QProcessEnvironment
The environment QtPass runs gpg in outside the active store's backend: the system's,...
static auto gitIdentityConfigured(const QString &dir, const AppSettings &s) -> bool
Whether git has a name and e-mail to commit with, i.e. user.name and user.email resolve (globally or ...
static auto writeGpgId(const QString &gpgIdFile, const QList< UserInfo > &users, bool signed_, QString *note, QByteArray *written=nullptr) -> bool
Write the enabled recipients to gpgIdFile, whole or not at all; with signed_ the list carries the gen...
static auto signGpgId(const QString &gpgIdFile, const QByteArray &contents, const AppSettings &s, QString *note) -> bool
Sign the list just written as gpgIdFile, over the bytes contents that were written.
static auto writeFileReplacing(const QString &path, const QByteArray &bytes, bool replace, QString *error=nullptr) -> bool
Write bytes as the file path through stageFileReplacing().
Definition util.cpp:1911
static auto regularFilesUnder(const QString &dir, const QStringList &nameFilters, QStringList *skipped=nullptr, bool hiddenFiles=false, QStringList *unlisted=nullptr) -> QStringList
Regular files under dir whose name matches one of nameFilters, found by walking only real directories...
Definition util.cpp:1149
static void requireExplicitBareRepository(QProcessEnvironment &env)
Make git in env refuse a folder that is merely laid out as a bare repository (safe....
Definition util.cpp:511
static auto gitStoreVariables(const QString &store, const QString &git={}, std::optional< uint > asUser=std::nullopt) -> QList< std::pair< QString, QString > >
The variables that keep git in store's own repository, never one above it: GIT_CEILING_DIRECTORIES (g...
Definition util.cpp:553
static auto mkpathForStore(const QString &path) -> bool
Create path and any missing parents as pass would.
Definition util.cpp:615
Executor, the FIFO queue every gpg, git and pass child process of QtPass goes through,...
Rollback detection for signed .gpg-id files: the generation counter and the record of what was last s...
GpgIdSigner, which signs a store's .gpg-id and verifies an existing .gpg-id.sig against the configure...
Initialising a new profile's store (.gpg-id, signature, Git) with blocking processes,...
The "qtpass" logging category.
Plain value-object holding all flat QtPass configuration.
Definition appsettings.h:36
QString passSigningKey
GPG key used to sign .gpg-id files.
Definition appsettings.h:61
bool usePass
Use the pass CLI (true) or native git/gpg.
Definition appsettings.h:59
Stores GPG key info including validity, creation date, and more.
Definition userinfo.h:20
UserInfo, one GPG key as listed by gpg, with the selection flag the recipient dialogs use.
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...