QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
storemodel.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2014 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
8#include "storemodel.h"
9#include "pass.h"
10#include "pathvalidator.h"
11#include "plainmessagebox.h"
12#include "qtpasslogging.h"
13#include "util.h"
14#include <QApplication>
15#include <QDebug>
16#include <QFileInfo>
17#include <QFileSystemModel>
18#include <QMessageBox>
19#include <QMimeData>
20#include <QRegularExpression>
21#include <QtGlobal>
22
23auto operator<<(QDataStream &out, const StoreDragItem &item) -> QDataStream & {
24 out << static_cast<quint8>(item.kind) << item.path;
25 return out;
26}
27
28auto operator>>(QDataStream &in, StoreDragItem &item) -> QDataStream & {
29 quint8 k;
30 in >> k >> item.path;
31 switch (k) {
32 case static_cast<quint8>(StoreDragItem::ItemKind::Directory):
34 break;
35 case static_cast<quint8>(StoreDragItem::ItemKind::File):
37 break;
38 default:
40 break;
41 }
42 return in;
43}
44
45// Filter approach via http://www.qtcentre.org/threads/46471-QTreeView-Filter
46StoreModel::StoreModel() { fs = nullptr; }
47
48void StoreModel::setPass(Pass *pass) { m_pass = pass; }
49
51 const QModelIndex &sourceParent) const
52 -> bool {
53 QModelIndex index = sourceModel()->index(sourceRow, 0, sourceParent);
54 return showThis(index);
55}
56
57auto StoreModel::showThis(const QModelIndex &index) const -> bool {
58 if (fs == nullptr) {
59 return false;
60 }
61 // Through filePath() a filter pass cost entries times sibling folders,
62 // again on every key typed in the search.
63 const QString filePath = pathOf(index);
64 QString path = QDir(store).relativeFilePath(filePath);
65 // Only what lies in the current store. The file system model keeps the
66 // rows of a store shown earlier (a profile switch only re-roots it), and
67 // a search would otherwise match those, open one and save it encrypted
68 // to this store's recipients. Folders above the store still lead there.
69 const bool outside = path == QLatin1String("..") ||
70 path.startsWith(QLatin1String("../")) ||
72 // A link inside the store is neither an entry nor a folder (SECURITY.md):
73 // it is listed by its name, so it can be deleted, but never entered. A
74 // planted `x -> .` was an endlessly expandable folder, and the search's
75 // expandAll() loaded it level after level until memory ran out.
76 const bool inside = !outside && path != QLatin1String(".");
77 if (inside && Util::isUnderLink(filePath, store, false)) {
78 return false;
79 }
80 const bool link = inside && Util::isLinkedFolder(filePath);
81 if (!link && sourceModel()->rowCount(index) > 0) {
82 return showsFolder(index, path, inside, outside);
83 }
84 if (outside || path.startsWith(".git")) {
85 return false;
86 }
87 // As data() shows it: ".gpg" is dropped from an entry's name only.
88 // The model knows a row's kind without a stat.
89 if (!(fs != nullptr ? fs->isDir(index) : QFileInfo(filePath).isDir())) {
90 path.replace(Util::endsWithGpg(), "");
91 }
92 return path.contains(filterRegularExpression());
93}
94
95auto StoreModel::showsFolder(const QModelIndex &index, const QString &path,
96 bool inside, bool outside) const -> bool {
97 for (int nChild = 0; nChild < sourceModel()->rowCount(index); ++nChild) {
98 const QModelIndex childIndex = sourceModel()->index(nChild, 0, index);
99 if (!childIndex.isValid()) {
100 break;
101 }
102 if (showThis(childIndex)) {
103 return true;
104 }
105 }
106 // Or, in a search, by its own name as data() shows it: `admins.gpg` is
107 // found by that name even when none of its entries is. Without a search
108 // a folder still shows only for what it holds, so .git and folders of
109 // other files stay out.
110 return inside && !outside && !path.startsWith(QLatin1String(".git")) &&
111 !filterRegularExpression().pattern().isEmpty() &&
112 path.contains(filterRegularExpression());
113}
114
115auto StoreModel::wordsFilter(const QString &query) -> QRegularExpression {
116 // Regular expressions belong to the content search; here a typed "[" or
117 // "(" must not switch filtering off, so each word is escaped.
118 QString pattern;
119 const QStringList words = query.split(QLatin1Char(' '), Qt::SkipEmptyParts);
120 for (const QString &word : words) {
121 pattern += QStringLiteral("(?>.*?") + QRegularExpression::escape(word) +
122 QLatin1Char(')');
123 }
124 if (pattern.isEmpty()) {
125 return {};
126 }
127 return QRegularExpression(QLatin1Char('^') + pattern,
128 QRegularExpression::CaseInsensitiveOption |
129 QRegularExpression::DotMatchesEverythingOption);
130}
131
132auto StoreModel::isLinkInStore(const QModelIndex &proxyIndex) const -> bool {
133 if (fs == nullptr || !proxyIndex.isValid()) {
134 return false;
135 }
136 // The same path showThis() lists the row by, or a link it lists would
137 // still get an expand arrow on Windows.
138 const QString filePath = pathOf(mapToSource(proxyIndex));
139 const QString path = QDir(store).relativeFilePath(filePath);
140 if (path == QLatin1String(".") || path == QLatin1String("..") ||
141 path.startsWith(QLatin1String("../")) || Util::isAbsoluteFsPath(path)) {
142 return false;
143 }
144 return Util::isLinkedFolder(filePath);
145}
146
147auto StoreModel::pathOf(const QModelIndex &sourceIndex) const -> QString {
148 // filePath() only for a node that has no file information yet.
149 const QFileInfo info = fs->fileInfo(sourceIndex);
150 return info.filePath().isEmpty() ? fs->filePath(sourceIndex)
151 : info.absoluteFilePath();
152}
153
154// NOLINTNEXTLINE(google-default-arguments): see the declaration.
155auto StoreModel::hasChildren(const QModelIndex &parent) const -> bool {
156 return !isLinkInStore(parent) && QSortFilterProxyModel::hasChildren(parent);
157}
158
159auto StoreModel::canFetchMore(const QModelIndex &parent) const -> bool {
160 return !isLinkInStore(parent) && QSortFilterProxyModel::canFetchMore(parent);
161}
162
163void StoreModel::fetchMore(const QModelIndex &parent) {
164 if (!isLinkInStore(parent)) {
165 QSortFilterProxyModel::fetchMore(parent);
166 }
167}
168
169void StoreModel::setModelAndStore(QFileSystemModel *sourceModel,
170 const QString &passStore) {
171 setSourceModel(sourceModel);
172 fs = sourceModel;
173 store = passStore;
174}
175
176auto StoreModel::rootIndexFor(const QString &path) -> QModelIndex {
177 if (fs == nullptr) {
178 return {};
179 }
180 return mapFromSource(fs->setRootPath(QDir::cleanPath(path)));
181}
182
183void StoreModel::setStore(const QString &passStore) {
184#if QT_VERSION >= QT_VERSION_CHECK(6, 10, 0)
185 // The Direction-scoped endFilterChange() overload needs Qt 6.10.
186 beginFilterChange();
187 store = passStore;
188 endFilterChange(QSortFilterProxyModel::Direction::Rows);
189#else
190 store = passStore;
191 invalidateFilter();
192#endif
193}
194
195auto StoreModel::data(const QModelIndex &index, int role) const -> QVariant {
196 if (!index.isValid()) {
197 return {};
198 }
199
200 QVariant initial_value;
201 initial_value = QSortFilterProxyModel::data(index, role);
202
203 // ".gpg" ends an entry's name, not a folder's: a folder renamed to
204 // "admins.gpg" is shown as that, not as the "admins" it may stand in for.
205 if (role == Qt::DisplayRole &&
206 !(fs != nullptr && fs->isDir(mapToSource(index)))) {
207 QString name = initial_value.toString();
208 name.replace(Util::endsWithGpg(), "");
209 initial_value.setValue(name);
210 }
211
212 return initial_value;
213}
214
215auto StoreModel::supportedDropActions() const -> Qt::DropActions {
216 return Qt::CopyAction | Qt::MoveAction;
217}
218
219auto StoreModel::supportedDragActions() const -> Qt::DropActions {
220 return Qt::CopyAction | Qt::MoveAction;
221}
222
223auto StoreModel::flags(const QModelIndex &index) const -> Qt::ItemFlags {
224 Qt::ItemFlags defaultFlags = QSortFilterProxyModel::flags(index);
225
226 if (index.isValid()) {
227 return Qt::ItemIsDragEnabled | Qt::ItemIsDropEnabled | defaultFlags;
228 }
229 return Qt::ItemIsDropEnabled | defaultFlags;
230}
231
232auto StoreModel::mimeTypes() const -> QStringList {
233 QStringList types;
234 types << kStoreDragMimeType;
235 return types;
236}
237
238auto StoreModel::mimeData(const QModelIndexList &indexes) const -> QMimeData * {
239 StoreDragItem info;
240
241 if (indexes.isEmpty())
242 return nullptr;
243 QByteArray encodedData;
244 // only use the first, otherwise we should enable multiselection
245 QModelIndex index = indexes.at(0);
246 if (index.isValid()) {
247 QModelIndex useIndex = mapToSource(index);
248 const QFileInfo fileInfo = fs->fileInfo(useIndex);
249
250 if (fileInfo.isDir()) {
252 } else if (fileInfo.isFile()) {
254 }
255 info.path = fileInfo.absoluteFilePath();
256 QDataStream stream(&encodedData, QIODevice::WriteOnly);
257 stream << info;
258 }
259
260 auto *mimeData = new QMimeData();
261 mimeData->setData(kStoreDragMimeType, encodedData);
262 return mimeData;
263}
264
265auto StoreModel::canDropMimeData(const QMimeData *data, Qt::DropAction action,
266 int row, int column,
267 const QModelIndex &parent) const -> bool {
268 qCDebug(lcQtPass) << "canDropMimeData" << action << row;
269
270 const auto parsed = parseDropData(data);
271 if (!parsed) {
272 return false;
273 }
274 const StoreDragItem &info = *parsed;
275
276 QModelIndex useIndex =
277 this->index(parent.row(), parent.column(), parent.parent());
278
279 if (column > 0) {
280 return false;
281 }
282
283 using IK = StoreDragItem::ItemKind;
284 // you can drop a folder on a folder
285 if (fs->fileInfo(mapToSource(useIndex)).isDir() &&
286 info.kind == IK::Directory) {
287 return true;
288 }
289 // you can drop a file on a folder
290 if (fs->fileInfo(mapToSource(useIndex)).isDir() && info.kind == IK::File) {
291 return true;
292 }
293 // you can drop a file on a file
294 if (fs->fileInfo(mapToSource(useIndex)).isFile() && info.kind == IK::File) {
295 return true;
296 }
297
298 return false;
299}
300
301auto StoreModel::dropMimeData(const QMimeData *data, Qt::DropAction action,
302 int row, int column, const QModelIndex &parent)
303 -> bool {
304 if (!canDropMimeData(data, action, row, column, parent)) {
305 return false;
306 }
307
308 if (action == Qt::IgnoreAction) {
309 return true;
310 }
311
312 if (action != Qt::MoveAction && action != Qt::CopyAction) {
313 return false;
314 }
315
316 const auto info = parseDropData(data);
317 if (!info) {
318 return false;
319 }
320
321 return executeDropAction(*info, action, parent);
322}
323
324auto StoreModel::parseDropData(const QMimeData *data)
325 -> std::optional<StoreDragItem> {
326 if (data == nullptr || !data->hasFormat(kStoreDragMimeType)) {
327 return std::nullopt;
328 }
329 QByteArray encodedData = data->data(kStoreDragMimeType);
330 if (encodedData.isEmpty()) {
331 return std::nullopt;
332 }
333 QDataStream stream(&encodedData, QIODevice::ReadOnly);
334 StoreDragItem info;
335 stream >> info;
336 if (stream.status() != QDataStream::Ok) {
337 return std::nullopt;
338 }
339 return info;
340}
341
343 Qt::DropAction action,
344 const QModelIndex &parent) -> bool {
345 QModelIndex destIndex =
346 this->index(parent.row(), parent.column(), parent.parent());
347 QFileInfo destFileinfo = fs->fileInfo(mapToSource(destIndex));
348 QFileInfo srcFileInfo = QFileInfo(info.path);
349
350 QString cleanedSrc = QDir::cleanPath(srcFileInfo.absoluteFilePath());
351 QString cleanedDest = QDir::cleanPath(destFileinfo.absoluteFilePath());
352
353 // Drop data could be crafted: both endpoints must resolve inside the store
354 // after symlink resolution (e.g. no in-store symlink pointing at /etc).
355 if (!PathValidator::isPathInStore(store, cleanedSrc) ||
356 !PathValidator::isPathInStore(store, cleanedDest)) {
357 qCWarning(lcQtPass)
358 << "executeDropAction: rejecting drop that escapes the store"
359 << "(src=" << cleanedSrc << "dest=" << cleanedDest << ")";
360 return false;
361 }
362
363 switch (info.kind) {
365 // Dropping a folder onto a folder: move/copy it *into* the target.
366 if (!destFileinfo.isDir()) {
367 return false;
368 }
369 const QString destDir =
370 QDir::cleanPath(Util::joinPath(cleanedDest, srcFileInfo.fileName()));
371 return performDrop(cleanedSrc, destDir, action, false);
372 }
374 // File onto a folder drops into it (no clash); file onto an existing
375 // file asks before overwriting.
376 if (destFileinfo.isDir()) {
377 return performDrop(cleanedSrc, cleanedDest, action, false);
378 }
379 return performDrop(cleanedSrc, cleanedDest, action,
381 qobject_cast<QWidget *>(QObject::parent()),
382 tr("Force overwrite?"),
383 tr("overwrite %1 with %2?")
384 .arg(Util::displayable(cleanedDest, false),
385 Util::displayable(cleanedSrc, false))));
386 default:
387 qCWarning(lcQtPass)
388 << "executeDropAction: unexpected ItemKind, ignoring drop";
389 return false;
390 }
391}
392
393auto StoreModel::performDrop(const QString &cleanedSrc,
394 const QString &cleanedDest, Qt::DropAction action,
395 bool force) -> bool {
396 if (!m_pass) {
397 return false;
398 }
399 // The pass backend re-encrypts the whole destination folder: asked first
400 // when an entry already there would gain a reader it does not have.
401 if (!PlainMessageBox::confirmPassRun(QApplication::activeWindow(), store,
402 [this, &cleanedSrc, &cleanedDest] {
403 return m_pass->entriesMoveWouldWiden(
404 cleanedSrc, cleanedDest);
405 })) {
406 return false;
407 }
408 if (action == Qt::MoveAction) {
409 m_pass->Move(cleanedSrc, cleanedDest, force);
410 } else if (action == Qt::CopyAction) {
411 m_pass->Copy(cleanedSrc, cleanedDest, force);
412 }
413 return true;
414}
415
416auto StoreModel::lessThan(const QModelIndex &source_left,
417 const QModelIndex &source_right) const -> bool {
418/* matches logic in QFileSystemModelSorter::compareNodes() */
419#ifndef Q_OS_MAC
420 if (fs && (source_left.column() == 0 || source_left.column() == 1)) {
421 bool leftD = fs->isDir(source_left);
422 bool rightD = fs->isDir(source_right);
423
424 if (leftD ^ rightD) {
425 return leftD;
426 }
427 }
428#endif
429
430 return QSortFilterProxyModel::lessThan(source_left, source_right);
431}
Abstract base class for password store operations.
Definition pass.h:77
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...
auto filterAcceptsRow(int source_row, const QModelIndex &source_parent) const -> bool override
Filter whether a row should be displayed.
auto data(const QModelIndex &index, int role) const -> QVariant override
Get display data for index.
StoreModel()
Construct a StoreModel.
auto showsFolder(const QModelIndex &index, const QString &path, bool inside, bool outside) const -> bool
showThis() for a folder with rows: shown when any of them is, or, in a search, when its own name matc...
static auto parseDropData(const QMimeData *data) -> std::optional< StoreDragItem >
Decode the drag payload from data.
auto showThis(const QModelIndex &index) const -> bool
Check if a specific index should be shown.
auto mimeTypes() const -> QStringList override
Get supported MIME types for drag/drop.
static auto wordsFilter(const QString &query) -> QRegularExpression
The tree filter for what is typed in the search box.
auto pathOf(const QModelIndex &sourceIndex) const -> QString
The path of a file system model index, as the node keeps it.
Pass * m_pass
Backend that performs drag-and-drop Move/Copy; not owned, null until setPass(), in which case drops a...
Definition storemodel.h:103
void setModelAndStore(QFileSystemModel *sourceModel, const QString &passStore)
Initialize model with source model and store path.
auto dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) -> bool override
Handle dropped MIME data.
void setStore(const QString &passStore)
Update the store path used for filtering without changing the source model.
auto mimeData(const QModelIndexList &indexes) const -> QMimeData *override
Create MIME data from indexes.
auto executeDropAction(const StoreDragItem &info, Qt::DropAction action, const QModelIndex &parent) -> bool
Resolve a validated drop into a Move or Copy.
void setPass(Pass *pass)
Inject the Pass backend for drag-and-drop Move/Copy operations.
auto rootIndexFor(const QString &path) -> QModelIndex
Set the source filesystem root and map it to a proxy index.
QString store
Store root used to make paths relative for filtering and for the drop boundary check.
Definition storemodel.h:98
auto supportedDragActions() const -> Qt::DropActions override
Get supported drag actions.
auto hasChildren(const QModelIndex &parent=QModelIndex()) const -> bool override
No children for a link inside the store: it is listed by name but never entered, so the view shows no...
void fetchMore(const QModelIndex &parent) override
Fetch more rows, except under a link inside the store.
auto isLinkInStore(const QModelIndex &proxyIndex) const -> bool
Whether a proxy index is a link (or junction) inside the store, the store root excluded.
auto flags(const QModelIndex &index) const -> Qt::ItemFlags override
Get item flags for index.
auto performDrop(const QString &cleanedSrc, const QString &cleanedDest, Qt::DropAction action, bool force) -> bool
Perform the actual Move/Copy for a validated drop.
auto canDropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) const -> bool override
Check if drop is possible.
auto lessThan(const QModelIndex &source_left, const QModelIndex &source_right) const -> bool override
Compare two indices for sorting.
auto canFetchMore(const QModelIndex &parent) const -> bool override
Nothing to fetch under a link inside the store, so the file system model never lists what the link po...
QFileSystemModel * fs
The wrapped file system model, set by setModelAndStore(); null until then, which makes showThis() hid...
Definition storemodel.h:93
auto supportedDropActions() const -> Qt::DropActions override
Get supported drop actions.
static auto endsWithGpg() -> const QRegularExpression &
Returns a regex to match .gpg file extensions.
Definition util.cpp:759
static auto isAbsoluteFsPath(const QString &path) -> bool
Whether path is absolute to the file system: as QDir::isAbsolutePath(), except that a name starting w...
Definition util.cpp:106
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:1217
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,...
Definition util.cpp:898
static auto isLinkedFolder(const QString &path) -> bool
Whether path names a symbolic link or NTFS junction, with or without a trailing separator (which woul...
Definition util.cpp:1213
static auto joinPath(const QString &dir, const QString &name) -> QString
name in dir, as the file system means it.
Definition util.cpp:110
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...
auto askYes(QWidget *parent, const QString &title, const QString &text) -> bool
Ask a yes/no question in plain text.
Pass, the abstract password-store backend that RealPass and ImitatePass implement,...
PathValidator: is a path inside the password store, and how is it spelled relative to the store root.
QMessageBox helpers that force Qt::PlainText so store-controlled names can never be read as rich-text...
The "qtpass" logging category.
auto operator>>(QDataStream &in, StoreDragItem &item) -> QDataStream &
Deserialize a StoreDragItem from the QtPass MIME type.
auto operator<<(QDataStream &out, const StoreDragItem &item) -> QDataStream &
Serialize a StoreDragItem for the QtPass MIME type.
StoreModel, the filtering/sorting proxy over the store's QFileSystemModel, and StoreDragItem,...
What a drag from the store tree carries: the kind of the dragged item and its path.
Definition storemodel.h:29
QString path
Definition storemodel.h:40
ItemKind
Type of the dragged item.
Definition storemodel.h:33
ItemKind kind
Definition storemodel.h:39
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...