QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
passworddialog.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2015 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
9#include "passworddialog.h"
10#include "fieldlabel.h"
11#include "filecontent.h"
12#include "pass.h"
14#include "pathvalidator.h"
15#include "qtpasssettings.h"
16#include "secretlineedit.h"
17#include "secretplaintextedit.h"
18#include "templateio.h"
19#include "totp.h"
20#include "ui_passworddialog.h"
21#include "util.h"
22#include <algorithm>
23#include <limits>
24
25#include <QAction>
26#include <QCheckBox>
27#include <QComboBox>
28#include <QDialogButtonBox>
29#include <QDir>
30#include <QFileInfo>
31#include <QFormLayout>
32#include <QHash>
33#include <QIcon>
34#include <QLabel>
35#include <QLineEdit>
36#include <QMessageBox>
37#include <QPushButton>
38#include <QSet>
39#include <QShortcut>
40#include <QSignalBlocker>
41#include <QTextDocument>
42#include <utility>
43
44#include "qtpasslogging.h"
45
46namespace {
49const char kOtpEditedProperty[] = "qtpassOtpEdited";
52const char kOriginalLineProperty[] = "qtpassOriginalLine";
53} // namespace
54
56 QWidget *parent)
57 : QDialog(parent), ui(new Ui::PasswordDialog),
58 m_passConfig(std::move(passConfig)), m_pass(QtPassSettings::getPass()) {
59 // Only reached from tests; production uses the overload taking an
60 // explicit Pass* with a caller-controlled lifetime.
61 m_templating = false;
62 m_isNew = false;
63
64 ui->setupUi(this);
65 connect(ui->checkBoxShow, &QCheckBox::toggled, this,
67 reportCopies(ui->lineEditPassword);
68 connect(ui->plainTextEdit, &SecretPlainTextEdit::copied, this,
73
75 connect(m_pass, &Pass::finishedInsert, this,
78}
79
80PasswordDialog::PasswordDialog(Pass *pass, const AppSettings &s, QString file,
81 const bool &isNew, QWidget *parent)
82 : QDialog(parent), ui(new Ui::PasswordDialog), m_pass(pass),
83 m_file(std::move(file)), m_isNew(isNew) {
84
85 ui->setupUi(this);
86 connect(ui->checkBoxShow, &QCheckBox::toggled, this,
88 reportCopies(ui->lineEditPassword);
89 connect(ui->plainTextEdit, &SecretPlainTextEdit::copied, this,
92 // The name row only appears once setNewEntryLocation() says where a new
93 // entry may go; an existing entry keeps its name.
94 ui->nameRow->hide();
95
96 setWindowTitle(isNew && m_file.isEmpty()
97 ? tr("New password")
98 : this->windowTitle() + " " + m_file);
103
106
109 connect(m_pass, &Pass::finishedInsert, this,
112 connect(this, &PasswordDialog::rejected, this, &PasswordDialog::on_rejected);
113
114 if (!isNew) {
115 // Show() is asynchronous: until finishedShow lands the fields are empty,
116 // so an early Ok would write nothing and the late setPass() would clobber
117 // what was typed. Lock the editor and Ok until the decrypt arrives.
118 ui->statusLabel->setText(tr("Decrypting…"));
119 setEditorEnabled(false);
120 ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
122 }
123}
124
126 // QDialog's destructor hides the window after this body, and losing focus
127 // emits editingFinished() into normalizeOtpField() or renameField(), slots
128 // of a PasswordDialog already gone. Hide here, while the object is whole.
129 hide();
130}
131
133 if (show) {
134 ui->lineEditPassword->setEchoMode(QLineEdit::Normal);
135 } else {
136 ui->lineEditPassword->setEchoMode(QLineEdit::Password);
137 }
138}
139
141 ui->widget->setEnabled(false);
142 const int currentIndex = ui->passwordTemplateSwitch->currentIndex();
143 if (currentIndex < 0 ||
144 currentIndex >= static_cast<int>(PasswordConfiguration::CHARSETS_COUNT)) {
145 ui->widget->setEnabled(true);
146 return;
147 }
148
149 QString newPass = m_pass->generatePassword(
150 static_cast<unsigned int>(ui->spinBox_pwdLength->value()),
152 currentIndex)]);
153 if (!newPass.isEmpty()) {
154 ui->lineEditPassword->setText(newPass);
155 }
156 ui->widget->setEnabled(true);
157}
158
160 // Show is asynchronous: refuse to save an existing entry before its
161 // content loads. getPassword() always returns at least a newline, so an
162 // isEmpty() check cannot stand in for this.
163 if (!m_isNew && !m_contentLoaded) {
164 return;
165 }
166
167 // Canonicalise before serialising: getPassword() stays a dumb serializer.
169
170 QString newValue = getPassword();
171 if (newValue.right(1) != "\n") {
172 newValue += "\n";
173 }
174
175 setSaving(true);
176 // A refusal (the name is taken, the .gpg-id is unusable, a linked path)
177 // comes through critical() before Insert() returns, with nothing started
178 // that could still report.
179 QString refusal;
180 const QMetaObject::Connection refused =
181 connect(m_pass, &Pass::critical, this,
182 [&refusal](const QString &, const QString &message) {
183 refusal = message;
184 });
185 // Reports from inserts already queued (an earlier dialog that a hanging
186 // queue let close while its save was still pending) must pass before one is
187 // taken as this dialog's own. The count is read before our own Insert()
188 // queues, so it does not include it.
190 m_pass->Insert(m_file, newValue, !m_isNew);
191 disconnect(refused);
192 if (m_saving && !refusal.isEmpty()) {
193 setSaving(false);
194 showNotSaved(refusal);
195 }
196}
197
198void PasswordDialog::setSaving(bool saving) {
199 m_saving = saving;
200 setEditorEnabled(!saving);
201 ui->nameRow->setEnabled(!saving);
202 // Another template would rebuild the field rows under a pending insert.
203 ui->templateBox->setEnabled(!saving);
204 // Cancel stays: a save that never reports (an unanswered PIN prompt, a
205 // queue held up by a hanging pull) must not leave quitting as the only
206 // way out. reject() asks first.
207 ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!saving);
208 ui->statusLabel->setText(saving ? tr("Saving…") : QString());
209}
210
212 if (!m_saving) {
213 return false;
214 }
215 // Since a hanging queue can let a dialog close while its insert is still
216 // queued (#1965), more than one insert can be in flight, and neither
217 // finishedInsert nor insertFailed says which it is. The Executor runs the
218 // queue in order, so the first m_insertsAhead reports belong to inserts
219 // queued before this dialog's; let them pass before taking one as our own.
220 if (m_insertsAhead > 0) {
222 return false;
223 }
224 return true;
225}
226
228 if (!isOwnInsertReport()) {
229 return;
230 }
231 setSaving(false);
232 QDialog::accept();
233}
234
235void PasswordDialog::onInsertFailed(const QString &err, bool written) {
236 if (!isOwnInsertReport()) {
237 return;
238 }
239 setSaving(false);
240 // The entry is in the store and a later step (git add or commit) failed,
241 // which the backend reports ("Saved, not committed"). Saved is saved, so
242 // the dialog closes, also for an existing entry: "Not saved" would be
243 // wrong, and a new entry could only be tried again under a name it now
244 // has.
245 if (written) {
246 QDialog::accept();
247 return;
248 }
249 showNotSaved(err);
250}
251
253 if (m_saving) {
254 const QMessageBox::StandardButton answer = QMessageBox::question(
255 this, tr("Still saving"),
256 tr("The entry is still being saved. Close the dialog anyway? If "
257 "saving then fails, what you typed is lost."),
258 QMessageBox::Yes | QMessageBox::No, QMessageBox::No);
259 // The insert may have reported while the question was up.
260 if (answer != QMessageBox::Yes || !m_saving) {
261 return;
262 }
263 // Whatever the insert reports later, the main window shows it.
264 m_saving = false;
265 }
266 QDialog::reject();
267}
268
269void PasswordDialog::showNotSaved(const QString &err) {
270 if (!m_storeRoot.isEmpty()) {
271 validateNewEntry(); // gates OK on the name again
272 }
273 ui->statusLabel->setText(tr("Not saved: %1").arg(err.trimmed()));
274}
275
277
278void PasswordDialog::setNewEntryLocation(const QString &storeRoot,
279 const QStringList &folders,
280 const QString &currentFolder) {
281 m_storeRoot = QDir::cleanPath(storeRoot);
282 ui->folderBox->clear();
283 int current = 0;
284 for (const QString &folder : folders) {
285 const QString rel = QDir::cleanPath(folder) == QStringLiteral(".")
286 ? QString()
287 : QDir::cleanPath(folder);
288 if (rel == QDir::cleanPath(currentFolder) ||
289 (rel.isEmpty() &&
290 QDir::cleanPath(currentFolder) == QStringLiteral("."))) {
291 current = ui->folderBox->count();
292 }
293 ui->folderBox->addItem(rel.isEmpty() ? QStringLiteral("/") : rel + u'/',
294 rel);
295 }
296 ui->folderBox->setCurrentIndex(current);
297 m_newEntryFolder = ui->folderBox->currentData().toString();
298 ui->nameRow->show();
299 connect(ui->nameEdit, &QLineEdit::textChanged, this,
301 connect(ui->folderBox, &QComboBox::currentIndexChanged, this,
304 ui->nameEdit->setFocus();
305}
306
307auto PasswordDialog::resolveNewEntry(QString *problem) const -> QString {
308 QString name = QDir::fromNativeSeparators(ui->nameEdit->text().trimmed());
309 // The suffix belongs to the file, not the entry: Insert() appends it, so a
310 // typed "github.gpg" would otherwise become github.gpg.gpg.
311 if (name.endsWith(QStringLiteral(".gpg"), Qt::CaseInsensitive)) {
312 name.chop(4);
313 }
314 if (name.isEmpty()) {
315 *problem = tr("Give the entry a name.");
316 return {};
317 }
318 if (name.endsWith(u'/')) {
319 *problem = tr("A name cannot end in /.");
320 return {};
321 }
322 const QString folder = ui->folderBox->currentData().toString();
323 const QString rel =
324 QDir::cleanPath(folder.isEmpty() ? name : folder + u'/' + name);
325 const QString absolute = QDir(m_storeRoot).filePath(rel);
326 if (rel.isEmpty() || rel == QStringLiteral(".") ||
328 *problem = tr("That name would resolve outside the password store.");
329 return {};
330 }
331 // The tree, like `pass ls`, hides names that start with a dot: such an
332 // entry would be saved but never listed.
333 const QStringList parts = rel.split(u'/');
334 if (std::any_of(parts.cbegin(), parts.cend(),
335 [](const QString &part) { return part.startsWith(u'.'); })) {
336 *problem = tr("A name or folder that starts with a dot would be hidden "
337 "from the list.");
338 return {};
339 }
340 // Checked here, not only by Insert(): accept() creates the entry's folder
341 // first, and behind a link that folder is outside the store.
342 if (Util::isUnderLink(absolute, m_storeRoot)) {
343 *problem = tr("%1 lies behind a symbolic link or junction, outside the "
344 "password store.")
345 .arg(rel);
346 return {};
347 }
348 if (QFileInfo::exists(absolute + QStringLiteral(".gpg"))) {
349 *problem = tr("An entry called %1 already exists.").arg(rel);
350 return {};
351 }
352 if (QFileInfo(absolute).isDir()) {
353 *problem = tr("%1 is a folder.").arg(rel);
354 return {};
355 }
356 problem->clear();
357 return rel;
358}
359
360// Re-checked on every keystroke; gates OK.
362 QString problem;
363 const QString rel = resolveNewEntry(&problem);
364 ui->statusLabel->setText(problem);
365 ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(!rel.isEmpty());
366}
367
369 if (m_saving) {
370 return;
371 }
372 if (!m_storeRoot.isEmpty()) {
373 QString problem;
374 const QString rel = resolveNewEntry(&problem);
375 if (rel.isEmpty()) {
376 ui->statusLabel->setText(problem);
377 return;
378 }
379 // A name like work/vpn may need its folder; gpg does not create it.
380 const QString parent = QFileInfo(QDir(m_storeRoot).filePath(rel)).path();
381 if (!QDir(parent).exists() && !Util::mkpathForStore(parent)) {
382 ui->statusLabel->setText(
383 tr("Could not create the folder %1.").arg(parent));
384 return;
385 }
386 m_file = rel;
387 setWindowTitle(tr("Password") + QStringLiteral(" ") + m_file);
388 }
389 save();
390}
391
392void PasswordDialog::setPassword(const QString &password) {
393 // Which lines become fields is the user's choice: forcing allFields
394 // (#1138, for #132) made every `key: value` line a label-locked widget,
395 // even with templates off (#1766). MainWindow renders by the same rule.
396 FileContent fileContent =
397 FileContent::parse(password, m_templating ? m_fields : QStringList(),
399 // As stored, past the line-break filter for input: an unedited save must
400 // write the entry back exactly. The "\r" of a CRLF line end is not part of
401 // the password: it stays out of the field and is written back after it.
402 ui->lineEditPassword->setStoredText(fileContent.getPassword());
403 m_passwordLineEnd = QStringView(password)
404 .left(password.indexOf(QLatin1Char('\n')))
405 .endsWith(u'\r')
406 ? QStringLiteral("\r")
407 : QString();
408
409 QWidget *previous = ui->checkBoxShow;
410 NamedValues namedValues = fileContent.getNamedValues();
411 for (QLineEdit *line : std::as_const(m_templateLines)) {
412 const NamedValue nv = namedValues.takeNamedValue(line->objectName());
413 if (auto *secret = qobject_cast<SecretLineEdit *>(line)) {
414 secret->setStoredText(nv.value);
415 } else {
416 line->setText(nv.value);
417 }
418 line->setProperty(kOriginalLineProperty, nv.originalLine);
419 // The value is the entry's again, whatever the user typed before this
420 // reload: not a value normalizeOtpField() may rewrite.
421 line->setProperty(kOtpEditedProperty, QVariant());
422 previous = line;
423 }
424 // Remove previously created dynamic widgets to prevent duplicates and leaks
425 for (QLineEdit *line : std::as_const(m_otherLines)) {
426 ui->formLayout->removeRow(line);
427 }
428 m_otherLines.clear();
429 for (const NamedValue &nv : std::as_const(namedValues)) {
430 previous = addFieldRow(nv, previous);
431 }
432
433 // setPlainText, not insertPlainText: re-populating must replace the body,
434 // not save back a duplicated copy.
435 ui->plainTextEdit->setPlainText(fileContent.getRemainingData());
436
437 // m_otherLines was just rebuilt, so the OTP field may be a new widget.
438 hookOtpField();
439}
440
441void PasswordDialog::renameField(QLineEdit *line, FieldLabel *label,
442 const QString &to) {
443 QList<QLineEdit *> allLines(m_templateLines);
444 allLines.append(m_otherLines);
445 for (QLineEdit *other : std::as_const(allLines)) {
446 if (other != line && other->objectName() == to) {
447 ui->statusLabel->setText(tr("A field called %1 already exists.").arg(to));
448 return;
449 }
450 }
451 ui->statusLabel->clear();
452 line->setObjectName(to);
453 label->setText(to);
454 // The field may have become, or stopped being, the OTP one.
455 hookOtpField();
456}
457
458void PasswordDialog::removeField(QLineEdit *line) {
459 m_otherLines.removeAll(line);
460 // takeRow(), not removeRow(): removeRow() deletes the widgets while the
461 // label's contextMenuEvent() or the action's triggered() is still on the
462 // stack. They are deleted once the stack has unwound.
463 const QFormLayout::TakeRowResult row = ui->formLayout->takeRow(line);
464 // hide() takes the focus from a focused line, and that emits
465 // editingFinished(): not into normalizeOtpField() for a field that is
466 // being removed.
467 disconnect(line, nullptr, this, nullptr);
468 if (m_otpLine == line) {
469 m_otpLine = nullptr;
470 }
471 for (QLayoutItem *item : {row.labelItem, row.fieldItem}) {
472 if (item == nullptr) {
473 continue;
474 }
475 if (QWidget *widget = item->widget()) {
476 widget->hide();
477 widget->deleteLater();
478 }
479 delete item;
480 }
481 hookOtpField();
482}
483
484auto PasswordDialog::otpLineEdit() const -> QLineEdit * {
485 QList<QLineEdit *> allLines(m_templateLines);
486 allLines.append(m_otherLines);
487 QLineEdit *firstMatch = nullptr;
488 for (QLineEdit *line : std::as_const(allLines)) {
489 if (!FileContent::isOtpFieldName(line->objectName())) {
490 continue;
491 }
492 // Prefer a populated field: the default template's empty `OTP` widget
493 // would otherwise shadow a `TOTP:` value in m_otherLines, leaving the
494 // real secret unvalidated and unnormalised.
495 if (!line->text().trimmed().isEmpty()) {
496 return line;
497 }
498 if (firstMatch == nullptr) {
499 firstMatch = line;
500 }
501 }
502 return firstMatch;
503}
504
506 // Only m_otherLines widgets are deleted by removeRow(); a template widget
507 // keeps its action, and the next validate would add a second icon.
508 // m_otpWarning is a QPointer: null when setPassword() deleted its owner.
509 if (!m_otpWarning.isNull()) {
510 if (auto *owner = qobject_cast<QWidget *>(m_otpWarning->parent())) {
511 owner->removeAction(m_otpWarning);
512 }
513 delete m_otpWarning;
514 }
515 m_otpWarning = nullptr;
516
517 QLineEdit *otp = otpLineEdit();
518 // The field that was the OTP one may not be any more (renamed away, or
519 // another one now comes first): it stops being validated and normalised
520 // here, so its OTP hooks go with the role. Its copies are still reported.
521 if (!m_otpLine.isNull() && m_otpLine != otp) {
522 disconnect(m_otpLine, &QLineEdit::textChanged, this,
524 disconnect(m_otpLine, &QLineEdit::textEdited, this,
526 disconnect(m_otpLine, &QLineEdit::editingFinished, this,
528 }
529 m_otpLine = otp;
530 if (otp == nullptr) {
531 return;
532 }
533 otp->setPlaceholderText(tr("otpauth:// URI or base32 secret"));
534 connect(otp, &QLineEdit::textChanged, this, &PasswordDialog::validateOtpField,
535 Qt::UniqueConnection);
536 // textEdited, not textChanged: it fires only for user input, so programmatic
537 // population does not count as the user having touched the field.
538 connect(otp, &QLineEdit::textEdited, this,
539 &PasswordDialog::markOtpFieldEdited, Qt::UniqueConnection);
540 // Canonicalise as soon as the user leaves the field, so the value they end
541 // up saving is the value they were shown.
542 connect(otp, &QLineEdit::editingFinished, this,
543 &PasswordDialog::normalizeOtpField, Qt::UniqueConnection);
545}
546
548 if (QObject *line = sender()) {
549 line->setProperty(kOtpEditedProperty, true);
550 }
551}
552
554 // m_otpLine, not otpLineEdit(): the signals that bring us here and the
555 // edit mark are that line's. The OTP role is settled when fields change.
556 QLineEdit *otp = m_otpLine;
557 if (otp == nullptr) {
558 return;
559 }
560
561 const QString text = otp->text().trimmed();
563 const bool bad = !text.isEmpty() && !Totp::parse(text, &why).has_value();
564 if (bad) {
565 if (m_otpWarning.isNull()) {
566 // Theme-aware indicator: no hardcoded colours and no extra layout row.
568 otp->addAction(QIcon::fromTheme(QStringLiteral("dialog-warning")),
569 QLineEdit::TrailingPosition);
570 }
571 // The reason, where parse() names one: "invalid" alone left the user
572 // guessing whether the secret, the algorithm or the kind was wrong.
573 const QString reason = Totp::describe(why);
574 otp->setToolTip(reason.isEmpty() ? tr("Invalid OTP secret") : reason);
575 } else {
576 if (!m_otpWarning.isNull()) {
577 otp->removeAction(m_otpWarning);
578 delete m_otpWarning;
579 m_otpWarning = nullptr;
580 }
581 otp->setToolTip(QString());
582 }
583}
584
585// Only a value typed or pasted into this field is rewritten; an untouched
586// one, otpauth:// URI or not, is written back as read. Base32::sanitizeInput()
587// maps 1 to L and 8 to B, so a backup code like `12345678` passes as base32
588// and was silently rewritten on any OK. A bare secret left alone still works:
589// Totp::parse() accepts one.
591 QLineEdit *otp = m_otpLine;
592 if (otp == nullptr) {
593 return;
594 }
595 const QString text = otp->text().trimmed();
596 if (text.isEmpty()) {
597 return;
598 }
599 // Only what the user typed or pasted here: an untouched line is written
600 // back as it was read, as every other untouched line is (#2147).
601 // Canonicalising it on every OK lost parameters with capitalised names, the
602 // text after a "#", and turned backup codes into secrets.
603 if (!otp->property(kOtpEditedProperty).toBool()) {
604 return;
605 }
606 // fileName(), not completeBaseName(): the latter truncates at the last dot,
607 // turning an entry called github.com into a label of "github". m_file already
608 // has its .gpg suffix stripped by MainWindow::getFile().
609 const QString canonical = Totp::normalize(text, QFileInfo(m_file).fileName());
610 if (!canonical.isEmpty()) {
611 otp->setText(canonical);
612 }
613}
614
616 QString passFile = ui->lineEditPassword->text() + m_passwordLineEnd + "\n";
617 QList<QLineEdit *> allLines(m_templateLines);
618 allLines.append(m_otherLines);
619 for (QLineEdit *line : std::as_const(allLines)) {
620 const QString text = line->text();
621 const QString name = line->objectName();
622 const QString original = line->property(kOriginalLineProperty).toString();
623 // A field whose name and value are still exactly what was parsed keeps its
624 // source line verbatim: reserialising would turn `key:value` into
625 // `key: value`, trim whitespace the value carried, and drop a field with an
626 // empty value (`recovery:`) entirely. The widget holds trimmed name/value,
627 // so compare against the original line split and trimmed the same way.
628 if (!original.isEmpty()) {
629 const qsizetype colon = original.indexOf(QLatin1Char(':'));
630 if (colon >= 0 && original.left(colon).trimmed() == name &&
631 original.right(original.length() - colon - 1).trimmed() == text) {
632 passFile += original + "\n";
633 continue;
634 }
635 }
636 if (text.isEmpty()) {
637 continue;
638 }
639 passFile += name + ": " + text + "\n";
640 }
641 // Not toPlainText(): it saves a blank for every no-break space (U+00A0) in
642 // the notes, so any OK rewrites even lines the user never touched and a
643 // passphrase or recovery code with no-break spaces is corrupted. The raw
644 // document text keeps the no-break spaces; only the block and line
645 // separators it uses are normalised back to '\n'.
646 QString notes = ui->plainTextEdit->document()->toRawText();
647 notes.replace(QChar(QChar::ParagraphSeparator), QLatin1Char('\n'));
648 notes.replace(QChar(QChar::LineSeparator), QLatin1Char('\n'));
649 passFile += notes;
650 return passFile;
651}
652
653void PasswordDialog::setTemplate(const QString &rawFields, bool useTemplate) {
654 m_fields = TemplateIO::fieldsIn(rawFields);
655 m_templating = useTemplate;
656
657 // removeRow() deletes the line edits, text and all, so what the rows hold
658 // is carried over: switching the template, or Ctrl+T (which with a single
659 // template rebuilds the same rows), used to empty everything typed into
660 // them. A value the new template has a row for goes there; any other stays
661 // a field row of its own, so nothing is dropped and nothing is doubled.
662 NamedValues held;
663 QSet<QString> otpTyped;
664 const auto holdAndRemove = [this, &held,
665 &otpTyped](QList<QLineEdit *> &lines) {
666 for (QLineEdit *line : std::as_const(lines)) {
667 const QString original = line->property(kOriginalLineProperty).toString();
668 // A stored field with no value ("recovery:") has an empty row but a
669 // source line, which getPassword() writes back as it was: keep it too.
670 if (!line->text().isEmpty() || !original.isEmpty()) {
671 held.append({line->objectName(), line->text(), original});
672 if (line->property(kOtpEditedProperty).toBool()) {
673 otpTyped.insert(line->objectName());
674 }
675 }
676 ui->formLayout->removeRow(line);
677 }
678 lines.clear();
679 };
680 holdAndRemove(m_templateLines);
681 holdAndRemove(m_otherLines);
682
683 QWidget *previous = ui->checkBoxShow;
684 if (m_templating) {
685 for (const QString &field : std::as_const(m_fields)) {
686 if (field.isEmpty()) {
687 continue;
688 }
689 auto *line = new SecretLineEdit();
690 reportCopies(line);
691 // Plain text before the name is set: the template comes from the
692 // store, and as rich text <img src="/dev/zero"> has Qt read that file
693 // without end.
694 auto *label = new QLabel();
695 label->setTextFormat(Qt::PlainText);
696 label->setText(field);
697 line->setObjectName(field);
698 const NamedValue kept = held.takeNamedValue(field);
699 if (!kept.name.isEmpty()) {
700 line->setStoredText(kept.value);
701 line->setProperty(kOriginalLineProperty, kept.originalLine);
702 if (otpTyped.contains(field)) {
703 line->setProperty(kOtpEditedProperty, true);
704 }
705 }
706 ui->formLayout->addRow(label, line);
707 setTabOrder(previous, line);
708 m_templateLines.append(line);
709 previous = line;
710 }
711 }
712 for (const NamedValue &field : std::as_const(held)) {
713 SecretLineEdit *line = addFieldRow(field, previous);
714 // A typed OTP value keeps its mark in a field row too, so save() still
715 // turns a bare secret into an otpauth:// URI.
716 if (otpTyped.contains(field.name)) {
717 line->setProperty(kOtpEditedProperty, true);
718 }
719 previous = line;
720 }
721
722 hookOtpField();
723}
724
728
729auto PasswordDialog::addFieldRow(const NamedValue &field, QWidget *previous)
730 -> SecretLineEdit * {
731 auto *line = new SecretLineEdit();
732 reportCopies(line);
733 line->setObjectName(field.name);
734 line->setStoredText(field.value);
735 line->setProperty(kOriginalLineProperty, field.originalLine);
736 auto *label = new FieldLabel(field.name);
737 label->setBuddy(line);
738 ui->formLayout->addRow(label, line);
739 setTabOrder(previous, line);
740 m_otherLines.append(line);
741 // Both widgets are rows of the form; removeRow() deletes them together,
742 // so a rename or removal that arrives afterwards finds no receiver.
743 connect(label, &FieldLabel::renamed, this,
744 [this, line, label](const QString &, const QString &to) {
745 renameField(line, label, to);
746 });
747 connect(label, &FieldLabel::removeRequested, this,
748 [this, line] { removeField(line); });
749 // The visible way to remove the field; the context menu is the other.
750 auto *remove = line->addAction(
751 QIcon::fromTheme(QStringLiteral("edit-delete"),
752 QIcon(QStringLiteral(":/icons/edit-delete.svg"))),
753 QLineEdit::TrailingPosition);
754 remove->setObjectName(QStringLiteral("removeFieldAction"));
755 remove->setToolTip(tr("Remove field"));
756 connect(remove, &QAction::triggered, this,
757 [this, line] { removeField(line); });
758 return line;
759}
760
764
766 ui->spinBox_pwdLength->setValue(length);
767}
768
770 ui->passwordTemplateSwitch->setCurrentIndex(templateIndex);
771}
772
775 ui->passwordTemplateSwitch->setDisabled(usePwgen);
776 ui->label_characterset->setDisabled(usePwgen);
777}
778
779// The template row stays hidden until setAvailableTemplates() fills it.
781 ui->label_template->hide();
782 ui->templateBox->hide();
783 connect(ui->templateBox, &QComboBox::currentTextChanged, this,
784 [this](const QString &name) {
785 // applyTemplate() rebuilds the field rows, so only act on a real
786 // change; the box is also updated from applyTemplate() itself.
787 if (name != m_currentTemplateName) {
788 applyTemplate(name);
789 }
790 });
791}
792
794 const QHash<QString, QStringList> &templates,
795 const QString &defaultTemplate) {
796 m_availableTemplates = templates;
797 QStringList templateNames = templates.keys();
798 if (templateNames.isEmpty()) {
799 return;
800 }
801 std::sort(templateNames.begin(), templateNames.end());
802 {
803 const QSignalBlocker blocker(ui->templateBox);
804 ui->templateBox->clear();
805 ui->templateBox->addItems(templateNames);
806 }
807 ui->label_template->show();
808 ui->templateBox->show();
809 if (!m_templateShortcut) {
810 m_templateShortcut = new QShortcut(QKeySequence(Qt::CTRL | Qt::Key_T), this,
811 this, [this] { cycleTemplate(); });
812 }
813 QString selected = defaultTemplate;
814 if (!templateNames.contains(selected)) {
815 selected = templateNames.first();
816 }
817 applyTemplate(selected);
818}
819
820void PasswordDialog::applyTemplate(const QString &templateName) {
821 if (m_saving) {
822 return;
823 }
824 auto it = m_availableTemplates.constFind(templateName);
825 if (it != m_availableTemplates.constEnd()) {
826 m_currentTemplateName = templateName;
827 const QSignalBlocker blocker(ui->templateBox);
828 ui->templateBox->setCurrentText(templateName);
829 QString fields = it.value().join("\n");
830 setTemplate(fields, true);
831 }
832}
833
835 if (m_availableTemplates.isEmpty()) {
836 return;
837 }
838 QStringList names = m_availableTemplates.keys();
839 std::sort(names.begin(), names.end());
840
841 qsizetype currentIdx = names.indexOf(m_currentTemplateName);
842 qsizetype nextIdx;
843 if (currentIdx < 0) {
844 nextIdx = 0;
845 } else {
846 nextIdx = (currentIdx + 1) % names.size();
847 }
848 // With a single template there is nothing to switch to: leave the rows,
849 // and the cursor in them, alone.
850 if (names.at(nextIdx) == m_currentTemplateName) {
851 return;
852 }
853 applyTemplate(names.at(nextIdx));
854}
855
856void PasswordDialog::setPass(const QString &output, const QString &file,
857 bool lossless) {
858 // finishedShow names its file: a decrypt of any other entry (a tree click
859 // that was still queued when the dialog opened) is not ours.
860 if (!file.isEmpty() && file != m_file) {
861 return;
862 }
863 // A refusal also takes back an earlier load of this entry: a later answer
864 // for it says the entry is not one this dialog can save, so OK must not
865 // write what was loaded before.
866 const auto refuse = [this](const QString &why) {
867 m_contentLoaded = false;
868 setEditorEnabled(false);
869 ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
870 ui->statusLabel->setText(why);
871 };
872 // Bytes that are not UTF-8 (a password typed on a Latin-1 terminal, a key
873 // file stored with `pass insert -m`) reach here as U+FFFD (on Windows as
874 // characters of the code page), a leading byte order mark not at all, and
875 // OK writes the whole entry back from this text: those bytes were changed
876 // for good, with the save reported as done. Not loaded, as below, so nothing
877 // is saved over the entry; showing and copying it are unaffected.
878 if (!lossless) {
879 refuse(tr("This entry contains bytes QtPass cannot save unchanged, so it "
880 "cannot be edited here."));
881 return;
882 }
883 // An editor block per line: an entry of millions of lines (a small,
884 // compressed one in a shared store can be one) would take QtPass down.
885 // Not loaded at all, so nothing can be saved over it from here either.
886 // Counted as an editor of the whole entry would hold it: the final
887 // newline pass and QtPass write ends the last line, it starts no new one.
888 // Password and fields count too, so this is stricter than the display's
889 // limit on the remaining text alone.
890 if (const qsizetype lines =
891 output.count(QLatin1Char('\n')) +
892 (output.isEmpty() || output.endsWith(QLatin1Char('\n')) ? 0 : 1);
894 // The count in a variable first, as in FileContent: older lupdate
895 // versions lose a tr() with template arguments among its arguments.
896 const int n = static_cast<int>(
897 std::min<qsizetype>(lines, std::numeric_limits<int>::max()));
898 refuse(tr("This entry has %n line(s), too many to edit here.", nullptr, n));
899 return;
900 }
901 setPassword(output);
902 m_contentLoaded = true;
903 // Drop the "Decrypting…" note so it cannot be mistaken for a warning.
904 ui->statusLabel->clear();
905 setEditorEnabled(true);
906 ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true);
907}
908
909void PasswordDialog::onShowError(int /* exitCode */, const QString &err) {
910 // React only while the dialog is still waiting for its own decrypt.
911 // processErrorExit carries no request identity, but for an existing entry
912 // the only Pass operation in flight is the Show() that opened this dialog.
913 if (m_isNew || m_contentLoaded) {
914 return;
915 }
916 ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false);
917 setEditorEnabled(false);
918 ui->statusLabel->setText(err);
919}
920
922 ui->lineEditPassword->setEnabled(enabled);
923 ui->createPasswordButton->setEnabled(enabled);
924 ui->checkBoxShow->setEnabled(enabled);
925 ui->passwordTemplateSwitch->setEnabled(enabled);
926 ui->label_characterset->setEnabled(enabled);
927 ui->spinBox_pwdLength->setEnabled(enabled);
928 ui->plainTextEdit->setEnabled(enabled);
929 for (QLineEdit *line : std::as_const(m_templateLines)) {
930 line->setEnabled(enabled);
931 }
932 for (QLineEdit *line : std::as_const(m_otherLines)) {
933 line->setEnabled(enabled);
934 }
935 // Re-apply the pwgen policy on the way back up, or the two widgets usePwgen()
936 // locks would be spuriously re-enabled with the rest of the editor.
937 if (enabled && m_usePwgen) {
938 usePwgen(true);
939 }
940}
The name of a key: value field in PasswordDialog, editable in place: double-click or the context menu...
Definition fieldlabel.h:26
FieldLabel(const QString &name, QWidget *parent=nullptr)
Label for the field called name.
void removeRequested()
The user chose "Remove field".
void renamed(const QString &from, const QString &to)
The user typed a different name and confirmed it.
Represents the parsed contents of a password file.
Definition filecontent.h:92
static auto isOtpFieldName(const QString &name) -> bool
Whether a field name designates the one-time password field.
static constexpr int kMaxDisplayLines
Most lines of remaining text getRemainingDataForDisplay() gives.
auto getRemainingData() const -> QString
auto getNamedValues() const -> NamedValues
static auto parse(const QString &fileContent, const QStringList &templateFields, bool allFields, const std::function< bool(const QString &)> &alsoField={}) -> FileContent
parse parses the given fileContent in a FileContent object. The password is accessible through getPas...
auto getPassword() const -> QString
The password: the first line, without the "\r" of a CRLF line end (passwordLine()).
The NamedValues class is mostly a list of NamedValue but also has a method to take a specific NamedVa...
Definition filecontent.h:58
auto takeNamedValue(const QString &name) -> NamedValue
Remove and return the named field, its original line included.
Abstract base class for password store operations.
Definition pass.h:76
void finishedInsert(const QString &out, const QString &err)
An Insert() succeeded: the entry is in the store and, with Git in use, committed.
virtual auto generatePassword(unsigned int length, const QString &charset) -> QString
Generate random password.
Definition pass.cpp:219
void insertFailed(const QString &err, bool written)
Emitted when an Insert() fails through a queued command, before the generic processErrorExit(): the p...
virtual void Show(QString file)=0
Show decrypted password file.
void finishedShow(const QString &out, const QString &file, bool lossless=true)
Emitted when a Show() succeeds.
virtual void Insert(QString file, QString value, bool force)=0
Insert or update password.
void processErrorExit(int exitCode, const QString &err)
An operation ended in failure: its process exited non-zero, could not be started or crashed,...
auto insertsPending() const -> int
How many inserts have started queueing but not yet reported.
Definition pass.h:202
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...
void validateOtpField()
Flag an OTP value that is neither a URI nor valid base32.
QScopedPointer< Ui::PasswordDialog > ui
Generated form (passworddialog.ui); owned.
bool m_templating
Whether template fields get widgets of their own (the "Use template" setting).
void hookOtpField()
Connect validation and normalisation to the OTP field, if present.
QList< QLineEdit * > m_otherLines
QStringList m_fields
Field names of the current template, in template order.
void onInsertFailed(const QString &err, bool written)
The insert started by accept() failed: unlock the fields, which still hold what was typed,...
void setPassword(const QString &password)
Populate the dialog's password field with the given text.
QString m_newEntryFolder
void setSaving(bool saving)
Lock or unlock the dialog while an insert is in flight.
void validateNewEntry()
Re-runs resolveNewEntry() as the user types or picks a folder: shows the problem (if any) in the stat...
Pass * m_pass
Backend for Show, Insert and generatePassword; not owned.
void cycleTemplate()
Cycle to next template (Ctrl+T).
void setAvailableTemplates(const QHash< QString, QStringList > &templates, const QString &defaultTemplate)
Set available templates from file and select default.
void setupTemplateBox()
Hides the template row until setAvailableTemplates() fills it and wires the combo box so that a user ...
void normalizeOtpField()
Rewrite the OTP field as a canonical otpauth URI.
bool m_allFields
Whether every key: value line becomes a field (the "Templateall fields" setting), as given to FileCon...
void showNotSaved(const QString &err)
Say why the entry was not saved and let the user try again; the fields keep what was typed.
void accept() override
OK: for a new entry, resolve and check the name first and stay open when it is not usable; then inser...
auto otpLineEdit() const -> QLineEdit *
Locate the field that holds the one-time password configuration.
void save()
Start inserting what the dialog holds and wait for the result.
auto addFieldRow(const NamedValue &field, QWidget *previous) -> SecretLineEdit *
Adds a row for a field outside the template: a FieldLabel that can be renamed or removed,...
PasswordDialog(PasswordConfiguration passConfig, QWidget *parent=nullptr)
Construct a PasswordDialog for entering a new password.
bool m_isNew
True when creating an entry, false when editing one; decides whether the name row and the decrypt-bef...
void setLength(int length)
Set the desired password length shown in the dialog.
void reject() override
Cancel, Esc and the window's close button. While an insert is in flight they ask first: closing then ...
void setPasswordVisible(bool show)
Show or mask the password field.
QHash< QString, QStringList > m_availableTemplates
QString m_file
Entry path relative to the store, without .gpg; empty for a new entry until accept() resolves the typ...
bool m_saving
True from accept() starting an insert until the backend reports back.
QShortcut * m_templateShortcut
Ctrl+T, created once templates are available; owned by the dialog.
void setEditorEnabled(bool enabled)
Enabled or grey out every editable field of the dialog.
void onShowError(int exitCode, const QString &err)
Handle a process error while waiting for an entry's decrypt.
void removeField(QLineEdit *line)
Drop a key: value field and its row from the form. The widgets are deleted once control is back in th...
QString m_storeRoot
Absolute store root while a new entry is being named; empty otherwise.
void copied(const QString &text)
Text was copied out of the password, a field or the body, marked as a secret: for ClipboardManager::t...
void setNewEntryLocation(const QString &storeRoot, const QStringList &folders, const QString &currentFolder)
Let a new entry be named inside the dialog: a folder picker over the store's folders and a name field...
void setPass(const QString &output, const QString &file=QString(), bool lossless=true)
Populate the dialog from a decrypted entry (Pass::finishedShow).
void renameField(QLineEdit *line, FieldLabel *label, const QString &to)
Give a key: value field a new key (#132). Refused, with the reason in the status label,...
auto isOwnInsertReport() -> bool
Whether the insert report now arriving is this dialog's own.
~PasswordDialog() override
Hides the window before QDialog tears it down, so the focus-out emitted on hiding cannot reach slots ...
PasswordConfiguration m_passConfig
Generator settings: character sets and default length.
auto resolveNewEntry(QString *problem) const -> QString
The name the user typed, resolved against the picked folder.
void usePwgen(bool usePwgen)
Enable or disable pwgen-style password generation mode.
void setPasswordCharTemplate(int templateIndex)
Set the password character template index.
QString m_passwordLineEnd
void setTemplate(const QString &rawFields, bool useTemplate)
Set the template fields and whether templating is enabled.
void templateAll(bool templateAll)
Whether every key: value line becomes a field of its own.
void reportCopies(SecretLineEdit *line)
Forwards the line edit's SecretLineEdit::copied to this dialog's copied(), so every copy out of any f...
auto getPassword() -> QString
Retrieve the current text from the dialog's password field.
void markOtpFieldEdited()
Remember, on the line edit that sent textEdited(), that the user typed in it: only such a field has a...
void on_rejected()
Connected to QDialog::rejected: blanks the password and field widgets so the decrypted secret does no...
void onInsertFinished()
The insert started by accept() succeeded: close as accepted.
QList< QLineEdit * > m_templateLines
QPointer< QLineEdit > m_otpLine
void applyTemplate(const QString &templateName)
Switch to a named template: records it, selects it in the combo box and rebuilds the field rows throu...
void on_createPasswordButton_clicked()
"Generate" button: asks the backend for a password of the chosen length from the selected character s...
QString m_currentTemplateName
Name of the template currently applied; cycleTemplate() steps from it.
QPointer< QAction > m_otpWarning
static auto isPathInStore(const QString &storeRoot, const QString &candidate) -> bool
Check that a candidate path resolves inside the password store root, after following symlinks and res...
Singleton that stores QtPass settings, handles persistence and defaults.
A QLineEdit for a password that can be shown: whatever is copied out of it is marked as a secret and ...
void copied(const QString &text)
Selected text was copied out of the line edit.
SecretLineEdit(QWidget *parent=nullptr)
Constructs the line edit.
void copied(const QString &text)
Selected text was copied or cut out of the editor.
static auto fieldsIn(const QString &templateText) -> QStringList
The field names of the template in the settings: one per line, with comment lines (starting with #,...
static auto parse(const QString &config, Refusal *why=nullptr) -> std::optional< Settings >
Parse an OTP configuration string.
Definition totp.cpp:123
static auto normalize(const QString &config, const QString &label={}, const QString &issuer={}) -> QString
Normalise a user-entered value to a canonical otpauth URI.
Definition totp.cpp:407
static auto describe(Refusal why) -> QString
One sentence for the user on why a configuration gives no code.
Definition totp.cpp:274
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 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...
Definition util.cpp:858
static auto mkpathForStore(const QString &path) -> bool
Create path and any missing parents as pass would.
Definition util.cpp:448
FieldLabel: the in-place renamable, removable name label of a key: value field in PasswordDialog.
Parser for a decrypted password entry: password line, key: value fields, remaining text and the OTP c...
Pass, the abstract password-store backend that RealPass and ImitatePass implement,...
Value object for the password generator: chosen character set, its alphabets and the length.
Dialog for creating or editing one password entry, including the generator, template fields,...
PathValidator: is a path inside the password store, and how is it spelled relative to the store root.
The "qtpass" logging category.
QtPassSettings, the QSettings singleton behind every saved setting, the profiles and the Pass backend...
QLineEdit whose copies, cuts and primary-selection fills carry the secret clipboard hints and are rep...
QPlainTextEdit for editing 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 usePwgen
Use pwgen for password generation.
QString passTemplate
Newline-separated template field names.
bool templateAllFields
Treat every key: line as a field.
bool useTemplate
Use the password template.
PasswordConfiguration passwordConfiguration
Length/charset/custom chars.
A name/value pair parsed from a password file field.
Definition filecontent.h:21
QString name
Field name (the part before the colon in "name: value").
Definition filecontent.h:25
QString originalLine
The field's verbatim source line, colon and spacing intact.
Definition filecontent.h:38
QString value
Field value (the part after the colon in "name: value").
Definition filecontent.h:29
Holds the password generator settings: which character set is selected, the alphabet of every set,...
int length
Length of the generated password, in characters.
CharacterSet selected
Currently active character set selection.
QString Characters[CHARSETS_COUNT]
The alphabet of each character set, indexed by CharacterSet. Only the CUSTOM entry is meant to be cha...
CharacterSet
Character set options for password generation; also the index into Characters.
TemplateIO: the store's .templates and .default_template files and the # secret: marker in template t...
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...