QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
passworddisplaypanel.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
9#include "appsettings.h"
10#include "otpcodewidget.h"
11#include "qpushbuttonasqrcode.h"
14#include "secretlineedit.h"
15#include "secrettextbrowser.h"
16#include "totp.h"
17#include "util.h"
18
19#include <QBoxLayout>
20#include <QDesktopServices>
21#include <QDrag>
22#include <QFrame>
23#include <QGridLayout>
24#include <QHBoxLayout>
25#include <QIcon>
26#include <QLabel>
27#include <QLayout>
28#include <QLineEdit>
29#include <QMouseEvent>
30#include <QPalette>
31#include <QPushButton>
32#include <QTextBrowser>
33#include <QUrl>
34
36 QBoxLayout *container,
37 QWidget *widgetParent,
38 QObject *parent)
39 : QObject(parent), m_grid(grid), m_container(container),
40 m_widgetParent(widgetParent) {}
41
43 while (m_grid->count() > 0) {
44 QLayoutItem *item = m_grid->takeAt(0);
45 if (QWidget *widget = item->widget()) {
46 // A drag out of a field value runs QDrag::exec() inside the value
47 // widget's own mouse handler, and clear() can be reached from that
48 // nested event loop (a drop on the search box, the panel autoclear
49 // timer, a second "qtpass NAME"). Deleting the row then - even with
50 // deleteLater(), which the drag's loop would deliver - frees it under
51 // its own handler and crashes. A row that has a QDrag among its children
52 // is hidden now and deleted once that QDrag is gone, which Qt does after
53 // the drag ends; rows without a drag are deleted at once as before.
54 const QList<QDrag *> drags = widget->findChildren<QDrag *>();
55 if (drags.isEmpty()) {
56 delete widget;
57 } else {
58 widget->hide();
59 connect(drags.last(), &QObject::destroyed, widget,
60 [widget]() { widget->deleteLater(); });
61 }
62 }
63 delete item;
64 }
65 m_container->setSpacing(0);
66}
67
68auto PasswordDisplayPanel::currentOtpCode() const -> QString {
69 // displayFields() renders at most one OTP row, so the first match is it.
70 for (int i = 0; i < m_grid->count(); ++i) {
71 QWidget *widget = m_grid->itemAt(i)->widget();
72 if (widget == nullptr) {
73 continue;
74 }
75 if (auto *otp = widget->findChild<OtpCodeWidget *>()) {
76 return otp->code();
77 }
78 }
79 return {};
80}
81
82void PasswordDisplayPanel::displayFields(const QString &password,
83 const NamedValues &namedValues,
84 const AppSettings &s,
85 const QString &otpConfig) {
86 // Rows are numbered as they are added rather than assuming the password
87 // occupies row 0: an entry written by `pass otp insert` has no password row,
88 // and starting at 1 regardless left an empty grid row above the OTP row.
89 int position = 0;
90 // Defence in depth: getPasswordForDisplay() already blanks a password line
91 // that holds a shared secret (an otpauth URI from `pass otp insert`, or an
92 // OTP field holding a seed); refuse one here too.
93 if (!password.isEmpty() && !FileContent::isOtpPasswordLine(password)) {
94 // The password is hidden in addField when needed.
95 addField(position, QObject::tr("Password"), password, s);
96 ++position;
97 }
98 bool otpRendered = false;
99 for (const NamedValue &nv : namedValues) {
100 // Keyed on the value too: a field called anything whose value is an otpauth
101 // URI is still a shared secret, and isLineHidden() hides it from the text
102 // browser, so suppressing only OTP/TOTP names leaked `2fa:` and friends.
103 if (FileContent::isOtpFieldName(nv.name) ||
104 FileContent::carriesOtpUri(nv.value)) {
105 // Never render an OTP field verbatim: addField() would display the
106 // shared secret and hand it to a copy button. Unconditional, so it stays
107 // hidden when OTP support is off and otpConfig is empty.
108 if (!otpRendered && !otpConfig.isEmpty()) {
109 addOtpField(position, otpConfig, s);
110 ++position;
111 otpRendered = true;
112 }
113 continue;
114 }
115 addField(position, nv.name, nv.value, s);
116 ++position;
117 }
118 // The configuration came from the entry body rather than from a field.
119 if (!otpConfig.isEmpty() && !otpRendered) {
120 addOtpField(position, otpConfig, s);
121 }
122 m_container->setSpacing(m_grid->count() == 0 ? 0 : 6);
123}
124
125namespace {
126
127// Scope every rule to the widget type so the transparent background does not
128// cascade into the field's standard context menu (a child QMenu), which would
129// otherwise render transparent too.
130constexpr const char *kButtonStyle =
131 "QPushButton { border-style: none; background: transparent; padding: 0; "
132 "margin: 0; icon-size: 16px; color: inherit; }";
133
134// 26px matches the action-button visual height for consistent alignment.
135constexpr int kFieldHeight = 26;
136
142auto valueBrowser(const QString &field, const QString &value,
143 const QString &lineStyle, bool links) -> SecretTextBrowser * {
144 auto *browser = new SecretTextBrowser();
145 browser->setOpenExternalLinks(true);
146 browser->setOpenLinks(true);
147 browser->setMaximumHeight(kFieldHeight);
148 browser->setMinimumHeight(kFieldHeight);
149 browser->setSizePolicy(
150 QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
151 browser->setObjectName(field);
152 // Both branches keep white space, which can hang Qt's layout on a run of
153 // 65536 spaces; the copy button still gets the value itself. One line:
154 // a carriage return or U+2029 in a value made a block each, millions of
155 // them for a crafted password line.
156 const QString shown =
158 // A value of hundreds of thousands of letters in a row (a crafted
159 // password line) wraps anywhere: at word boundaries Qt took minutes.
160 if (Util::hasLongUnbrokenRun(shown)) {
161 browser->setWordWrapMode(QTextOption::WrapAnywhere);
162 }
163 bool linked = false;
164 const QString linkedText =
165 links ? Util::linkifyUrls(shown, &linked) : QString();
166 if (linked) {
167 // Always HTML here: the text is escaped and carries anchor tags, so do
168 // not leave the interpretation to setText()'s auto-detection. With its
169 // white space kept, as setPlainText() below keeps it.
170 browser->setHtml(QStringLiteral("<span style=\"white-space: pre-wrap;\">") +
171 linkedText + QStringLiteral("</span>"));
172 } else {
173 // Plain text: escaping plus setText() showed `a&b` as `a&amp;b` unless
174 // the value happened to contain a '<'.
175 browser->setPlainText(shown);
176 }
177 browser->setReadOnly(true);
178 browser->setStyleSheet(lineStyle);
179 browser->setContentsMargins(0, 0, 0, 0);
180 return browser;
181}
182
184auto urlButton(const QString &url, QWidget *parent) -> QPushButton * {
185 auto *button = new QPushButton(parent);
186 button->setIcon(QIcon::fromTheme(QStringLiteral("applications-internet"),
187 QIcon(":/icons/open-url.svg")));
188 // Escape for the tooltip only; the launched URL stays the validated value.
189 // <qt> forces rich text: auto-detection would show `&amp;` literally, and
190 // plain text misreads a URL containing `&lt;`. Rich text wraps, breaking
191 // the URL at `/` and `?`; white-space:nowrap keeps it on one line (<nobr>
192 // is not enough: Qt only makes its spaces non-breaking).
193 button->setToolTip(
194 QStringLiteral("<qt style=\"white-space:nowrap\">%1</qt>")
195 .arg(QObject::tr("Open %1 in browser").arg(url.toHtmlEscaped())));
196 button->setStyleSheet(QString::fromLatin1(kButtonStyle));
197 button->setCursor(Qt::PointingHandCursor);
198 QObject::connect(button, &QPushButton::clicked, button, [url]() {
199 // Re-validate: never hand an unvalidated string to the OS URL handler.
200 if (Util::isLaunchableWebUrl(url)) {
201 QDesktopServices::openUrl(QUrl(url));
202 }
203 });
204 return button;
205}
206
207} // namespace
208
209void PasswordDisplayPanel::setMarkedSecrets(const QStringList &names) {
210 // Case-folded into a set once: isSecret() runs for every field line of an
211 // entry, and a store's .templates may mark thousands of names, so a scan
212 // of the list per line froze the window for minutes.
213 m_markedSecrets.clear();
214 for (const QString &name : names) {
215 m_markedSecrets.insert(name.toCaseFolded());
216 }
217}
218
219auto PasswordDisplayPanel::hides(const QString &field,
220 const AppSettings &s) const -> bool {
221 return s.hidePassword &&
222 (s.hideAllFields || field == QObject::tr("Password") ||
223 isSecret(field, s));
224}
225
226auto PasswordDisplayPanel::isSecret(const QString &field,
227 const AppSettings &s) const -> bool {
228 if (!s.hidePassword) {
229 return false;
230 }
231 const bool marked = m_markedSecrets.contains(field.toCaseFolded());
232 return marked || (s.hideSecretFields &&
233 FileContent::isSecretFieldName(field, s.secretFieldNames));
234}
235
237 const QString &field,
238 const QString &value,
239 const AppSettings &s) {
240 const QString buttonStyle = QString::fromLatin1(kButtonStyle);
242 auto *copy = new QPushButtonWithClipboard(value, m_widgetParent);
243 connect(copy, &QPushButtonWithClipboard::textClicked, this,
245 copy->setStyleSheet(buttonStyle);
246 layout->addWidget(copy);
247 }
248 if (s.useQrencode) {
249 auto *qr = new QPushButtonAsQRCode(value, m_widgetParent);
250 connect(qr, &QPushButtonAsQRCode::textClicked, this,
252 qr->setStyleSheet(buttonStyle);
253 layout->addWidget(qr);
254 }
255 // Never on the password field, nor on any field hidden like it: its value
256 // must not reach a tooltip or the browser. A field shown in plain view
257 // keeps its link.
258 if (field != QObject::tr("Password") && !hides(field, s) &&
260 layout->addWidget(urlButton(value, m_widgetParent));
261 }
262}
263
265 const QString &field,
266 const QString &value,
267 const QString &lineStyle) {
268 // Shown with the eye button, the password can be selected and copied;
269 // SecretLineEdit marks that copy and reports it, as the value browsers do.
270 auto *passwordLineEdit = new SecretLineEdit();
271 connect(passwordLineEdit, &SecretLineEdit::copied, this,
273 passwordLineEdit->setObjectName(field);
274 // As stored: the line-break filter is for input, and the eye button and a
275 // copy must show and copy the password the entry holds.
276 passwordLineEdit->setStoredText(value);
277 passwordLineEdit->setReadOnly(true);
278 passwordLineEdit->setStyleSheet(lineStyle);
279 passwordLineEdit->setContentsMargins(0, 0, 0, 0);
280 passwordLineEdit->setEchoMode(QLineEdit::Password);
281 auto *showButton =
282 new QPushButtonShowPassword(passwordLineEdit, m_widgetParent);
283 showButton->setStyleSheet(QString::fromLatin1(kButtonStyle));
284 showButton->setContentsMargins(0, 0, 0, 0);
285 layout->addWidget(showButton);
286 layout->addWidget(passwordLineEdit);
287}
288
289void PasswordDisplayPanel::addField(int position, const QString &field,
290 const QString &value,
291 const AppSettings &s) {
292 const QString trimmedField = field.trimmed();
293 // The password row keeps its value exactly: a leading or trailing space is
294 // part of the password, so the copy button, QR code and revealed text must
295 // return what is stored, as Ctrl+C on the tree and the edit dialog do. The
296 // carriage return of a CRLF line end is gone already
297 // (FileContent::passwordLine()), and dropping another here would make this
298 // row disagree with Ctrl+C. Every other row is `name: value`, where the
299 // whitespace around the value is layout and is trimmed.
300 const QString displayValue =
301 trimmedField == QObject::tr("Password") ? value : value.trimmed();
302 QFrame *frame = createFieldFrame();
303 addActionButtons(frame->layout(), trimmedField, displayValue, s);
304 const QString lineStyle =
306 ? "QLineEdit, QTextBrowser { border-style: none; background: "
307 "transparent; font-family: monospace; }"
308 : "QLineEdit, QTextBrowser { border-style: none; background: "
309 "transparent; }";
310 // The password, and with it the other secrets an entry holds (a PIN, a
311 // CVV, an API key, what a template marks): behind the eye button too.
312 if (hides(trimmedField, s)) {
313 addHiddenPassword(frame->layout(), trimmedField, displayValue, lineStyle);
314 } else {
315 // A password or another secret is never a link, also when shown: a
316 // click on a URL-shaped one handed it to the browser, its history and
317 // the command line of the URL handler.
318 AppSettings asHidden = s;
319 asHidden.hidePassword = true;
320 asHidden.hideSecretFields = true;
321 const bool secret = trimmedField == QObject::tr("Password") ||
322 isSecret(trimmedField, asHidden);
323 SecretTextBrowser *browser =
324 valueBrowser(trimmedField, displayValue, lineStyle, !secret);
325 connect(browser, &SecretTextBrowser::copied, this,
327 frame->layout()->addWidget(browser);
328 }
329 // Plain text before the name is set: a field name comes from the entry,
330 // and as rich text <img src="/dev/zero"> has Qt read that file without end.
331 auto *label = new QLabel();
332 label->setTextFormat(Qt::PlainText);
333 // Bounded: the label sizes the main window.
334 label->setText(Util::shownName(trimmedField));
335 addRow(position, label, frame);
336}
337
338void PasswordDisplayPanel::addRow(int position, QLabel *label, QFrame *frame) {
339 m_grid->addWidget(label, position, 0);
340 m_grid->addWidget(frame, position, 1);
341 label->installEventFilter(this);
342 frame->installEventFilter(this);
343 // The value widgets swallow mouse events before the frame sees them.
344 for (QWidget *child : frame->findChildren<QWidget *>()) {
345 child->installEventFilter(this);
346 }
347}
348
349auto PasswordDisplayPanel::eventFilter(QObject *watched, QEvent *event)
350 -> bool {
351 if (event->type() == QEvent::MouseButtonDblClick &&
352 static_cast<QMouseEvent *>(event)->button() == Qt::LeftButton) {
353 emit editRequested();
354 return true;
355 }
356 return QObject::eventFilter(watched, event);
357}
358
359// The colour is baked into the stylesheet (a `palette(mid)` reference
360// resolves once at polish time), so refreshPalette() re-runs this.
361void PasswordDisplayPanel::applyFrameStyle(QFrame *frame) const {
362 const QString borderColor =
363 m_widgetParent->palette().color(QPalette::Mid).name();
364 frame->setStyleSheet(QStringLiteral(".QFrame{border: 1px solid %1; "
365 "border-radius: 5px;}")
366 .arg(borderColor));
367}
368
370 for (int i = 0; i < m_grid->count(); ++i) {
371 if (auto *frame = qobject_cast<QFrame *>(m_grid->itemAt(i)->widget())) {
372 applyFrameStyle(frame);
373 }
374 }
375}
376
377// Shared by addField() and addOtpField() so they cannot drift apart on
378// spacing or border colour.
380 auto *frame = new QFrame();
381 auto *frameLayout = new QHBoxLayout();
382 frameLayout->setContentsMargins(5, 2, 2, 2);
383 frameLayout->setSpacing(0);
384 frame->setLayout(frameLayout);
385 applyFrameStyle(frame);
386 return frame;
387}
388
389// One label plus one frame, like every row, so grid rows match
390// displayFields()' position counter. hidePassword does not apply (the code
391// expires in seconds, next to a visible countdown), and there is no QR
392// button: a QR of the configuration would show the shared secret.
393void PasswordDisplayPanel::addOtpField(int position, const QString &otpConfig,
394 const AppSettings &s) {
396 const std::optional<Totp::Settings> settings = Totp::parse(otpConfig, &why);
397 if (!settings.has_value()) {
398 // Report the problem without echoing what the user stored: the value is
399 // still a would-be secret, so it gets neither a copy nor a QR button.
400 // Why it gives no code (HOTP, an export, an unknown algorithm), where
401 // parse() can say.
402 AppSettings inert = s;
404 inert.useQrencode = false;
405 inert.hidePassword = false; // a message, never behind the eye button
406 const QString reason = Totp::describe(why);
407 addField(position, QObject::tr("OTP code"),
408 reason.isEmpty()
409 ? QObject::tr("No OTP code found in this password entry")
410 : reason,
411 inert);
412 return;
413 }
414
415 auto *frame = createFieldFrame();
416 auto *otpWidget =
418 s.useMonospace, frame);
419 connect(otpWidget, &OtpCodeWidget::copyRequested, this,
421 frame->layout()->addWidget(otpWidget);
422
423 addRow(position, new QLabel(QObject::tr("OTP code")), frame);
424}
AppSettings, the value object holding every flat QtPass setting.
static auto isOtpFieldName(const QString &name) -> bool
Whether a field name designates the one-time password field.
static auto isSecretFieldName(const QString &name, const QStringList &secrets) -> bool
Whether a field name names a secret: one of secrets occurs in it as whole words, compared case-insens...
static auto isOtpPasswordLine(const QString &line) -> bool
Whether an entry's first line holds a TOTP shared secret rather than a password.
static auto carriesOtpUri(const QString &text) -> bool
Whether text holds an otpauth URI anywhere: after a list dash, in quotes, behind other text or a seco...
The NamedValues class is mostly a list of NamedValue but also has a method to take a specific NamedVa...
Definition filecontent.h:58
Live one-time password display: code, copy button and countdown.
OtpCodeWidget(Totp::Settings settings, bool withCopyButton, bool monospace, QWidget *parent=nullptr)
Build a live OTP code display and start its refresh timer.
void copyRequested(const QString &text)
Emitted when the copy button is activated.
auto isSecret(const QString &field, const AppSettings &s) const -> bool
Whether a field is a secret "Hide password" hides: one a template marks (setMarkedSecrets()),...
void qrRequested(const QString &text)
Emitted when a field's QR button is clicked.
QWidget * m_widgetParent
Parent for the buttons the panel creates and source of the palette used by applyFrameStyle(); not own...
void refreshPalette()
Re-derive palette-dependent styling after a runtime theme change.
void setMarkedSecrets(const QStringList &names)
Set the field names a template marks as secret.
void displayFields(const QString &password, const NamedValues &namedValues, const AppSettings &s, const QString &otpConfig={})
Render the password and template fields of a decrypted entry.
auto eventFilter(QObject *watched, QEvent *event) -> bool override
Turn a left double-click on a field row into editRequested().
QGridLayout * m_grid
The grid the rows go into; owned by MainWindow's .ui.
void addActionButtons(QLayout *layout, const QString &field, const QString &value, const AppSettings &s)
Add the copy, QR and open-in-browser buttons a field gets, per the settings.
QBoxLayout * m_container
Layout around the grid whose spacing is 0 while empty and 6 once rows are shown; owned by MainWindow'...
void addField(int position, const QString &field, const QString &value, const AppSettings &s)
Render one name: value row: action buttons, then the value either behind the eye button (see hides())...
void clear()
Remove all field rows and collapse the container spacing.
auto createFieldFrame() -> QFrame *
New bordered frame with a tight horizontal layout, styled by applyFrameStyle(); shared by addField() ...
PasswordDisplayPanel(QGridLayout *grid, QBoxLayout *container, QWidget *widgetParent, QObject *parent=nullptr)
Construct a panel that renders into the given layouts.
void textCopied(const QString &text)
Text was selected and copied out of a field's value (Ctrl+C, the context menu, a drag,...
QSet< QString > m_markedSecrets
Field names the current template marks as secret, case-folded, so isSecret() looks a name up in any c...
void addRow(int position, QLabel *label, QFrame *frame)
Put a row's label and value frame into the grid, listening for a double-click on either (and on the f...
void copyRequested(const QString &text)
Emitted when a field's copy button is clicked.
void addOtpField(int position, const QString &otpConfig, const AppSettings &s)
Render the live OTP row: an OtpCodeWidget in a field frame under an "OTP code" label....
void addHiddenPassword(QLayout *layout, const QString &field, const QString &value, const QString &lineStyle)
Add the password, hidden, with a button that shows it.
auto currentOtpCode() const -> QString
The one-time password currently on display, if there is one.
void editRequested()
Emitted on a double-click anywhere on a field row: the user wants to change what they are looking at.
auto hides(const QString &field, const AppSettings &s) const -> bool
Whether a field is shown behind the eye button: the password, a field a template marks,...
void applyFrameStyle(QFrame *frame) const
Give a field frame its rounded border in the current QPalette::Mid colour. The colour is baked into t...
QPushButtonAsQRCode(QString textToCopy="", QWidget *parent=nullptr)
Construct a QPushButtonAsQRCode with an optional initial text.
void textClicked(const QString &text)
Emitted when the button is activated with the current text payload. Not named clicked(): that would h...
QPushButtonShowPassword(QLineEdit *line, QWidget *parent=nullptr)
Construct a show-password button linked to the given QLineEdit.
void textClicked(const QString &text)
Emitted when the button is activated with the stored text. Not named clicked(): that would hide QAbst...
QPushButtonWithClipboard(QString textToCopy="", QWidget *parent=nullptr)
Construct a QPushButtonWithClipboard with an optional initial text.
void copied(const QString &text)
Selected text was copied out of the line edit.
SecretLineEdit(QWidget *parent=nullptr)
Constructs the line edit.
A QTextBrowser for decrypted entry text: whatever is copied out of it is marked as a secret and repor...
SecretTextBrowser(QWidget *parent=nullptr)
Constructs the browser.
void copied(const QString &text)
Selected text was copied out of the browser.
static auto parse(const QString &config, Refusal *why=nullptr) -> std::optional< Settings >
Parse an OTP configuration string.
Definition totp.cpp:264
static auto describe(Refusal why) -> QString
One sentence for the user on why a configuration gives no code.
Definition totp.cpp:329
Refusal
Why parse() gave no settings, so the user can be told more than "invalid".
Definition totp.h:59
@ None
Parsed: there was nothing to refuse.
Definition totp.h:60
static auto hasLongUnbrokenRun(QStringView text) -> bool
Whether text holds more than kMaxUnbrokenRun characters in a row without white space Qt wraps at (a n...
Definition util.cpp:976
static auto withoutOtherBlockBreaks(QString text) -> QString
text with every block break other than a line feed (isOtherBlockBreak()) shown as a space,...
Definition util.cpp:967
static auto boundSpaceRuns(const QString &text) -> QString
text with every run of white space other than tabs and line feeds cut to kMaxSpaceRun characters,...
Definition util.cpp:1029
static auto isLaunchableWebUrl(const QString &value) -> bool
Check whether a value is a safe, launchable web URL.
Definition util.cpp:843
static auto shownName(const QString &name, qsizetype max=kMaxShownName) -> QString
A name or path from the store, as a label or list shows it: one line, at most max characters.
Definition util.cpp:1000
static auto linkifyUrls(const QString &text, bool *linked=nullptr) -> QString
Turn plain text into HTML with clickable links for safe web URLs.
Definition util.cpp:914
@ CLIPBOARD_NEVER
Definition enums.h:25
Self-refreshing widget showing an entry's current TOTP code with a countdown bar and optional copy bu...
PasswordDisplayPanel: renders the decrypted fields of an entry (password, template fields,...
Icon button that asks for a stored secret to be shown as a QR code.
Eye-icon button that toggles a QLineEdit between password and plain-text echo mode.
Copy-to-clipboard icon button that carries the text of the field it sits next to.
QLineEdit whose copies, cuts and primary-selection fills carry the secret clipboard hints and are rep...
QTextBrowser for showing decrypted entry text that marks everything copied out of it as a secret.
Plain value-object holding all flat QtPass configuration.
Definition appsettings.h:36
bool hidePassword
Definition appsettings.h:85
bool hideSecretFields
Definition appsettings.h:88
Enums::ClipBoardType clipBoardType
Clipboard copy behaviour.
Definition appsettings.h:73
bool useMonospace
Render content in a monospace font.
Definition appsettings.h:96
bool useQrencode
Enable qrencode support.
A name/value pair parsed from a password file field.
Definition filecontent.h:21
RFC 6238 TOTP: otpauth URI parsing, code generation and canonical re-serialisation.
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...