13#include "ui_usersdialog.h"
16#include <QApplication>
18#include <QDialogButtonBox>
30#include <QRegularExpression>
33#include <QSignalBlocker>
54 connect(
ui->buttonBox, &QDialogButtonBox::rejected,
this, &QDialog::reject);
66 connect(
ui->buttonBox, &QDialogButtonBox::accepted,
this,
68 connect(
ui->buttonBox, &QDialogButtonBox::rejected,
this, &QDialog::reject);
69 connect(
ui->listWidget, &QListWidget::itemChanged,
this,
74 ui->lineEdit->setClearButtonEnabled(
true);
82 QList<UserInfo> users =
m_pass->listKeys();
83 if (users.isEmpty()) {
84 QMessageBox::critical(parentWidget(), tr(
"Keylist missing"),
85 tr(
"Could not fetch list of available GPG keys"));
98 QSet<QString> secretKeyIds;
99 for (
const UserInfo &sec : std::as_const(secret_keys)) {
100 secretKeyIds.insert(sec.key_id);
102 for (
auto &user : users) {
103 if (secretKeyIds.contains(user.key_id)) {
104 user.have_secret =
true;
110 const QString &name) {
113 auto *banner =
new QLabel(
this);
114 banner->setTextFormat(Qt::PlainText);
118 banner->setObjectName(name);
119 banner->setWordWrap(
true);
122 QFont bold = banner->font();
124 banner->setFont(bold);
125 QPalette palette = banner->palette();
126 palette.setColor(QPalette::WindowText, QColor(Qt::red));
127 banner->setPalette(palette);
128 banner->setContentsMargins(4, 4, 4, 4);
134 auto *area =
new QScrollArea(
this);
135 area->setWidget(banner);
136 area->setWidgetResizable(
true);
137 area->setFrameShape(QFrame::NoFrame);
138 area->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
139 area->setMaximumHeight(banner->fontMetrics().lineSpacing() * 8 + 8);
140 ui->verticalLayout->insertWidget(1, area);
145 const QString dir = QDir::cleanPath(
m_dir);
146 if (!QFileInfo(dir).isDir()) {
149 QStringList unlisted;
151 dir, {QStringLiteral(
".gpg-id")},
nullptr,
true, &unlisted);
152 const auto relative = [&dir](
const QString &folder) {
153 return QDir::toNativeSeparators(QDir(dir).relativeFilePath(folder));
156 for (
const QString &list : lists) {
157 const QString folder = QFileInfo(list).path();
158 if (QDir::cleanPath(folder) != dir) {
159 nested << relative(folder);
163 for (
const QString &folder : std::as_const(unlisted)) {
164 unread << relative(folder);
166 constexpr qsizetype kMaxNamed = 5;
167 const auto named = [](
const QStringList &folders) {
168 QString names = folders.mid(0, kMaxNamed).join(QStringLiteral(
", "));
169 if (folders.size() > kMaxNamed) {
170 names += QStringLiteral(
", …");
175 if (!nested.isEmpty()) {
178 text << tr(
"%n folder(s) below this one have their own recipients, which "
179 "saving here does not change: %1",
180 nullptr,
static_cast<int>(nested.size()))
183 if (!unread.isEmpty()) {
186 text << tr(
"%n folder(s) below this one could not be read, so whether "
187 "they have their own recipients is unknown: %1",
188 nullptr,
static_cast<int>(unread.size()))
191 if (!text.isEmpty()) {
193 QStringLiteral(
"nestedListsWarning"));
200auto normalisedKeyId(
const QString &
id) -> QString {
201 const QString trimmed =
id.trimmed();
202 return (trimmed.startsWith(QLatin1String(
"0x"), Qt::CaseInsensitive)
211auto keyIdsMatch(
const QString &first,
const QString &second) ->
bool {
212 static const QRegularExpression hexId(QStringLiteral(
"^[0-9A-F]{8,}$"));
213 const QString a = normalisedKeyId(first);
214 const QString b = normalisedKeyId(second);
215 if (!hexId.match(a).hasMatch() || !hexId.match(b).hasMatch()) {
218 if (a.size() == 64) {
219 return b == a || (b.size() == 16 && a.startsWith(b)) ||
220 (b.size() == 8 && a.mid(8, 8) == b);
222 if (b.size() == 64) {
223 return a == b || (a.size() == 16 && b.startsWith(a)) ||
224 (a.size() == 8 && b.mid(8, 8) == a);
226 return a.endsWith(b) || b.endsWith(a);
232auto keyIdOfLine(
const QString &recipient) -> QString {
233 static const QRegularExpression hexLine(
234 QStringLiteral(
"^(?:0[xX])?([0-9A-Fa-f]+)!?$"));
235 const QRegularExpressionMatch match = hexLine.match(recipient.trimmed());
236 if (!match.hasMatch()) {
239 const QString digits = match.captured(1);
240 const qsizetype size = digits.size();
241 return size == 8 || size == 16 || size == 40 || size == 64 ? digits
248auto nameTermOfLine(
const QString &recipient) -> QString {
249 const QString line = recipient.trimmed();
250 if (line.isEmpty()) {
257 static const QRegularExpression hexish(QStringLiteral(
258 "^(?:0[xX]|[0-9A-Fa-f]+!?$|[0-9A-Fa-f]{4}(?:\\s+[0-9A-Fa-f]{4})+!?$)"));
259 if (hexish.match(line).hasMatch() ||
260 QStringLiteral(
".+#&^/[:!\\").contains(line.front())) {
264 if (term.startsWith(u
'<')) {
265 if (!term.endsWith(u
'>')) {
268 term = term.mid(1, term.size() - 2);
269 }
else if (term.startsWith(u
'=') || term.startsWith(u
'@') ||
270 term.startsWith(u
'*')) {
282auto judgedLocally(
const QString &recipient) ->
bool {
283 return !keyIdOfLine(recipient).isEmpty() ||
284 !nameTermOfLine(recipient).isEmpty();
294auto answersTo(
const UserInfo &key,
const QString &recipient) ->
bool {
295 const QString keyId = keyIdOfLine(recipient);
296 if (!keyId.isEmpty()) {
297 return keyIdsMatch(key.key_id, keyId) ||
298 std::any_of(key.subkeys.cbegin(), key.subkeys.cend(),
299 [&keyId](
const QString &subkey) {
300 return keyIdsMatch(subkey, keyId);
303 const QString term = nameTermOfLine(recipient);
304 if (term.isEmpty()) {
307 const auto holds = [&term](
const QString &uid) {
308 return uid.contains(term, Qt::CaseInsensitive);
310 return holds(key.name) ||
311 std::any_of(key.uids.cbegin(), key.uids.cend(), holds);
316auto uniqueLines(
const QStringList &listed) -> QStringList {
319 for (
const QString &line : listed) {
320 if (!seen.contains(line)) {
331 QStringList recipients = uniqueLines(listed);
341 const std::optional<QStringList> reached =
343 if (reached && !reached->isEmpty() &&
tickReached(*reached, recipients)) {
366 kept.
name =
" ?? " + why;
382 QSet<int> reachedRows;
383 for (
const QString &
id : ids) {
385 for (
int row = 0; row <
m_userList.size(); ++row) {
390 if (rows.isEmpty()) {
393 shared = shared || rows.size() > 1;
394 for (
const int row : std::as_const(rows)) {
395 reachedRows.insert(row);
399 for (
const int row : std::as_const(reachedRows)) {
404 for (
const QString &line : lines) {
405 const QString keyId = keyIdOfLine(line);
407 if (!keyId.isEmpty()) {
408 for (
const int row : std::as_const(reachedRows)) {
409 if (keyIdsMatch(
m_userList.at(row).key_id, keyId)) {
416 keepAsWritten(line, tr(
"Matches more than one key; kept as written"));
428 if (
const std::optional<QHash<QString, QStringList>> held =
429 m_pass->keyLinesHeldTwice(*recipients);
430 !held || !held->isEmpty()) {
432 QStringLiteral(
"heldTwiceWarning"));
434 for (
const QString &line : std::as_const(*recipients)) {
436 keepAsWritten(line, tr(
"Keys could not be checked; kept as written"));
437 }
else if (held->contains(line)) {
438 keepAsWritten(line, tr(
"Held by more than one key; kept as written"));
443 if (rest.isEmpty()) {
446 *recipients = std::move(rest);
453 std::copy_if(recipients->cbegin(), recipients->cend(),
454 std::back_inserter(order),
455 [](
const QString &line) { return keyIdOfLine(line).isEmpty(); });
457 recipients->cbegin(), recipients->cend(), std::back_inserter(order),
458 [](
const QString &line) { return !keyIdOfLine(line).isEmpty(); });
459 constexpr int kMaxLineProbes = 10;
462 for (
const QString &line : std::as_const(order)) {
463 if (probes++ >= kMaxLineProbes) {
468 const std::optional<QStringList> one =
469 recipients->size() == 1 ? std::nullopt
470 :
m_pass->encryptionReaches({line});
472 keepAsWritten(line, tr(
"Key not found in keyring, or not usable"));
473 }
else if (one->isEmpty() || !
tickReached(*one, {line})) {
477 if (unsure.isEmpty()) {
480 *recipients = std::move(unsure);
487 if (resolved.isEmpty() && recipients.size() > 1) {
493 QStringList readable;
494 std::copy_if(recipients.cbegin(), recipients.cend(),
495 std::back_inserter(readable), judgedLocally);
496 if (!readable.isEmpty() && readable.size() < recipients.size()) {
506 constexpr int kMaxLookups = 10;
508 QHash<QString, bool> perLineHasKey;
509 QSet<QString> notLookedUp;
510 for (
const QString &recipient : std::as_const(recipients)) {
511 if (judgedLocally(recipient)) {
514 if (lookups++ >= kMaxLookups) {
515 notLookedUp.insert(recipient);
519 perLineHasKey.insert(recipient, !keys.isEmpty());
524 if (std::any_of(resolved.cbegin(), resolved.cend(),
526 return key.key_id == user.key_id;
536 for (
const QString &recipient : std::as_const(recipients)) {
538 missing.
key_id = recipient;
539 if (notLookedUp.contains(recipient)) {
540 missing.
name =
" ?? " + tr(
"Not looked up in keyring");
545 const auto cached = perLineHasKey.constFind(recipient);
546 const bool found = cached != perLineHasKey.constEnd()
548 : std::any_of(resolved.cbegin(), resolved.cend(),
550 return answersTo(key, recipient);
554 missing.
name =
" ?? " + tr(
"Key not found in keyring");
574 if (!loaded.
warning.isEmpty()) {
605 QMessageBox::warning(
606 this, tr(
"Recipients not changed"),
607 tr(
"The recipient list of this folder changed while this dialog was "
608 "open, for example through an update from Git. OK would have "
609 "written the old list back. Close this dialog and open it again "
610 "to see the new list."));
644 [](
const UserInfo &user) { return user.enabled; });
648 if (
auto *ok =
ui->buttonBox->button(QDialogButtonBox::Ok)) {
654 switch (event->key()) {
656 ui->lineEdit->clear();
668 const int index = item->data(Qt::UserRole).toInt(&ok);
671 <<
"UsersDialog::itemChange: invalid user index data for item";
674 if (index < 0 || index >=
m_userList.size()) {
675 qCWarning(lcQtPass) <<
"UsersDialog::itemChange: user index out of range:"
676 << index <<
"valid range is [0,"
680 m_userList[index].enabled = item->checkState() == Qt::Checked;
688 QString patternString =
"*" + filter +
"*";
693 QRegularExpression re(
694 QRegularExpression::wildcardToRegularExpression(
695 patternString, QRegularExpression::NonPathWildcardConversion),
696 QRegularExpression::CaseInsensitiveOption);
706 ui->listWidget->setSortingEnabled(
false);
707 ui->listWidget->clear();
720 item->setCheckState(user.enabled ? Qt::Checked : Qt::Unchecked);
721 item->setData(Qt::UserRole, QVariant::fromValue(i));
722 ui->listWidget->addItem(item);
725 ui->listWidget->sortItems();
726 ui->listWidget->setSortingEnabled(
true);
731 const QRegularExpression &nameFilter)
const {
732 if (!filter.isEmpty() && !nameFilter.match(user.
name).hasMatch()) {
739 if (user.
enabled ||
ui->checkBox->isChecked() ||
752 return user.validity ==
'e' ||
768auto shortened(
const QString &text) -> QString {
769 constexpr qsizetype kMaxShown = 256;
770 if (text.size() <= kMaxShown) {
773 qsizetype cut = kMaxShown;
774 if (text.at(cut - 1).isHighSurrogate()) {
777 return text.left(cut) + QChar(0x2026);
789 text +=
" " + tr(
"created") +
" " +
790 QLocale::system().toString(user.
created, QLocale::ShortFormat);
792 if (user.
expiry.isValid()) {
793 text +=
" " + tr(
"expires") +
" " +
794 QLocale::system().toString(user.
expiry, QLocale::ShortFormat);
801 const QString originalText = item->text();
810 item->setBackground(Qt::darkRed);
811 item->setForeground(Qt::white);
812 item->setText(tr(
"[EXPIRED] ") + originalText);
814 item->setBackground(Qt::darkRed);
815 item->setForeground(Qt::white);
816 item->setText(tr(
"[INVALID] ") + originalText);
818 item->setBackground(Qt::darkYellow);
819 item->setForeground(Qt::white);
820 item->setText(tr(
"[PARTIAL] ") + originalText);
822 item->setText(originalText);
827 item->setForeground(QApplication::palette().color(QPalette::Link));
829 QFont font = item->font();
843 for (
int i = 0; i <
ui->listWidget->count(); ++i) {
844 QListWidgetItem *item =
ui->listWidget->item(i);
846 const int idx = item !=
nullptr ? item->data(Qt::UserRole).toInt(&ok) : -1;
847 if (ok && idx >= 0 && idx <
m_userList.size() &&
849 keyIdsMatch(
m_userList[idx].key_id, importedKey)) {
850 ui->listWidget->setCurrentItem(item);
858 if (dialog.exec() != QDialog::Accepted) {
865 if (importedKey.isEmpty()) {
873 QStringList selected;
876 selected.append(user.key_id);
892 QStringList unresolved;
893 for (
const QString &keyId : std::as_const(selected)) {
894 bool matched =
false;
896 if (user.key_id == keyId) {
902 unresolved.append(keyId);
905 if (!unresolved.isEmpty()) {
912 const QSignalBlocker blocker(
ui->lineEdit);
913 ui->lineEdit->clear();
Dialog for importing GPG keys from file or clipboard.
auto importedKeyId() const -> QString
Get the imported key id on success.
Abstract base class for password store operations.
virtual auto encryptionReaches(const QStringList &recipients) -> std::optional< QStringList >
The keys a gpg encryption to recipients reaches: a throwaway encryption outside the store,...
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().
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 entriesInitWouldWiden(const QString &dir, const QList< UserInfo > &users) -> QStringList
Entries a pass init of dir with users would hand to someone who cannot read them now (an entry copied...
auto listKeys(QStringList keystrings, bool secret=false) -> QList< UserInfo >
List GPG keys matching patterns.
auto recipientsForEditing(const QString &dir, const QString &passStore) -> RecipientsForEditing
The recipients a dialog may preselect for editing the list of dir.
virtual void Init(QString path, const QList< UserInfo > &users)=0
Initialize new password store.
QString m_cachedPatternString
~UsersDialog() override
Destroys the dialog and its generated form.
void updateOkButton()
Enable OK only while at least one key is ticked (hasSelection()).
void itemChange(QListWidgetItem *item)
Handle user selection change.
QRegularExpression m_cachedNameFilter
void on_importKeyButton_clicked()
Import a GPG key and refresh the list.
void on_lineEdit_textChanged(const QString &filter)
Filter user list.
auto isUserExpired(const UserInfo &user) const -> bool
Check if GPG key is expired.
void keyPressEvent(QKeyEvent *event) override
Handle key press.
void showRecipientWarning(const QString &text, const QString &name=QStringLiteral("recipientWarning"))
Show text above the key list in bold red, for a recipient list that could not be verified.
void selectRecipients(const QStringList &listed)
Tick the keys the folder is encrypted to, and list recipients no key in the keyring answers to,...
void applyUserStyling(QListWidgetItem *item, const UserInfo &user) const
Apply visual styling to user item.
void searchKeyring(const QStringList &recipients)
Tick the keys a keyring search resolves recipients to, and list the lines no key answers to,...
Preselect
Whether the recipients on disk are ticked when it opens.
@ Nothing
None: for a store that had no list when it was chosen.
auto tickReached(const QStringList &ids, const QStringList &lines) -> bool
Tick the rows of the keys ids, which a probe of lines reached. A key on more than one row (a shared s...
void keepAsWritten(const QString &line, const QString &why)
List line as a ticked row of its own, named by why, so OK writes it back as it was.
QList< UserInfo > m_userList
void connectSignals()
Connect dialog signals.
auto setAsideHeldTwice(QStringList *recipients) -> bool
Keep as written, and warn about, the lines a key ID or fingerprint names that two key blocks hold,...
QDateTime m_cachedCurrentDateTime
void restoreDialogState()
auto listChangedSinceRead() const -> bool
Whether the folder's recipient list reads differently now from when loadRecipients() read it: a pull,...
QString buildUserText(const UserInfo &user) const
Build display text for user: the user ID and key ID on a line each, each cut to 256 characters (the r...
QStringList m_readRecipients
The recipients the list named when the dialog read it.
void populateList(const QString &filter=QString())
Populate user list.
void selectImportedKey(const QString &importedKey)
Make the key gpg just imported the current row. gpg reports a 16-character long ID (IMPORTED) or a 40...
void showNestedLists()
Name the folders below this one that have a recipient list of their own: saving here does not change ...
void loadRecipients()
Load recipients and handle missing keys.
void accept() override
Handle dialog acceptance.
bool m_cachedDateTimeValid
UsersDialog(Pass *pass, const AppSettings &s, QString dir, QWidget *parent=nullptr)
Construct users dialog.
void markSecretKeys(QList< UserInfo > &users)
Mark which keys have secret counterparts.
auto probeEachLine(QStringList *recipients) -> bool
After gpg refused the list as a whole, probe each line on its own (address and name lines first,...
QSet< QString > m_notLookedUp
.gpg-id lines selectRecipients() listed unticked without asking gpg. They are shown without "Show unu...
bool passesFilter(const UserInfo &user, const QString &filter, const QRegularExpression &nameFilter) const
Check if user passes filter.
auto hasSelection() const -> bool
Whether at least one key is ticked.
void on_checkBox_clicked()
Handle select all checkbox.
QScopedPointer< Ui::UsersDialog > ui
The widgets from usersdialog.ui.
auto loadGpgKeys() -> bool
Load GPG keys and determine secret key status.
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 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,...
Dialog that imports an ASCII-armored GPG public key from a file or the clipboard by running gpg --imp...
auto confirmPassRun(QWidget *parent, const QString &store, const std::function< QStringList()> &check) -> bool
Run check (which lists the entries a pass run would give new readers, one gpg call each) under a wait...
void attach(QDialog &dialog, const QString &key)
restore() now, save() whenever the dialog finishes.
Pass, the abstract password-store backend that RealPass and ImitatePass implement,...
QMessageBox helpers that force Qt::PlainText so store-controlled names can never be read as rich-text...
The "qtpass" logging category.
QtPassSettings, the QSettings singleton behind every saved setting, the profiles and the Pass backend...
Plain value-object holding all flat QtPass configuration.
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.
State
How the list on disk stood up.
@ Rejected
Not to be used: signature invalid, written for another folder or for no folder in particular while a ...
Stores GPG key info including validity, creation date, and more.
bool have_secret
Whether secret key is available (can decrypt with this key).
bool enabled
Whether this user/key is enabled for normal use.
QString key_id
Hexadecimal representation of the GnuPG key identifier.
auto fullyValid() const -> bool
Check full validity per GnuPG validity codes.
auto isValid() const -> bool
Check whether the key has any usable validity level.
QDateTime created
Date/time when key was created.
QString name
GPG user ID / full name.
QDateTime expiry
Date/time when key expires.
UsersDialog, the recipient picker for a folder's .gpg-id.
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...
WindowStateStore: saves and restores top-level window geometry through QtPassSettings,...