19#include <QCoreApplication>
27#include <QRandomGenerator>
28#include <QRegularExpression>
31#include <QTemporaryDir>
52auto fallbackCharset(
const QString &input,
const QString &fallback) -> QString {
53 return input.isEmpty() ? fallback : input;
57 int sel = passConfig.selected;
60 return fallbackCharset(
61 passConfig.Characters[sel],
71void mergeIntoWslenv(QProcessEnvironment &env,
const QStringList &names) {
72 QStringList parts = env.value(QStringLiteral(
"WSLENV"))
73 .split(QLatin1Char(
':'), Qt::SkipEmptyParts);
74 for (
const QString &name : names) {
75 if (!parts.contains(name)) {
79 env.insert(QStringLiteral(
"WSLENV"), parts.join(QLatin1Char(
':')));
115 const QStringList wslenvVars = {
116 QStringLiteral(
"PASSWORD_STORE_DIR/p"),
117 QStringLiteral(
"PASSWORD_STORE_SIGNING_KEY/u"),
118 QStringLiteral(
"PASSWORD_STORE_GENERATED_LENGTH/u"),
119 QStringLiteral(
"PASSWORD_STORE_CHARACTER_SET/u"),
120 QStringLiteral(
"PASSWORD_STORE_GPG_OPTS/u"),
121 QStringLiteral(
"GIT_CEILING_DIRECTORIES/p"),
122 QStringLiteral(
"GIT_LITERAL_PATHSPECS/u")};
123 mergeIntoWslenv(
env, wslenvVars);
127 const QStringList &args,
bool readStdout,
133 const QStringList &args, QString input,
134 bool readStdout,
bool readStderr) {
138 readStdout, readStderr);
144 static const QStringList secretOptions{
145 QStringLiteral(
"--passphrase"), QStringLiteral(
"--override-session-key")};
148 for (
const QString &arg : args) {
150 out << QStringLiteral(
"<redacted>");
154 if (arg.startsWith(QStringLiteral(
"otpauth://"))) {
155 out << QStringLiteral(
"<redacted>");
158 if (arg.startsWith(QStringLiteral(
"--passphrase=")) ||
159 arg.startsWith(QStringLiteral(
"--override-session-key="))) {
160 out << arg.left(arg.indexOf(u
'=') + 1) + QStringLiteral(
"<redacted>");
163 hide = secretOptions.contains(arg);
180 if (QFile(QStringLiteral(
"/usr/local/MacGPG2/bin")).exists())
181 env.insert(QStringLiteral(
"PATH"),
182 QStringLiteral(
"/usr/local/MacGPG2/bin:") +
183 env.value(QStringLiteral(
"PATH")));
185 const QString currentPath =
env.value(QStringLiteral(
"PATH"));
186 if (!currentPath.split(
':', Qt::SkipEmptyParts)
187 .contains(QStringLiteral(
"/usr/local/bin"))) {
188 env.insert(QStringLiteral(
"PATH"),
189 currentPath.isEmpty()
190 ? QStringLiteral(
"/usr/local/bin")
191 : QStringLiteral(
"/usr/local/bin:") + currentPath);
198 const QString inheritedHome = QProcessEnvironment::systemEnvironment().value(
199 QStringLiteral(
"GNUPGHOME"));
200 const auto useInheritedHome = [
this, &inheritedHome]() {
201 if (inheritedHome.isEmpty()) {
202 env.remove(QStringLiteral(
"GNUPGHOME"));
204 env.insert(QStringLiteral(
"GNUPGHOME"), inheritedHome);
211 absHome.makeAbsolute();
212 if (absHome.exists()) {
213 env.insert(QStringLiteral(
"GNUPGHOME"), absHome.path());
215 if (inheritedHome.isEmpty()) {
216 qCWarning(lcQtPass) <<
"gpgHome" << absHome.path()
217 <<
"does not exist; using the default GnuPG home";
218 emit
statusMsg(tr(
"Configured GPG home %1 does not exist, using the "
220 .arg(absHome.path()),
224 <<
"gpgHome" << absHome.path() <<
"does not exist; using GNUPGHOME"
225 << inheritedHome <<
"from the environment";
226 emit
statusMsg(tr(
"Configured GPG home %1 does not exist, using "
227 "GNUPGHOME %2 from the environment")
228 .arg(absHome.path(), inheritedHome),
246 emit
critical(tr(
"Invalid password length"),
247 tr(
"Can't generate password with zero length."));
256 args.append(
"--secure");
258 args.append(
m_settings.avoidCapitals ?
"--no-capitalize" :
"--capitalize");
259 args.append(
m_settings.avoidNumbers ?
"--no-numerals" :
"--numerals");
261 args.append(
"--symbols");
263 args.append(QString::number(length));
266 static const QRegularExpression literalNewLines{
"[\\n\\r]"};
267 passwd.remove(literalNewLines);
270 qCDebug(lcQtPass) <<
"pwgen fail";
275 tr(
"Password generation failed"),
276 tr(
"Could not run pwgen (\"%1\"). Check the pwgen program in the "
277 "settings, or turn \"Use pwgen\" off.")
283 const QString cs = fallbackCharset(
286 if (cs.length() > 0) {
290 tr(
"No characters chosen"),
291 tr(
"Can't generate password, there are no characters to choose from "
292 "set in the configuration!"));
300 gpgExecutable.isEmpty() ? QStringLiteral(
"gpg") : gpgExecutable;
305 static const QRegularExpression versionRegex(
306 QStringLiteral(R
"(gpg \(GnuPG\) (\d+)\.(\d+))"));
307 QRegularExpressionMatch match = versionRegex.match(out);
308 if (!match.hasMatch()) {
311 int major = match.captured(1).toInt();
312 int minor = match.captured(2).toInt();
313 return major > 2 || (major == 2 && minor >= 1);
319 return QStringLiteral(
"%echo Generating a default key\n"
321 "Key-Curve: Ed25519\n"
322 "Subkey-Type: ECDH\n"
323 "Subkey-Curve: Curve25519\n"
325 "Name-Comment: QtPass\n"
332 return QStringLiteral(
"%echo Generating a default key\n"
336 "Name-Comment: QtPass\n"
345auto resolveWslGpgconfPath(
const QString &lastPart) -> QString {
346 qsizetype lastSep = lastPart.lastIndexOf(
'/');
348 lastSep = lastPart.lastIndexOf(
'\\');
351 return lastPart.left(lastSep + 1) +
"gpgconf";
353 return QStringLiteral(
"gpgconf");
356QString findGpgconfInGpgDir(
const QString &gpgPath) {
357 QFileInfo gpgInfo(gpgPath);
358 if (!gpgInfo.isAbsolute()) {
362 QDir dir(gpgInfo.absolutePath());
365 QFileInfo candidateExe(dir.filePath(
"gpgconf.exe"));
366 if (candidateExe.isExecutable()) {
367 return candidateExe.filePath();
371 QFileInfo candidate(dir.filePath(
"gpgconf"));
372 if (candidate.isExecutable()) {
373 return candidate.filePath();
382 if (gpgPath.trimmed().isEmpty()) {
383 return {
"gpgconf", {}};
390 if (!QFileInfo(wsl->command).fileName().startsWith(
"gpg")) {
391 return {
"gpgconf", {}};
393 const auto gpgconf = wsl->with(resolveWslGpgconfPath(wsl->command));
394 return {gpgconf.launcher, gpgconf.argv({})};
397 const QStringList parts = QProcess::splitCommand(gpgPath);
398 if (parts.isEmpty()) {
399 return {
"gpgconf", {}};
401 const QString &first = parts.first();
402 if (QFileInfo(first).fileName().compare(
"wsl", Qt::CaseInsensitive) == 0 ||
403 QFileInfo(first).fileName().compare(
"wsl.exe", Qt::CaseInsensitive) ==
405 return {
"gpgconf", {}};
408 if (!first.contains(
'/') && !first.contains(
'\\')) {
409 return {
"gpgconf", {}};
412 QString gpgconfPath = findGpgconfInGpgDir(first);
413 if (!gpgconfPath.isEmpty()) {
414 return {std::move(gpgconfPath), {}};
417 return {
"gpgconf", {}};
422 if (gpgPath.isEmpty()) {
427 QMetaObject::invokeMethod(
433 Qt::QueuedConnection);
440 QStringList killArgs = resolvedGpgconf.
arguments;
441 killArgs <<
"--kill";
442 killArgs <<
"gpg-agent";
445 qCWarning(lcQtPass) <<
"Failed to kill gpg-agent";
449 std::move(batch),
true,
true);
461auto keyOfLine(
const QString &line) -> QString {
462 QString key = line.trimmed();
463 if (key.endsWith(QLatin1Char(
'!'))) {
466 if (key.startsWith(QLatin1String(
"0x"), Qt::CaseInsensitive)) {
469 static const QRegularExpression grouped(
470 QStringLiteral(
"^[0-9A-Fa-f]{4}(?:\\s+[0-9A-Fa-f]{4})+$"));
471 if (grouped.match(key).hasMatch()) {
472 static const QRegularExpression space(QStringLiteral(
"\\s"));
474 if (key.size() != 40 && key.size() != 64) {
478 static const QRegularExpression hex(QStringLiteral(
479 "^(?:[0-9A-Fa-f]{8}|[0-9A-Fa-f]{16}|[0-9A-Fa-f]{40}|[0-9A-Fa-f]{64})$"));
480 return hex.match(key).hasMatch() ? key.toUpper() : QString();
500auto keyBlocks(
const QString &listing) -> QList<KeyBlock> {
501 QList<KeyBlock> blocks;
502 bool expectPrimary =
false;
503 const QStringList lines =
505 for (
const QString &line : lines) {
506 const QStringList f = line.split(QLatin1Char(
':'));
507 const QString type = f.value(0);
508 if (type == QLatin1String(
"pub")) {
509 blocks.append(KeyBlock{});
510 blocks.last().keyIds << f.value(4).toUpper();
511 expectPrimary =
true;
512 }
else if (blocks.isEmpty()) {
514 }
else if (type == QLatin1String(
"sub")) {
515 blocks.last().keyIds << f.value(4).toUpper();
516 expectPrimary =
false;
517 }
else if (type == QLatin1String(
"fpr")) {
518 const QString fpr = f.value(9).toUpper();
519 blocks.last().fprs << fpr;
521 blocks.last().primary = fpr;
522 expectPrimary =
false;
524 }
else if (type == QLatin1String(
"uid") && blocks.last().name.isEmpty()) {
537auto holderName(
const KeyBlock &block) -> QString {
538 const QString
id = block.primary.size() == 64 ? block.primary.left(16)
539 : block.primary.right(16);
540 return block.name.isEmpty() ? id
541 : QStringLiteral(
"%1 (%2)").arg(block.name,
id);
551 {QStringLiteral(
"--batch"), QStringLiteral(
"--no-tty"),
552 QStringLiteral(
"--with-colons"), QStringLiteral(
"--with-fingerprint"),
553 QStringLiteral(
"--with-subkey-fingerprint"),
554 QStringLiteral(
"--list-keys")},
559 QString *out, QString *err) ->
int {
564 QStringList{QStringLiteral(
"--armor"), QStringLiteral(
"--export")} + keys,
565 QString(), out, err);
569 const std::optional<QHash<QString, QStringList>> held =
571 if (held && held->isEmpty()) {
574 emit
critical(held ? tr(
"A recipient key is held twice")
575 : tr(
"Cannot check the recipient keys"),
582 for (
const UserInfo &user : users) {
584 lines << user.key_id;
591 -> std::optional<QHash<QString, QStringList>> {
592 if (std::none_of(lines.cbegin(), lines.cend(), [](
const QString &line) {
593 return !keyOfLine(line).isEmpty();
595 return QHash<QString, QStringList>();
603 return QHash<QString, QStringList>();
612 -> QHash<QString, QStringList> {
617 const QList<KeyBlock> blocks = keyBlocks(listing);
618 QHash<QString, QStringList> held;
619 for (
const QString &line : lines) {
620 const QString key = keyOfLine(line);
624 const bool isId = key.size() == 8 || key.size() == 16;
626 for (
const KeyBlock &block : blocks) {
629 block.keyIds.cbegin(), block.keyIds.cend(),
630 [&key](
const QString &
id) { return id.endsWith(key); })
631 : block.fprs.contains(key);
633 named << holderName(block);
636 if (named.size() > 1) {
637 held.insert(line, named);
644 const std::optional<QHash<QString, QStringList>> &held) -> QString {
646 return tr(
"gpg could not list the keyring, so QtPass cannot tell whether "
647 "each key ID and fingerprint in the recipient list names one "
648 "key. Nothing was encrypted.");
650 QStringList lines = held->keys();
653 for (
const QString &line : std::as_const(lines)) {
654 parts << tr(
"%1 is held by more than one key: %2")
655 .arg(line, held->value(line).join(QStringLiteral(
", ")));
657 return parts.join(QStringLiteral(
"\n")) + QStringLiteral(
"\n\n") +
658 tr(
"gpg may encrypt to any of them, so nothing is encrypted to this "
659 "list. A key that holds someone else's key as a subkey was "
660 "made to do so: look at it, and delete it if you did not expect "
672 {QStringLiteral(
"--batch"), QStringLiteral(
"--no-tty"),
673 QStringLiteral(
"--decrypt"), QStringLiteral(
"--list-only"),
674 QStringLiteral(
"--max-output"), QStringLiteral(
"1"),
675 QStringLiteral(
"--status-fd=1"),
676 QStringLiteral(
"--keyid-format=long"), QStringLiteral(
"--"),
677 Executor::translatePathForWsl(path, m_settings.gpgExecutable)},
678 QString(), &status) != 0) {
681 static const QRegularExpression encTo(
682 QStringLiteral(
"^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
684 const QStringList lines =
686 for (
const QString &line : lines) {
687 const QRegularExpressionMatch match = encTo.match(line);
688 if (match.hasMatch()) {
689 ids << match.captured(1).toUpper();
696 static const QRegularExpression bareAddress(
697 QStringLiteral(
"^[^=<>@*+#&\\s][^<>@\\s]*@[^<>@\\s]+$"));
698 return bareAddress.match(line).hasMatch()
699 ? QLatin1Char(
'<') + line + QLatin1Char(
'>')
708 -> std::optional<QStringList> {
709 if (recipients.isEmpty()) {
712 QTemporaryDir scratch;
713 if (!scratch.isValid()) {
716 const QString &gpg =
m_settings.gpgExecutable;
718 scratch.filePath(QStringLiteral(
"probe.gpg")), gpg);
721 QStringList args{QStringLiteral(
"--batch"),
722 QStringLiteral(
"--no-tty"),
723 QStringLiteral(
"--yes"),
724 QStringLiteral(
"--quiet"),
725 QStringLiteral(
"--no-throw-keyids"),
726 QStringLiteral(
"--no-auto-key-locate"),
727 QStringLiteral(
"--no-encrypt-to"),
728 QStringLiteral(
"--output"),
730 QStringLiteral(
"--encrypt")};
731 for (
const QString &recipient : recipients) {
741 {QStringLiteral(
"--batch"), QStringLiteral(
"--no-tty"),
742 QStringLiteral(
"--decrypt"), QStringLiteral(
"--list-only"),
743 QStringLiteral(
"--max-output"), QStringLiteral(
"1"),
744 QStringLiteral(
"--status-fd=1"),
745 QStringLiteral(
"--keyid-format=long"), QStringLiteral(
"--"), probe},
746 QString(), &status) != 0) {
747 return QStringList();
749 static const QRegularExpression encTo(
750 QStringLiteral(
"^\\[GNUPG:\\] ENC_TO ([0-9A-Fa-f]{16})(?: |$)"));
752 const QStringList lines =
754 for (
const QString &line : lines) {
755 const QRegularExpressionMatch match = encTo.match(line);
756 if (match.hasMatch()) {
757 ids << match.captured(1).toUpper();
764 QStringList args = {
"--no-tty",
"--with-colons",
"--with-fingerprint"};
765 args.append(secret ?
"--list-secret-keys" :
"--list-keys");
767 for (
const QString &keystring : std::as_const(keystrings)) {
768 if (!keystring.isEmpty()) {
769 args.append(keystring);
780 return listKeys(QStringList(keystring), secret);
785auto containsAny(
const QString &str,
const QStringList &patterns) ->
bool {
786 for (
const QString &p : patterns) {
787 if (str.contains(p)) {
795auto containsAnyCaseInsensitive(
const QString &str,
const QStringList &patterns)
797 const QString lower = str.toLower();
798 for (
const QString &p : patterns) {
799 if (lower.contains(p)) {
810 if (containsAny(err, {QStringLiteral(
"[GNUPG:] KEYEXPIRED"),
811 QStringLiteral(
"[GNUPG:] INV_RECP 5 ")}))
812 return QCoreApplication::translate(
813 "Pass",
"Encryption failed: GPG key has expired. Please renew or "
815 if (containsAny(err, {QStringLiteral(
"[GNUPG:] KEYREVOKED"),
816 QStringLiteral(
"[GNUPG:] INV_RECP 4 ")}))
817 return QCoreApplication::translate(
818 "Pass",
"Encryption failed: GPG key has been revoked.");
819 if (containsAny(err, {QStringLiteral(
"[GNUPG:] NO_PUBKEY"),
820 QStringLiteral(
"[GNUPG:] INV_RECP")}))
821 return QCoreApplication::translate(
822 "Pass",
"Encryption failed: recipient GPG key not found or invalid. "
823 "Check that the key ID in .gpg-id is correct and imported.");
824 if (err.contains(QStringLiteral(
"[GNUPG:] FAILURE")))
825 return QCoreApplication::translate(
826 "Pass",
"Encryption failed. Check that your GPG key is valid.");
829 if (containsAnyCaseInsensitive(err, {QLatin1String(
"key has expired"),
830 QLatin1String(
"key expired")}))
831 return QCoreApplication::translate(
832 "Pass",
"Encryption failed: GPG key has expired. Please renew or "
834 if (containsAnyCaseInsensitive(err, {QLatin1String(
"key has been revoked"),
835 QLatin1String(
"revoked")}))
836 return QCoreApplication::translate(
837 "Pass",
"Encryption failed: GPG key has been revoked.");
843 if (containsAnyCaseInsensitive(err, {QLatin1String(
"unusable public key")}))
844 return QCoreApplication::translate(
845 "Pass",
"Encryption failed: a recipient's GPG key cannot be used. It "
846 "may have expired or been revoked, have no encryption subkey, "
847 "or not be trusted; gpg's message below says which.");
848 if (containsAnyCaseInsensitive(err, {QLatin1String(
"no public key"),
849 QLatin1String(
"no secret key")}))
850 return QCoreApplication::translate(
851 "Pass",
"Encryption failed: recipient GPG key not found or invalid. "
852 "Check that the key ID in .gpg-id is correct and imported.");
853 if (containsAnyCaseInsensitive(err, {QLatin1String(
"encryption failed")}))
854 return QCoreApplication::translate(
855 "Pass",
"Encryption failed. Check that your GPG key is valid.");
861 const QString &err) {
862 auto pid =
static_cast<PROCESS>(id);
897 const QString &err) {
911 emit
critical(tr(
"Saved, not committed"),
912 tr(
"The entry is saved in the store, but recording it "
913 "in git failed. What was reported:\n\n%1")
914 .arg(err.trimmed()));
927 QStringList humanLines;
928 for (
const QString &line : err.split(
'\n')) {
929 QString cleanedLine = line;
930 cleanedLine.remove(
'\r');
931 if (!cleanedLine.startsWith(QLatin1String(
"[GNUPG:]")))
932 humanLines.append(cleanedLine);
934 return humanLines.join(
'\n');
940 return humanErr.isEmpty() ? friendly : friendly +
"\n\n" + humanErr;
944 const QString &err) {
955 using Signal = void (
Pass::*)(
const QString &,
const QString &);
956 static const QHash<int, Signal> kSignals{
972 if (
const Signal signal = kSignals.value(pid,
nullptr)) {
973 (this->*signal)(out, err);
981 env.insert(name, value);
985 setEnvVar(QStringLiteral(
"PASSWORD_STORE_SIGNING_KEY"),
992 setEnvVar(QStringLiteral(
"GIT_LITERAL_PATHSPECS"), QStringLiteral(
"1"));
995 setEnvVar(QStringLiteral(
"PASSWORD_STORE_GENERATED_LENGTH"),
996 QString::number(passConfig.
length));
998 setEnvVar(QStringLiteral(
"PASSWORD_STORE_CHARACTER_SET"),
999 effectiveCharset(passConfig));
1004 static const QRegularExpression whitespace(QStringLiteral(
"\\s+"));
1005 QStringList gpgOpts = QProcessEnvironment::systemEnvironment()
1006 .value(QStringLiteral(
"PASSWORD_STORE_GPG_OPTS"))
1007 .split(whitespace, Qt::SkipEmptyParts);
1009 setEnvVar(QStringLiteral(
"PASSWORD_STORE_GPG_OPTS"),
1010 gpgOpts.join(QLatin1Char(
' ')));
1025 setEnvVar(QStringLiteral(
"GIT_DIR"), QString());
1026 setEnvVar(QStringLiteral(
"GIT_WORK_TREE"), QString());
1028 setEnvVar(QStringLiteral(
"GIT_CEILING_DIRECTORIES"),
1029 qEnvironmentVariable(
"GIT_CEILING_DIRECTORIES"));
1031 const auto variables =
1033 for (
const auto &[name, value] : variables) {
1044 QStringList gitConfig{QStringLiteral(
"GIT_CONFIG_COUNT/u")};
1045 if (
env.contains(QStringLiteral(
"GIT_CONFIG_PARAMETERS"))) {
1046 gitConfig << QStringLiteral(
"GIT_CONFIG_PARAMETERS/u");
1048 const int gitConfigCount =
1049 env.value(QStringLiteral(
"GIT_CONFIG_COUNT")).toInt();
1050 for (
int i = 0; i < gitConfigCount; ++i) {
1051 gitConfig << QStringLiteral(
"GIT_CONFIG_KEY_%1/u").arg(i)
1052 << QStringLiteral(
"GIT_CONFIG_VALUE_%1/u").arg(i);
1054 mergeIntoWslenv(
env, gitConfig);
1070auto userAttributeLines(
const QString &existing,
const QString &marker)
1073 if (existing.isEmpty()) {
1076 const QStringList lines = existing.split(QLatin1Char(
'\n'));
1077 bool inBlock =
false;
1078 for (
const QString &line : lines) {
1079 if (line == marker) {
1084 if (line.startsWith(QStringLiteral(
"*.gpg ")) ||
1085 line.startsWith(QStringLiteral(
".gpg-id ")) ||
1086 line.startsWith(QStringLiteral(
".gpg-id.sig "))) {
1091 preserved += line + QLatin1Char(
'\n');
1093 while (preserved.endsWith(QStringLiteral(
"\n\n"))) {
1108 const QString gitDir =
1110 if (!QFileInfo(gitDir).isDir()) {
1122 static const QString marker =
1123 QStringLiteral(
"# QtPass: keep encrypted store files byte-for-byte");
1124 const QString block =
1125 marker + QStringLiteral(
"\n") +
1127 "*.gpg -text -filter -ident -working-tree-encoding\n"
1128 ".gpg-id -text -filter -ident -working-tree-encoding\n"
1129 ".gpg-id.sig -text -filter -ident -working-tree-encoding\n");
1131 const QString infoDir = gitDir + QStringLiteral(
"/info");
1132 const QString attrPath = infoDir + QStringLiteral(
"/attributes");
1135 QFile attr(attrPath);
1136 if (attr.exists()) {
1138 if (!attr.open(QIODevice::ReadOnly | QIODevice::Text)) {
1139 qCWarning(lcQtPass) <<
"Cannot read" << attrPath
1140 <<
"to pin attributes:" << attr.errorString();
1143 existing = QString::fromUtf8(attr.readAll());
1145 if (existing.contains(block)) {
1150 if (!QDir().mkpath(infoDir)) {
1151 qCWarning(lcQtPass) <<
"Cannot create" << infoDir <<
"to pin attributes";
1158 const QString preserved = userAttributeLines(existing, marker);
1160 QSaveFile out(attrPath);
1161 const QByteArray payload = (preserved + block).toUtf8();
1162 if (!out.open(QIODevice::WriteOnly | QIODevice::Text) ||
1163 out.write(payload) != payload.size() || !out.commit()) {
1164 qCWarning(lcQtPass) <<
"Cannot write" << attrPath
1165 <<
"to pin attributes:" << out.errorString();
1170 -> QProcessEnvironment {
1174 base.remove(QStringLiteral(
"GIT_DIR"));
1175 base.remove(QStringLiteral(
"GIT_WORK_TREE"));
1176 const auto variables =
1178 for (
const auto &[name, value] : variables) {
1179 base.insert(name, value);
1192constexpr auto kPathCase = Qt::CaseInsensitive;
1194constexpr auto kPathCase = Qt::CaseSensitive;
1198auto isAtOrUnder(
const QString &path,
const QString &dir,
1199 const QString &dirPrefix) ->
bool {
1200 return path.compare(dir, kPathCase) == 0 ||
1201 path.startsWith(dirPrefix, kPathCase);
1210 QString storePrefix;
1215auto gpgIdLookup(
const QString &for_file,
const QString &passStore)
1217 const QString normalizedFile = QDir::fromNativeSeparators(for_file);
1220 const QString storeDir =
1221 QDir::cleanPath(QDir::fromNativeSeparators(passStore));
1222 const QString storePrefix = storeDir.endsWith(QLatin1Char(
'/'))
1224 : storeDir + QLatin1Char(
'/');
1225 const QString cleanFile = QDir::cleanPath(normalizedFile);
1226 const bool insideStore = isAtOrUnder(cleanFile, storeDir, storePrefix);
1229 const QString fullPath =
1230 insideStore || (QDir::isAbsolutePath(cleanFile) &&
1231 !cleanFile.startsWith(QLatin1Char(
':')))
1233 : storePrefix + cleanFile;
1236 const bool isFolder =
1237 normalizedFile.endsWith(QLatin1Char(
'/')) || QFileInfo(fullPath).isDir();
1242 const QString folder =
1243 QDir::cleanPath(isFolder ? fullPath : QFileInfo(fullPath).absolutePath());
1244 QString start = folder;
1245 while (!QFileInfo::exists(start) &&
1246 isAtOrUnder(QDir::cleanPath(start), storeDir, storePrefix) &&
1247 QDir::cleanPath(start) != storeDir) {
1248 start = QFileInfo(start).absolutePath();
1250 return {QDir(start), folder, storeDir, storePrefix};
1257auto isOwnGpgId(
const QFileInfo &candidate) ->
bool {
1258 return candidate.isFile() && !candidate.isSymLink() &&
1259 !candidate.isJunction();
1265auto nearestGpgId(
const GpgIdLookup &lookup) -> std::optional<QString> {
1266 QDir dir = lookup.start;
1267 while (dir.exists() && isAtOrUnder(QDir::cleanPath(dir.absolutePath()),
1268 lookup.storeDir, lookup.storePrefix)) {
1269 const QFileInfo candidate(dir.absoluteFilePath(
".gpg-id"));
1270 if (isOwnGpgId(candidate)) {
1271 return candidate.absoluteFilePath();
1277 return std::nullopt;
1283 static QSet<QString> scopes;
1288 return QDir::cleanPath(QDir(
m_settings.passStore).absoluteFilePath(path));
1292 const QString store =
scopePath(QString());
1294 return std::any_of(scopes.cbegin(), scopes.cend(),
1295 [&store](
const QString &s) {
1296 return isAtOrUnder(s, store, store + QLatin1Char(
'/'));
1315 for (
auto it = scopes.begin(); it != scopes.end();) {
1316 it = isAtOrUnder(*it, root, root + QLatin1Char(
'/')) ? scopes.erase(it)
1330 <<
"Path spelled through the store root's link target, not as the "
1331 "store is configured; Pass operations expect the configured "
1340 tr(
"%1 is, or lies behind, a symbolic link or junction. What that "
1341 "points to is not part of the password store and is left alone.")
1342 .arg(QDir::toNativeSeparators(QDir::cleanPath(full)));
1349 if (
const std::optional<QString> inStore =
1351 if (relative !=
nullptr) {
1352 *relative = *inStore;
1357 tr(
"%1 is not inside the password store. Recipients are set for the "
1358 "store or a folder in it.")
1359 .arg(QDir::toNativeSeparators(QDir::cleanPath(folder))));
1373 const std::array<std::pair<QLatin1String, QString>, 6> markers{{
1376 {QLatin1String(
"rebase-merge"), tr(
"rebase")},
1379 {QLatin1String(
"rebase-apply"), tr(
"rebase")},
1382 {QLatin1String(
"MERGE_HEAD"), tr(
"merge")},
1385 {QLatin1String(
"CHERRY_PICK_HEAD"), tr(
"cherry-pick")},
1388 {QLatin1String(
"REVERT_HEAD"), tr(
"revert")},
1395 {QLatin1String(
"sequencer"), tr(
"cherry-pick or revert")},
1397 QStringList args{QStringLiteral(
"rev-parse")};
1398 for (
const auto &marker : markers) {
1399 args << QStringLiteral(
"--git-path") << marker.first;
1407 const QStringList paths = out.split(QLatin1Char(
'\n'), Qt::SkipEmptyParts);
1408 for (
int i = 0; i < paths.size() && i <
static_cast<int>(markers.size());
1410 const QString path = paths.at(i).trimmed();
1411 const QString full = QDir::isAbsolutePath(path)
1414 if (!QFileInfo::exists(full)) {
1419 return tr(
"The password store's Git repository is in the middle of a %1. "
1420 "Finish or abort it with Git before changing the password store, "
1421 "or what you change may be lost.")
1422 .arg(markers.at(
static_cast<size_t>(i)).second);
1432 tr(
"The password store is being updated (a Git pull is in progress). "
1433 "Wait until it has finished, then try again.");
1437 emit
critical(tr(
"Update in progress"), why);
1443 const QString &dir,
const QString &passStore,
1447 const auto done = qScopeGuard([
this] {
m_expectedList.reset(); });
1465 tr(
"The recipient list of this folder changed after the users dialog "
1466 "read it, for example through an update from Git. Nothing was "
1467 "written. Open the dialog again to see the new list.");
1470 emit
critical(tr(
"Recipients not changed"), why);
1480 tr(
"Another operation is still running. Wait until it has finished, "
1481 "then save the recipients again.");
1484 emit
critical(tr(
"Recipients not changed"), why);
1491 if (why.isEmpty()) {
1498 emit
critical(tr(
"Unfinished Git operation"), why);
1507 emit
critical(tr(
"Not part of the store"), why);
1513 return nearestGpgId(gpgIdLookup(for_file, passStore))
1515 QDir(QDir::fromNativeSeparators(passStore)).filePath(
".gpg-id"));
1525 QString recordError;
1526 const std::optional<QString> skipped =
1528 if (!skipped || (!except.isEmpty() &&
1529 QDir::cleanPath(*skipped) == QDir::cleanPath(except))) {
1533 if (!recordError.isEmpty()) {
1534 emit
critical(QCoreApplication::translate(
1535 "ImitatePass",
"Cannot check the recipient list"),
1536 QCoreApplication::translate(
1537 "ImitatePass",
"%1 Whether %2 was removed cannot be "
1538 "told, so nothing was encrypted.")
1539 .arg(recordError, QDir::toNativeSeparators(*skipped)));
1543 QCoreApplication::translate(
"ImitatePass",
"Recipient list missing"),
1544 QCoreApplication::translate(
1546 "The signed recipient list %1 is missing or is not a regular file. "
1547 "QtPass does not fall back to a parent folder's list for it: that "
1548 "list was not signed for this folder. If a link is under that name, "
1549 "remove it. Then open Users for that folder and save its "
1550 "recipients, which writes and signs a fresh list.")
1551 .arg(QDir::toNativeSeparators(*skipped)));
1556 QByteArray *contents, QString *why)
const ->
bool {
1557 if (!signer.verifyFile(gpgIdFile, contents)) {
1560 if (why !=
nullptr && !signer.refusal().isEmpty()) {
1561 *why = signer.refusal();
1571 if (why !=
nullptr) {
1572 *why = std::move(reason);
1580 const QFileInfo candidate(dir + QStringLiteral(
"/.gpg-id"));
1581 if (isOwnGpgId(candidate)) {
1587 if (candidate.isSymLink() || candidate.isJunction()) {
1588 return SkippedWalk{candidate.absoluteFilePath(), QString()};
1594 const std::optional<bool> seen =
1599 ? tr(
"The generation record of the recipient lists "
1604 return SkippedWalk{candidate.absoluteFilePath(), QString()};
1606 return std::nullopt;
1611 -> std::optional<QString> {
1612 const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
1616 QStringList climbed;
1620 const auto answer = [&climbed, walks, recordError](
1621 std::optional<QString> skipped, QString why) {
1623 if (walks !=
nullptr) {
1624 for (
const QString &folder : std::as_const(climbed)) {
1625 walks->insert(folder, {skipped, why});
1628 if (recordError !=
nullptr && !why.isEmpty()) {
1629 *recordError = std::move(why);
1638 QString dir = lookup.folder;
1639 while (dir.startsWith(lookup.storePrefix, kPathCase)) {
1640 if (walks !=
nullptr) {
1641 if (
const auto known = walks->constFind(dir);
1642 known != walks->constEnd()) {
1643 return answer(known->skipped, known->recordError);
1647 if (
const std::optional<SkippedWalk> found =
gpgIdVerdictIn(dir)) {
1648 return answer(found->skipped, found->recordError);
1650 const QString parent = QDir::cleanPath(QFileInfo(dir).absolutePath());
1651 if (parent == dir) {
1656 return answer(std::nullopt, QString());
1661 const GpgIdLookup lookup = gpgIdLookup(forFile, passStore);
1665 QStringList climbed;
1666 const auto answer = [&climbed, walks](std::optional<QString> linked) {
1667 if (walks !=
nullptr) {
1668 for (
const QString &folder : std::as_const(climbed)) {
1669 walks->insert(folder, linked);
1676 QDir dir = lookup.start;
1677 while (dir.exists()) {
1678 const QString here = QDir::cleanPath(dir.absolutePath());
1679 if (!isAtOrUnder(here, lookup.storeDir, lookup.storePrefix)) {
1682 if (walks !=
nullptr) {
1684 if (
const auto known = walks->constFind(here);
1685 known != walks->constEnd()) {
1686 return answer(std::optional<QString>(*known));
1690 const QFileInfo candidate(dir.absoluteFilePath(
".gpg-id"));
1691 if (isOwnGpgId(candidate)) {
1692 return answer(std::nullopt);
1694 if (candidate.isSymLink() || candidate.isJunction()) {
1695 return answer(candidate.absoluteFilePath());
1701 return answer(std::nullopt);
1709 const QByteArray &contents,
const QString &gpgIdPath,
1712 RecipientsForEditing result;
1715 result.state = RecipientsForEditing::State::Verified;
1721 result.state = RecipientsForEditing::State::VerifiedRollback;
1723 result.warning = why;
1733 result.state = RecipientsForEditing::State::Rejected;
1735 Pass::tr(
"%1 Nothing is preselected: saving would sign whatever is "
1736 "in it. Select the recipients yourself.")
1748 const QString folder = dir.isEmpty() ? QString() : dir;
1749 const QString gpgIdPath =
getGpgIdPath(folder, passStore);
1760 const QFileInfo info(gpgIdPath);
1761 if (!info.exists() && !info.isSymLink()) {
1770 tr(
"%1 cannot be read as a recipient list (a regular file of at "
1771 "most %2), so nothing is preselected. Check it before choosing "
1772 "recipients here: OK writes a new list over it.")
1780 if (!misread.isEmpty()) {
1783 tr(
"pass reads %1 differently from this dialog (%2), so it may "
1784 "encrypt to recipients not shown here. QtPass will not encrypt "
1785 "with it through pass: check the recipients, then OK writes the "
1787 .arg(gpgIdPath, misread);
1791 QString recordError;
1792 if (
const std::optional<QString> skipped =
1800 recordError.isEmpty()
1801 ? tr(
"The recipient list %1 is missing or is not a regular file, "
1802 "so nothing is preselected: the list of a parent folder was "
1803 "not signed for this one. Select this folder's recipients "
1804 "yourself; OK writes and signs a fresh list.")
1806 : tr(
"%1 Nothing is preselected: whether %2 was removed cannot "
1808 .arg(recordError, *skipped);
1811 if (!QFileInfo::exists(gpgIdPath)) {
1817 QByteArray contents;
1818 if (!signer.
verifyFile(gpgIdPath, &contents)) {
1821 tr(
"The recipient list %1 does not verify against the signing key, "
1822 "so nothing is preselected: saving would sign whatever is in it. "
1823 "Select the recipients yourself; OK writes and signs a fresh list.")
1830 return judgedRecipients(verdict, contents, gpgIdPath, why);
1835 const QString gpgIdPath =
getGpgIdPath(for_file, passStore);
1840 const std::optional<QByteArray> bytes =
1849 const QString &sourceName) -> QStringList {
1850 QStringList recipients;
1851 const QString text = QString::fromUtf8(contents);
1852 for (
const QString &line : text.split(QLatin1Char(
'\n'))) {
1853 QString recipient = line.split(QLatin1Char(
'#')).first().trimmed();
1854 if (recipient.isEmpty()) {
1860 qCWarning(lcQtPass) <<
"Skipping unusable recipient in" << sourceName
1861 <<
":" << recipient;
1864 recipients += recipient;
1870 if (contents.startsWith(
"\xEF\xBB\xBF")) {
1871 return tr(
"it starts with a byte-order mark");
1873 if (contents.contains(
'\0')) {
1874 return tr(
"it holds a NUL byte");
1876 if (contents.contains(
'\r')) {
1877 return tr(
"it has Windows line ends (a carriage return)");
1879 const QString text = QString::fromUtf8(contents);
1880 if (text.toUtf8() != contents) {
1881 return tr(
"it is not valid UTF-8");
1883 const QStringList lines = text.split(QLatin1Char(
'\n'));
1884 for (qsizetype i = 0; i < lines.size(); ++i) {
1885 const QString &line = lines.at(i);
1886 const QString recipient = line.left(line.indexOf(QLatin1Char(
'#')));
1887 for (
const QChar c : recipient) {
1889 if (c.isSpace() && c != QLatin1Char(
' ') && c != QLatin1Char(
'\t')) {
1890 return tr(
"line %1 holds whitespace other than blanks and tabs")
1894 const QString trimmed = recipient.trimmed();
1895 if (trimmed.startsWith(QLatin1Char(
'-'))) {
1896 return tr(
"line %1 starts with a dash").arg(i + 1);
1900 if (i == lines.size() - 1 && !trimmed.isEmpty()) {
1901 return tr(
"its last line has no line end");
1918 const quint32 rejectionThreshold = (1 + ~bound) % bound;
1921 randval = QRandomGenerator::system()->generate();
1922 }
while (randval < rejectionThreshold);
1924 return randval % bound;
1929 if (charset.isEmpty() || length == 0U) {
1933 for (
unsigned int i = 0; i < length; ++i) {
1934 out.append(charset.at(
static_cast<int>(
1943 const int seconds = (timeoutMs + 999) / 1000;
1944 return tr(
"Git pull did not finish within %n second(s); editing the entry "
static void seedStore(const QString &storeRoot)
Record every entry of a store the first time it is seen; later calls for the same store do nothing....
auto lastOutputLossless() const -> bool
Whether the stdout of the item whose finished() or error() is being emitted encodes back (toUtf8(),...
void dequeuing(int id, bool completes)
Emitted, synchronously, when the queue's head leaves it: just before it is started,...
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 translatePathForWsl(const QString &path, const QString &exe) -> QString
Translate a native path for a WSL-routed executable.
void execute(int id, const QString &app, const QStringList &args, bool readStdout, bool readStderr=true)
Queue a command without stdin input.
void drained()
Emitted once the last queued item is done and nothing runs or waits any more (isIdle()),...
void error(int id, int exitCode, const QString &output, const QString &errout)
Emitted instead of finished() when a queued process could not be started, had no executable configure...
void finished(int id, int exitCode, const QString &output, const QString &errout)
Emitted when a queued process exits normally, whatever its exit code; a non-zero code is the receiver...
void starting()
Emitted just before a queued process is started; the main window shows the busy indicator on it.
void setEnvironment(const QProcessEnvironment &env)
Set the environment passed to all child processes.
static auto parseWslCommand(const QString &app) -> std::optional< WslCommand >
Parse a configured executable as a WSL command.
static auto accept(const QString &gpgIdFile, const QByteArray &contents, const QString &storeRoot, QString *error=nullptr) -> Verdict
Decide about a verified list: its folder against where it sits, its generation against the remembered...
static auto seen(const QString &gpgIdFile, QString *error=nullptr) -> std::optional< bool >
Whether this device accepted or wrote a list at gpgIdFile before, of any generation: a headerless lis...
Verdict
The outcome of accept(). Only Accepted means the list may be used; the others say why not,...
@ Malformed
A header line malformed or duplicated.
@ Accepted
Folder, generation and record all agree; remembered.
@ RecordUnavailable
The record could not be read or written.
@ Rollback
Authentic and bound to this folder, but older than a generation this device accepted.
@ WrongFolder
Written for another folder of the store.
@ WrongStore
Written for another store (its store line names another id than this device knows the store by),...
@ Unbound
Older than a generation this device accepted and without a folder line: authentic,...
@ Conflict
The generation this device accepted last, but not the bytes: two devices saved at once (Git shows tha...
The detached signature on a store's .gpg-id: whether the configured signing key is usable,...
void setStoreRoot(const QString &root)
The store the lists and signatures this signer reads belong to.
auto enabled() const -> bool
Whether any signing key is configured at all.
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 verifyFile(const QString &gpgIdFile, QByteArray *contents) const -> bool
Read gpgIdFile and verify it against <file>.sig.
static auto keysFromSetting(const QString &passSigningKey) -> QStringList
Split the settings value into keys, upper-cased the way gpg prints fingerprints.
auto storeEnvironment() const -> QProcessEnvironment
The environment QtPass runs the store's processes in.
auto exportPublicKeys(const QString &gpg, const QStringList &keys, QString *out, QString *err) -> int
gpg --armor --export of keys, in the store's environment: the keyring keyLinesHeldTwice() reads.
void startingExecuteWrapper()
Emitted each time a queued process is about to start, and by the refusals that go on to emit processE...
virtual void beforeExecute(PROCESS id)
Hook invoked just before a wrapped command is dispatched.
void GenerateGPGKeys(QString batch)
Generate GPG keys using batch script.
static auto skippedGpgId(const QString &forFile, const QString &passStore, QString *recordError=nullptr, SkippedWalks *walks=nullptr) -> std::optional< QString >
The folder list getGpgIdPath() passed over on its way up to the one it returns, if it passed one over...
static QString getDefaultKeyTemplate(const QString &gpgExecutable={})
Get default key template for new GPG keys.
void finishedAnyWithPid(const QString &out, const QString &err, Enums::PROCESS pid)
A process of any kind finished successfully and its output cannot contain a secret.
void finishedInsert(const QString &out, const QString &err)
An Insert() succeeded: the entry is in the store and, with Git in use, committed.
void pinStoreGitAttributes()
Pin byte-for-byte Git attributes for the store's encrypted files.
virtual auto recipientArgument(const QString &line) const -> QString
The -r argument for one recipient line, as this backend's encryption hands it to gpg: the probe (encr...
AppSettings m_settings
Application settings snapshot injected at init() time.
static auto passReadsDifferently(const QByteArray &contents) -> QString
Why pass would read a .gpg-id differently from parseRecipients(), if it would.
static auto getGpgIdPath(const QString &for_file, const QString &passStore) -> QString
Get .gpg-id file path for a password file.
void handleProcessError(PROCESS pid, int exitCode, const QString &out, const QString &err)
Report a process that exited non-zero; called by finished().
virtual auto encryptionReaches(const QStringList &recipients) -> std::optional< QStringList >
The keys a gpg encryption to recipients reaches: a throwaway encryption outside the store,...
auto scopePath(const QString &path) const -> QString
path as an absolute, cleaned path, relative ones taken from the current store.
auto refusePendingPull() -> bool
Refuse a store change while a Git pull is still queued or running.
auto initIfUnchanged(const QString &path, const QList< UserInfo > &users, const QString &dir, const QString &passStore, const RecipientsForEditing &read) -> bool
Init(), but only while the list of dir still reads as the caller read it with recipientsForEditing().
void releaseAutoPush(const QString &folder)
Release the holds a clean re-encryption of folder covers: those for folder itself and everything unde...
QString m_reportedInsert
The entry of the insert whose report is going out; see reportedInsert().
void finishedGenerateGPGKeys(const QString &out, const QString &err)
GenerateGPGKeys() succeeded; the new key pair is in the keyring.
Enums::PROCESS PROCESS
Alias for Enums::PROCESS used throughout this class.
static auto describeKeyLinesHeldTwice(const std::optional< QHash< QString, QStringList > > &held) -> QString
A message naming each line keyLinesHeldTwice() found and what the user can do about it.
virtual auto generatePassword(unsigned int length, const QString &charset) -> QString
Generate random password.
void statusMsg(const QString &msg, int timeout)
Progress or a non-fatal problem worth a line in the status bar ("Creating backup commit",...
QProcessEnvironment env
The environment the store's processes run in: the system environment plus what updateEnv() sets (PASS...
auto unfinishedGitOperationReason() -> QString
The unfinished git operation in progress in the store, if any.
void GitPushAutomatic()
GitPush() for an automatic push, the one after a change. A backend that has to make the push later dr...
PathSpelling
How a path handed to refuseLinkedPath() is spelled.
@ Configured
As the store is configured or relative to it, the class's path rule. A path spelled through the targe...
virtual auto fullKeyListing(QString *listing) -> int
The whole public keyring as keyLinesHeldTwice() reads it.
auto boundedRandom(quint32 bound) -> quint32
Generate random number in range.
void insertFailed(const QString &err, bool written)
Emitted when an Insert() fails through a queued command, before the generic processErrorExit(): the p...
static auto gpgIdVerdictIn(const QString &dir) -> std::optional< SkippedWalk >
What skippedGpgId() concludes at one folder on its way up.
auto pushIsAutomatic() const -> bool
Whether the GitPush() running now is an automatic one.
static auto keyLinesHeldTwiceIn(const QStringList &lines, const QString &listing) -> QHash< QString, QStringList >
keyLinesHeldTwice() on a listing already made.
void emitProcessFinishedSignal(PROCESS pid, const QString &out, const QString &err)
Emit the signals for a process that exited with 0; called by finished() for everything but PASS_SHOW.
static bool gpgSupportsEd25519(const QString &gpgExecutable={})
Check if GPG supports Ed25519 encryption.
void refuseAsNotPartOfStore(const QString &why)
Refuse an operation on something that is not part of the store.
static auto maxOutputArgs() -> QStringList
The gpg options that enforce kMaxPlaintextBytes.
virtual auto storeGit(const QStringList &args, QString *out) -> bool
Run a git command in the store's repository, blocking.
Pass()
Construct a Pass instance.
virtual auto insertWritten(const QString &err) const -> bool
Whether the insert that just failed had put its entry in the store before a later step failed....
void holdAutoPush(const QString &scope)
Hold automatic pushes of the store that holds scope (autoPushHeld()): its re-encryption did not finis...
void finishedCopy(const QString &out, const QString &err)
A Copy() succeeded; the copy exists beside the original.
void finishedMove(const QString &out, const QString &err)
A Move() succeeded; the entry or folder is under its new name.
void executeWrapper(PROCESS id, const QString &app, const QStringList &args, bool readStdout=true, bool readStderr=true)
Execute external wrapper command.
void finishedShow(const QString &out, const QString &file, bool lossless=true)
Emitted when a Show() succeeds.
static auto resolveGpgconfCommand(const QString &gpgPath) -> ResolvedGpgconfCommand
Resolve the gpgconf command to kill agents.
static auto exactRecipientArg(const QString &line) -> QString
A bare mail address in gpg's exact form, <address>; any other line as written.
auto refuseLinkedPath(const QString &path, LinkScope scope=LinkScope::EntryAndParents, PathSpelling spelling=PathSpelling::Configured) -> bool
Refuse an operation on something that is, or lies behind, a symbolic link or NTFS junction inside the...
auto listKeys(QStringList keystrings, bool secret=false) -> QList< UserInfo >
List GPG keys matching patterns.
QQueue< QString > m_insertedEntries
The entries of the inserts counted in m_insertsPending, in queue order.
QHash< QString, SkippedWalk > SkippedWalks
SkippedWalk per absolute folder, for one check of many folders.
static auto enabledKeyLines(const QList< UserInfo > &users) -> QStringList
The enabled users' key IDs, as Init() writes them to .gpg-id.
void finishedGitPull(const QString &out, const QString &err)
git pull succeeded; entries may have changed on disk.
virtual void GitPush()=0
Push changes to remote Git repository.
bool m_expectedListRefused
Set when refuseChangedList() or refuseBusyForExpectedList() refused during initIfUnchanged().
void finishedGitPush(const QString &out, const QString &err)
git push succeeded.
auto recipientsForEditing(const QString &dir, const QString &passStore) -> RecipientsForEditing
The recipients a dialog may preselect for editing the list of dir.
static auto linkedGpgId(const QString &forFile, const QString &passStore, LinkedWalks *walks=nullptr) -> std::optional< QString >
The link or junction under the name .gpg-id that getGpgIdPath() skips on its way up from forFile,...
auto refuseBusyForExpectedList() -> bool
Refuse an Init() under initIfUnchanged() while the executor has work queued or running,...
auto keyLinesHeldTwice(const QStringList &lines) -> std::optional< QHash< QString, QStringList > >
The key ID and fingerprint lines of a recipient list that more than one key block holds,...
Executor exec
Internal command executor for queuing and running subprocesses.
std::optional< ExpectedList > m_expectedList
Set during initIfUnchanged().
void processErrorExit(int exitCode, const QString &err)
An operation ended in failure: its process exited non-zero, could not be started or crashed,...
auto verifySignedList(const GpgIdSigner &signer, const QString &gpgIdFile, QByteArray *contents, QString *why) const -> bool
Whether gpgIdFile is a signed list QtPass accepts: its signature verifies (GpgIdSigner::verifyFile())...
void init(const AppSettings &settings)
Initialize the Pass instance with a settings snapshot.
auto refuseChangedList() -> bool
Refuse an Init() under initIfUnchanged() when the folder's list no longer reads as the caller read it...
bool m_pushIsAutomatic
Set while GitPushAutomatic() runs GitPush().
auto formatInsertError(const QString &friendly, const QString &err) -> QString
Put the translated reason for a failed insert above what gpg itself printed, leaving out the machine-...
auto entryReaders(const QString &path) -> QStringList
The long key IDs an entry is encrypted to, as gpg lists them without anyone's secret key (ENC_TO).
void finishedGitInit(const QString &out, const QString &err)
git init in the store succeeded; the store is a repository now and the tree is re-read.
static auto withoutStatusLines(const QString &err) -> QString
gpg's stderr without its machine-readable [GNUPG:] lines (and without carriage returns),...
static auto heldScopes() -> QSet< QString > &
The folders (cleaned absolute paths) whose re-encryption did not finish, for every store and both bac...
auto withCurrentGitPin(QProcessEnvironment base) const -> QProcessEnvironment
base with GIT_DIR and GIT_WORK_TREE as the store is now (Util::gitStoreVariables()),...
void setEnvVar(const QString &name, const QString &value)
Set or remove an environment variable.
static auto loggableArgs(const QStringList &args) -> QStringList
The arguments as they may appear in the debug log: the value of --passphrase and friends,...
auto autoPushHeld() const -> bool
Whether automatic pushes of the current store are held because its last re-encryption did not finish ...
static auto pullTimedOut(int timeoutMs) -> QString
The status-bar text for a blocking pull stopped at its deadline.
void updateEnv()
Update environment for subprocesses.
void finishedInit(const QString &out, const QString &err)
An Init() succeeded: the folder's .gpg-id holds the new recipient list.
QHash< QString, std::optional< QString > > LinkedWalks
void idle()
Nothing of the store's runs or waits any more (isIdle()).
virtual void finished(int id, int exitCode, const QString &out, const QString &err)
Handle process completion.
void critical(const QString &title, const QString &message)
Something went wrong that the user has to be told about in a dialog, such as a refused path or a fail...
auto refuseSkippedGpgId(const QString &file, bool signing, const QString &except=QString(), SkippedWalks *walks=nullptr) -> bool
With signing on, refuse to encrypt file when the lookup passed over its folder's own list (skippedGpg...
auto refuseKeyLinesHeldTwice(const QStringList &lines) -> bool
Refuse, with critical(), a recipient list with a line that more than one key block holds (keyLinesHel...
void generateGPGKeysFailed(const QString &err)
Emitted when GPG key generation fails, alongside the generic processErrorExit(); lets the keygen dial...
static constexpr qint64 kMaxPlaintextBytes
Most bytes of plaintext a gpg decryption may produce.
int m_insertsPending
Inserts that have started queueing but not yet reported; see queueInsert.
static auto getRecipientList(const QString &for_file, const QString &passStore) -> QStringList
Get list of recipients for a password file.
virtual void Init(QString path, const QList< UserInfo > &users)=0
Initialize new password store.
LinkScope
What refuseLinkedPath() judges.
@ EntryAndParents
The entry itself and every folder above it in the store.
void finishedRemove(const QString &out, const QString &err)
A Remove() succeeded; the entry or folder is gone from the store.
auto refuseUnfinishedGitOperation() -> bool
Refuse to change the store while git is mid-rebase, -merge, -cherry-pick or -revert.
QQueue< QString > m_pendingShows
Files of the Show() calls still in flight, oldest first.
static auto parseRecipients(const QByteArray &contents, const QString &sourceName) -> QStringList
Parse the contents of a .gpg-id: one recipient per line, # starts a comment, unusable lines are logge...
auto refuseFolderOutsideStore(const QString &folder, QString *relative=nullptr) -> bool
Refuse recipients for a folder outside the store, as pass refuses a path with .. in it.
auto generateRandomPassword(const QString &charset, unsigned int length) -> QString
Generate random password from charset.
static auto storeRelativePath(const QString &storeRoot, const QString &candidate) -> std::optional< QString >
Where candidate lies in the store, judged as isPathInStore() judges it.
static auto isTargetSpelled(const QString &storeRoot, const QString &path) -> bool
Whether path is spelled through the target of a store root that is itself a link, rather than from th...
static auto isUnderLink(const QString &path, const QString &storeRoot, bool includeSelf=true) -> bool
Whether the way from storeRoot down to path passes through a symbolic link or NTFS junction: path its...
static void requireExplicitBareRepository(QProcessEnvironment &env)
Make git in env refuse a folder that is merely laid out as a bare repository (safe....
static constexpr qint64 kMaxGpgIdBytes
Most bytes of a .gpg-id QtPass reads.
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 displayable(const QString &text, bool lineBreaks=true) -> QString
text with the characters that change how the text around them reads replaced by U+FFFD,...
static auto isLinkedFolder(const QString &path) -> bool
Whether path names a symbolic link or NTFS junction, with or without a trailing separator (which woul...
static auto joinPath(const QString &dir, const QString &name) -> QString
name in dir, as the file system means it.
static auto isValidKeyId(const QString &keyId) -> bool
Check whether a .gpg-id token may be passed to gpg as a key selector. Accepts any non-empty token tha...
static auto newLinesRegex() -> const QRegularExpression &
Returns a regex to match newline characters.
static auto readRegularFileInStore(const QString &store, const QString &path, qint64 maxBytes) -> std::optional< QByteArray >
readRegularFileUnder() for a file of the store at store, spelled under the store as configured or und...
EntryRecord: the entry paths this device has saved, kept outside the store.
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...
auto parseGpgColonOutput(const QString &output, bool secret) -> QList< UserInfo >
Parse a gpg colon listing into one UserInfo per key.
Parsing of gpg --with-colons key listings into UserInfo records.
auto processInfo(PROCESS pid) -> const ProcessInfo &
What is known about pid.
auto gpgErrorMessage(const QString &err) -> QString
Maps GPG stderr (which may include –status-fd 2 tokens) to a translated user-friendly encryption erro...
Pass, the abstract password-store backend that RealPass and ImitatePass implement,...
QString gpgErrorMessage(const QString &err)
Maps GPG stderr (which may include –status-fd 2 tokens) to a translated user-friendly encryption erro...
PathValidator: is a path inside the password store, and how is it spelled relative to the store root.
Enums::ProcessInfo, the one table that names each kind of subprocess and says whether its output may ...
The "qtpass" logging category.
Plain value-object holding all flat QtPass configuration.
QString gpgExecutable
Path to the gpg/gpg2 executable.
QString passSigningKey
GPG key used to sign .gpg-id files.
QString passStore
Password-store root path.
QString gitExecutable
Path to the git executable.
QString gpgHome
GPG home directory (read-only externally).
bool gitUseParentRepository
PasswordConfiguration passwordConfiguration
Length/charset/custom chars.
What initIfUnchanged() expects the list to read as, for refuseChangedList(); empty outside it.
QString passStore
The store root given to recipientsForEditing().
QString dir
The folder given to recipientsForEditing().
QStringList recipients
The recipients read then.
RecipientsForEditing::State state
The state read then.
What a dialog may do with the list of a folder (recipientsForEditing()).
QStringList recipients
The recipients to preselect; empty when Rejected.
State state
How the list on disk stood up.
QString warning
What the dialog should show, if anything.
@ Verified
Signature and generation and folder all accepted.
@ Unsigned
No signing key: the list as it is.
@ Rejected
Not to be used: signature invalid, written for another folder or for no folder in particular while a ...
What skippedGpgId() found on its way up from one folder.
Holds the password generator settings: which character set is selected, the alphabet of every set,...
int length
Length of the generated password, in characters.
Represents a command invocation for gpgconf operations.
QStringList arguments
Full argv list, including any wrapper/prefix args followed by the actual gpgconf operation flags (e....
QString program
Executable to run — may be a bare name resolved via PATH or a wrapper (e.g. wsl.exe) rather than a di...
Stores GPG key info including validity, creation date, and more.
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...