17#include <QElapsedTimer>
33auto withGpgHome(QProcessEnvironment env,
const AppSettings &s)
34 -> QProcessEnvironment {
35 if (!s.gpgHome.isEmpty()) {
39 env.insert(QStringLiteral(
"GNUPGHOME"), home.path());
50auto gitEnvironment(
const QString &dir,
const AppSettings &s)
51 -> QProcessEnvironment {
52 QProcessEnvironment env =
53 withGpgHome(QProcessEnvironment::systemEnvironment(), s);
56 env.insert(QStringLiteral(
"GIT_LITERAL_PATHSPECS"), QStringLiteral(
"1"));
60 if (!s.gitUseParentRepository) {
62 for (
const auto &[name, value] : variables) {
63 env.insert(name, value);
74constexpr int kGitSetupTimeoutMs = 2 * 60 * 1000;
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);
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();
107 const QFileInfo nested(here.filePath(QStringLiteral(
".git")));
108 if (folder != QLatin1String(
".") &&
109 (nested.exists() || nested.isSymLink())) {
110 return nested.filePath();
126 [s](
const QString &app,
const QStringList &args,
const QString &input,
127 QString *out, QString *err) {
129 gpg.setProcessEnvironment(
130 withGpgHome(QProcessEnvironment::systemEnvironment(), s));
131 return Executor::executeBlocking(gpg, app, args, input, out, err);
133 signer.setStoreRoot(s.passStore);
137auto commitArgs(QProcess &git,
const AppSettings &s) -> QStringList {
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")};
152 return withGpgHome(QProcessEnvironment::systemEnvironment(), s);
156 if (path.isEmpty()) {
163 return !dir.exists(
".gpg-id");
168 QString *note) ->
bool {
173 QString &out = note !=
nullptr ? *note : scratch;
176 const QDir folder(dir);
178 out = tr(
"Could not create %1.").arg(folder.absolutePath());
185 {QStringLiteral(
".gpg-id"), QStringLiteral(
".gpg-id.sig")},
189 const QString gpgIdFile = folder.filePath(QStringLiteral(
".gpg-id"));
204 if (!
signGpgId(gpgIdFile, written, s, &out)) {
207 sigFile = gpgIdFile + QStringLiteral(
".sig");
210 !
commitGpgId(folder.absolutePath(), gpgIdFile, sigFile, s, &out)) {
214 const QStringList existing =
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());
227 if (s.passSigningKey.trimmed().isEmpty() || signerFor(s).haveSecretKey()) {
230 *note = tr(
"The secret key of the signing key %1 is not available, so no "
231 "recipient list was written.")
234 if (!s.gpgHome.isEmpty()) {
235 QDir home(s.gpgHome);
237 if (!home.exists()) {
238 *note += QLatin1Char(
' ') + tr(
"The configured GPG home %1 does not "
253 const QString root = QDir::cleanPath(dir);
254 const QString rootList =
255 QFileInfo(QDir(root).filePath(QStringLiteral(
".gpg-id")))
256 .canonicalFilePath();
258 const auto ownList = [&rootList,
259 viaPass](
const QString &folder) -> std::optional<bool> {
266 const QFileInfo list(QDir(folder).filePath(QStringLiteral(
".gpg-id")));
267 if (viaPass && list.isFile() && !rootList.isEmpty() &&
268 list.canonicalFilePath() == rootList) {
272 (viaPass || (!list.isSymLink() && !list.isJunction()))) {
280 QHash<QString, bool> verdictOf;
281 const auto underSubStore = [&root, &ownList,
282 &verdictOf](
const QString &entry) {
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();
293 if (
const std::optional<bool> own = ownList(at)) {
297 at = QFileInfo(at).absolutePath();
299 for (
const QString &folder : std::as_const(climbed)) {
300 verdictOf.insert(folder, verdict);
304 QStringList entries =
306 entries.erase(std::remove_if(entries.begin(), entries.end(), underSubStore),
312 const QList<UserInfo> &users,
bool signed_,
313 QString *note, QByteArray *written) ->
bool {
315 for (
const UserInfo &user : users) {
321 *note = tr(
"No recipient selected; %1 was not written.").arg(gpgIdFile);
327 QByteArray contents =
328 (ids.join(QLatin1Char(
'\n')) + QLatin1Char(
'\n')).toUtf8();
335 QFileInfo(gpgIdFile).absolutePath(), std::nullopt, &why);
337 *note = std::move(why);
340 const std::optional<qint64> generation =
343 *note = std::move(why);
351 *note = std::move(why);
354 if (written !=
nullptr) {
362 qCWarning(lcQtPass) <<
"Could not record the written .gpg-id:" << why;
370 QString *note) ->
bool {
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());
381 if (!s.gpgHome.isEmpty()) {
382 QDir home(s.gpgHome);
384 if (!home.exists()) {
387 tr(
"The configured GPG home %1 does not exist.").arg(home.path());
396 const QString &dir,
const QStringList &args,
397 QString *note) ->
bool {
398 const bool bounded = args.first() == QLatin1String(
"init") ||
399 args.first() == QLatin1String(
"add");
404 QString(),
nullptr, &err,
nullptr,
405 bounded ? kGitSetupTimeoutMs : -1);
410 if (bounded && rc == -1 && clock.elapsed() >= kGitSetupTimeoutMs) {
411 *note = tr(
"git %1 did not finish within %2 minutes in %3, and was "
414 .arg(kGitSetupTimeoutMs / 60000)
417 *note = tr(
"git %1 failed in %2: %3").arg(args.first(), dir, err.trimmed());
423 QString *note) ->
bool {
424 const QString path = blocksGit(dir, files);
425 if (path.isEmpty()) {
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 "
435 .arg(QDir::toNativeSeparators(path));
441 QString *note) ->
bool {
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);
450 QStringList files{QFileInfo(gpgIdFile).fileName()};
451 if (!sigFile.isEmpty()) {
452 files << QFileInfo(sigFile).fileName();
459 const QStringList add =
460 QStringList{QStringLiteral(
"add"), QStringLiteral(
"--")} + files;
461 if (!run({QStringLiteral(
"init")}) || !run(add)) {
464 return run(commitArgs(git, s) +
465 QStringList{QStringLiteral(
"-m"),
466 QStringLiteral(
"Added .gpg-id using QtPass."),
467 QStringLiteral(
"--")} +
472 QString *note) ->
bool {
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);
483 const QDir base(dir);
488 {QStringLiteral(
"*.gpg"), QStringLiteral(
".gpg-id"),
489 QStringLiteral(
".gpg-id.sig")},
491 for (
const QString &path : found) {
492 files << base.relativeFilePath(path);
497 if (!run({QStringLiteral(
"init")})) {
500 if (!files.isEmpty() &&
501 !run(QStringList{QStringLiteral(
"add"), QStringLiteral(
"--")} + files)) {
504 return run(commitArgs(git, s) +
505 QStringList{QStringLiteral(
"--allow-empty"), QStringLiteral(
"-m"),
506 QStringLiteral(
"Added password store using QtPass.")});
512 git.setWorkingDirectory(dir);
513 git.setProcessEnvironment(gitEnvironment(dir, s));
514 for (
const char *key : {
"user.name",
"user.email"}) {
517 {QStringLiteral(
"config"),
518 QStringLiteral(
"--get"),
519 QString::fromLatin1(key)},
520 QString(), &out,
nullptr) != 0 ||
521 out.trimmed().isEmpty()) {
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.
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,...
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().
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...
static void requireExplicitBareRepository(QProcessEnvironment &env)
Make git in env refuse a folder that is merely laid out as a bare repository (safe....
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...
static auto mkpathForStore(const QString &path) -> bool
Create path and any missing parents as pass would.
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.
QString passSigningKey
GPG key used to sign .gpg-id files.
bool usePass
Use the pass CLI (true) or native git/gpg.
Stores GPG key info including validity, creation date, and more.
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...