QtPass 2.0.0
Developer documentation
Loading...
Searching...
No Matches
qtpasssettings.cpp
Go to the documentation of this file.
1// SPDX-FileCopyrightText: 2016 Anne Jan Brouwer
2// SPDX-License-Identifier: GPL-3.0-or-later
9#include "qtpasssettings.h"
10#include "pass.h"
11#include "passbackendfactory.h"
12#include "settingsserializer.h"
13
14#include "util.h"
15
16#include <QCoreApplication>
17#include <QCursor>
18#include <QDebug>
19#include <QDir>
20#include <QFile>
21#include <QFileInfo>
22#include <QGuiApplication>
23#include <QScreen>
24#include <utility>
25
27
29// Portable mode: a qtpass.ini next to the executable wins over the platform
30// settings store.
33 QString portable_ini = QCoreApplication::applicationDirPath() +
34 QDir::separator() + "qtpass.ini";
35 if (QFile(portable_ini).exists()) {
36 m_instance = new QtPassSettings(portable_ini, QSettings::IniFormat);
37 } else {
38 m_instance = new QtPassSettings("IJHack", "QtPass");
39 }
40
41 initialized = true;
42 }
43
44 return m_instance;
45}
46
49 if (!s.passStore.isEmpty()) {
50 s.passStore = QDir::cleanPath(QDir(s.passStore).absolutePath());
51 if (!s.passStore.endsWith('/'))
52 s.passStore += '/';
53 }
54 return s;
55}
56
57auto QtPassSettings::activeProfileFlag(std::optional<bool> Profile::*flag)
58 -> std::optional<bool> {
59 const QString name = getProfile();
60 if (name.isEmpty()) {
61 return std::nullopt;
62 }
63 const Profiles profiles = getProfiles();
64 const auto active = profiles.constFind(name);
65 return active == profiles.constEnd() ? std::nullopt : (*active).*flag;
66}
67
68#ifndef Q_OS_WIN
69#include <sys/stat.h>
70#endif
71
72namespace {
77#if defined(Q_OS_WIN) || defined(Q_OS_MACOS)
78constexpr auto kStoreCase = Qt::CaseInsensitive;
79#else
80constexpr auto kStoreCase = Qt::CaseSensitive;
81#endif
82
89auto comparableFolder(const QString &path) -> QString {
90 const QString real = QFileInfo(path).canonicalFilePath();
91 return real.isEmpty() ? QDir::cleanPath(QDir(path).absolutePath()) : real;
92}
93
102auto sameFolder(const QString &a, const QString &b) -> bool {
103#ifndef Q_OS_WIN
104 struct stat first{};
105 struct stat second{};
106 if (::stat(QFile::encodeName(a).constData(), &first) == 0 &&
107 ::stat(QFile::encodeName(b).constData(), &second) == 0) {
108 return first.st_dev == second.st_dev && first.st_ino == second.st_ino;
109 }
110#endif
111 return comparableFolder(a).compare(comparableFolder(b), kStoreCase) == 0;
112}
113
114} // namespace
115
117 const Profiles &profiles) {
118 if (settings.passStore.isEmpty()) {
119 return;
120 }
121 // Several profiles can share a folder. The active one wins when it is
122 // among them (an OK that changed nothing changes nothing); else one with
123 // a signing key wins over one without, so a typed folder never opens
124 // unsigned while a signed profile claims it; else the first by name.
125 QString exact;
126 for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
127 if (i.key().isEmpty() || i.value().path.isEmpty()) {
128 continue;
129 }
130 if (sameFolder(settings.passStore, i.value().path)) {
131 if (i.key() == settings.activeProfile) {
132 exact = i.key();
133 break;
134 }
135 if (exact.isEmpty() || (profiles.value(exact).signingKey.isEmpty() &&
136 !i.value().signingKey.isEmpty())) {
137 exact = i.key();
138 }
139 }
140 }
141 if (!exact.isEmpty()) {
142 settings.activeProfile = exact;
143 settings.passSigningKey = profiles.value(exact).signingKey;
144 }
145}
146
148 AppSettings s = load();
149 const Profiles profiles = getProfiles();
150 const auto active = profiles.constFind(s.activeProfile);
151 if (!s.activeProfile.isEmpty() && active != profiles.constEnd()) {
152 s.useGit = active->useGit.value_or(s.useGit);
153 s.autoPush = active->autoPush.value_or(s.autoPush);
154 s.autoPull = active->autoPull.value_or(s.autoPull);
155 }
156 return s;
157}
158
159void QtPassSettings::save(const AppSettings &settings) {
161 // The "use pass" mode may have changed; rebuild the backend on next use.
163}
164
168
171 Profiles profiles;
172
173 // migration from version <= v1.3.2: profiles datastructure
174 QStringList childKeys = getInstance()->childKeys();
175 for (const auto &key : std::as_const(childKeys)) {
176 Profile profile;
177 profile.path = getInstance()->value(key).toString();
178 profiles.insert(key, profile);
179 }
180 // /migration from version <= v1.3.2
181
182 QStringList childGroups = getInstance()->childGroups();
183 for (const auto &group : std::as_const(childGroups)) {
184 Profile profile;
185 profile.path = getInstance()->value(group + "/path").toString();
186 profile.signingKey = getInstance()->value(group + "/signingKey").toString();
188 getInstance()->value(group + "/useGit").toString());
190 getInstance()->value(group + "/autoPush").toString());
192 getInstance()->value(group + "/autoPull").toString());
193 profiles.insert(group, profile);
194 }
195
196 getInstance()->endGroup();
197
198 return profiles;
199}
200
202 // "profile" is both the active-profile scalar (getProfile()) and the
203 // profile/<name>/ group; remove() wipes both, which would switch the active
204 // store on every save, so preserve the active name across the rewrite.
205 const QString activeProfile =
206 getInstance()->value(SettingsConstants::profile).toString();
208 if (!activeProfile.isEmpty()) {
209 getInstance()->setValue(SettingsConstants::profile, activeProfile);
210 }
212
213 for (auto i = profiles.cbegin(); i != profiles.cend(); ++i) {
214 getInstance()->setValue(i.key() + "/path", i.value().path);
215 getInstance()->setValue(i.key() + "/signingKey", i.value().signingKey);
216 getInstance()->setValue(i.key() + "/useGit",
217 Profile::flagToString(i.value().useGit));
218 getInstance()->setValue(i.key() + "/autoPush",
219 Profile::flagToString(i.value().autoPush));
220 getInstance()->setValue(i.key() + "/autoPull",
221 Profile::flagToString(i.value().autoPull));
222 }
223
224 getInstance()->endGroup();
225}
226
230
231auto QtPassSettings::getVersion(const QString &defaultValue) -> QString {
232 return getInstance()
233 ->value(SettingsConstants::version, defaultValue)
234 .toString();
235}
236void QtPassSettings::setVersion(const QString &version) {
237 getInstance()->setValue(SettingsConstants::version, version);
238}
239
240auto QtPassSettings::getGeometry(const QByteArray &defaultValue) -> QByteArray {
241 return getInstance()
242 ->value(SettingsConstants::geometry, defaultValue)
243 .toByteArray();
244}
245void QtPassSettings::setGeometry(const QByteArray &geometry) {
246 getInstance()->setValue(SettingsConstants::geometry, geometry);
247}
248
249auto QtPassSettings::getSavestate(const QByteArray &defaultValue)
250 -> QByteArray {
251 return getInstance()
252 ->value(SettingsConstants::savestate, defaultValue)
253 .toByteArray();
254}
255void QtPassSettings::setSavestate(const QByteArray &saveState) {
256 getInstance()->setValue(SettingsConstants::savestate, saveState);
257}
258
259auto QtPassSettings::getDialogGeometry(const QString &key,
260 const QByteArray &defaultValue)
261 -> QByteArray {
262 return getInstance()
263 ->value(SettingsConstants::dialogGeometry + "/" + key, defaultValue)
264 .toByteArray();
265}
266void QtPassSettings::setDialogGeometry(const QString &key,
267 const QByteArray &geometry) {
268 getInstance()->setValue(SettingsConstants::dialogGeometry + "/" + key,
269 geometry);
270}
271
272void QtPassSettings::setUsePass(const bool &usePass) {
273 getInstance()->setValue(SettingsConstants::usePass, usePass);
274 // Backend selection changed: force re-selection on next getPass().
276}
277
278auto QtPassSettings::getAutoclearSeconds(const int &defaultValue) -> int {
279 return getInstance()
280 ->value(SettingsConstants::autoclearSeconds, defaultValue)
281 .toInt();
282}
283// Creates the directory if missing; the result always ends in a separator.
284auto QtPassSettings::getPassStore(const QString &defaultValue) -> QString {
285 QString returnValue = getInstance()
286 ->value(SettingsConstants::passStore, defaultValue)
287 .toString();
288
289 returnValue = QDir(returnValue).absolutePath();
290
291 // ensure directory exists if never used pass or misconfigured.
292 // otherwise process->setWorkingDirectory(passStore); will fail on execution.
293 if (!QDir(returnValue).exists()) {
294 if (!Util::mkpathForStore(returnValue)) {
295 qWarning() << "Failed to create password store directory:" << returnValue;
296 }
297 }
298
299 if (!returnValue.endsWith("/") && !returnValue.endsWith(QDir::separator())) {
300 returnValue += QDir::separator();
301 }
302
303 return returnValue;
304}
305void QtPassSettings::setPassStore(const QString &passStore) {
306 getInstance()->setValue(SettingsConstants::passStore, passStore);
307}
310 if (s.passExecutable.isEmpty())
312 if (s.gitExecutable.isEmpty())
314 if (s.gpgExecutable.isEmpty()) {
316 if (s.gpgExecutable.isEmpty())
318 }
319 if (s.pwgenExecutable.isEmpty())
322}
323auto QtPassSettings::getPassExecutable(const QString &defaultValue) -> QString {
324 return getInstance()
325 ->value(SettingsConstants::passExecutable, defaultValue)
326 .toString();
327}
328
329auto QtPassSettings::getProfile(const QString &defaultValue) -> QString {
330 return getInstance()
331 ->value(SettingsConstants::profile, defaultValue)
332 .toString();
333}
334// With a true default and nothing stored, a store with a .git dir means Git.
335auto QtPassSettings::isUseGit(const bool &defaultValue) -> bool {
336 // The active profile's own flag, else the Git page's.
337 if (const std::optional<bool> own = activeProfileFlag(&Profile::useGit)) {
338 return *own;
339 }
340 bool storedValue =
341 getInstance()->value(SettingsConstants::useGit, defaultValue).toBool();
342 if (storedValue == defaultValue && defaultValue) {
343 QString passStore = getPassStore();
344 if (QFileInfo(passStore).isDir() &&
345 QFileInfo(passStore + QDir::separator() + ".git").isDir()) {
346 return true;
347 }
348 }
349 return storedValue;
350}
351auto QtPassSettings::isUseGrepSearch(const bool &defaultValue) -> bool {
352 return getInstance()
353 ->value(SettingsConstants::useGrepSearch, defaultValue)
354 .toBool();
355}
356
357auto QtPassSettings::isUseOtp(const bool &defaultValue) -> bool {
358 return getInstance()->value(SettingsConstants::useOtp, defaultValue).toBool();
359}
360
361void QtPassSettings::setQrencodeExecutable(const QString &qrencodeExecutable) {
363 qrencodeExecutable);
364}
365
366auto QtPassSettings::isHideOnClose(const bool &defaultValue) -> bool {
367 return getInstance()
368 ->value(SettingsConstants::hideOnClose, defaultValue)
369 .toBool();
370}
371auto QtPassSettings::isAlwaysOnTop(const bool &defaultValue) -> bool {
372 return getInstance()
373 ->value(SettingsConstants::alwaysOnTop, defaultValue)
374 .toBool();
375}
376
377auto QtPassSettings::isAutoPush(const bool &defaultValue) -> bool {
378 if (const std::optional<bool> own = activeProfileFlag(&Profile::autoPush)) {
379 return *own;
380 }
381 return getInstance()
382 ->value(SettingsConstants::autoPush, defaultValue)
383 .toBool();
384}
385
386auto QtPassSettings::isShowProcessOutput(const bool &defaultValue) -> bool {
387 return getInstance()
388 ->value(SettingsConstants::showProcessOutput, defaultValue)
389 .toBool();
390}
397
Implementation that imitates 'pass' when the real tool is unavailable.
Definition imitatepass.h:41
static auto getPass() -> Pass *
Get the active backend, constructing and initialising it on first use after construction or invalidat...
static auto getRealPass() -> RealPass *
Get the lazily-constructed RealPass backend.
static auto isIdle() -> bool
Whether neither backend runs or waits for anything: after a switch of backend the previous one is kep...
static auto getImitatePass() -> ImitatePass *
Get the lazily-constructed ImitatePass backend.
static void invalidate()
Forget the currently active backend.
Abstract base class for password store operations.
Definition pass.h:77
Singleton that stores QtPass settings, handles persistence and defaults.
static bool initialized
Whether getInstance() has chosen the store and built m_instance.
static auto getInstance() -> QtPassSettings *
Get the singleton instance.
static void setPassStore(const QString &passStore)
Save password store path.
static auto getPass() -> Pass *
Get currently active pass backend instance.
static auto getPasswordConfiguration() -> PasswordConfiguration
Get complete password generation configuration.
static auto isUseGit(const bool &defaultValue=QVariant().toBool()) -> bool
Check whether Git integration is enabled.
static auto isUseOtp(const bool &defaultValue=true) -> bool
Check whether OTP support is enabled.
static auto getPassStore(const QString &defaultValue=QVariant().toString()) -> QString
Get password store directory path.
static auto getVersion(const QString &defaultValue=QVariant().toString()) -> QString
Get saved application version.
static void initExecutables()
Initialize executable paths by auto-detecting them.
static auto load() -> AppSettings
Load all flat settings into an AppSettings value object.
static auto isUseGrepSearch(const bool &defaultValue=false) -> bool
Check whether content search is enabled.
QtPassSettings()=delete
Deleted: QtPassSettings is used through its static functions and never instantiated....
static void setVersion(const QString &version)
Save application version.
static auto getProfiles() -> Profiles
Get all configured profiles.
static auto getRealPass() -> RealPass *
Get real pass backend instance.
static void setQrencodeExecutable(const QString &qrencodeExecutable)
Save qrencode executable path.
static auto getProfile(const QString &defaultValue=QVariant().toString()) -> QString
Get active profile name.
static auto isShowProcessOutput(const bool &defaultValue=false) -> bool
Get showProcessOutput setting.
static void setProfiles(const Profiles &profiles)
Save all configured profiles.
static void setUsePass(const bool &usePass)
Save use pass setting.
static auto activeProfileFlag(std::optional< bool > Profile::*flag) -> std::optional< bool >
The active profile's own value of a Git flag.
static void setSavestate(const QByteArray &saveState)
Save window state.
static auto isAlwaysOnTop(const bool &defaultValue=QVariant().toBool()) -> bool
Check whether main window should stay always on top.
static void setDialogGeometry(const QString &key, const QByteArray &geometry)
Save dialog geometry.
static auto getPassExecutable(const QString &defaultValue=QVariant().toString()) -> QString
Get pass executable path.
static auto getDialogGeometry(const QString &key, const QByteArray &defaultValue=QVariant().toByteArray()) -> QByteArray
Get saved dialog geometry.
static void takeProfileOfStore(AppSettings &settings, const Profiles &profiles)
Make settings use the profile whose store it opens.
static auto getImitatePass() -> ImitatePass *
Get imitate pass backend instance.
static auto isHideOnClose(const bool &defaultValue=QVariant().toBool()) -> bool
Check whether closing the window hides the application.
static void save(const AppSettings &settings)
Persist an AppSettings value object to the singleton store.
static QtPassSettings * m_instance
static auto getAutoclearSeconds(const int &defaultValue=QVariant().toInt()) -> int
Get autoclear delay in seconds.
static auto isAutoPush(const bool &defaultValue=QVariant().toBool()) -> bool
Check whether automatic push is enabled.
static void setGeometry(const QByteArray &geometry)
Save window geometry.
static auto getGeometry(const QByteArray &defaultValue=QVariant().toByteArray()) -> QByteArray
Get saved window geometry.
static auto loadEffective() -> AppSettings
load() with the active profile's own Git flags applied: what the backends and the Git actions run wit...
static auto getSavestate(const QByteArray &defaultValue=QVariant().toByteArray()) -> QByteArray
Get saved window state.
static auto backendsIdle() -> bool
Whether no backend, the active one or one kept from before a switch, runs or waits for anything (Pass...
Implementation of Pass that wraps the 'pass' command-line tool.
Definition realpass.h:35
static const QString savestate
Saved dock and toolbar state of the main window (mainwindow/savestate). Bytes from QMainWindow::saveS...
static const QString passExecutable
Path of the pass program. Text.
static const QString useGrepSearch
Offer the search in the content of entries. Boolean, default false.
static const QString dialogGeometry
Prefix of the saved geometry of each dialog: the key is dialog/geometry/<dialog name>....
static const QString geometry
Saved geometry of the main window (mainwindow/geometry). Bytes from QWidget::saveGeometry().
static const QString version
Version of QtPass that last wrote the settings. Text.
static const QString showProcessOutput
Show the Process Output panel. Boolean, default false.
static const QString usePass
Run the pass program (true) or call gpg and Git directly (false). Boolean, default false.
static const QString hideOnClose
With a tray icon: closing the window hides it to the tray and QtPass keeps running....
static const QString alwaysOnTop
Keep the main window above other windows. Boolean, default false.
static const QString useGit
Use Git in the store. Boolean, default false; a profile can set its own value.
static const QString profile
Name of the active profile, and also the group profile/<name>/ that holds each profile (path,...
static const QString useOtp
Show one-time codes for entries that hold an otpauth:// line. Boolean, default true.
static const QString autoclearSeconds
Seconds until the clipboard is cleared. Integer, default 0.
static const QString qrencodeExecutable
Path of the qrencode program. Text.
static const QString passStore
Root folder of the password store. Path as text.
static const QString autoPush
Run git push after each change. Boolean, default false; a profile can set its own value.
static auto loadPasswordConfiguration(QSettings &qs) -> PasswordConfiguration
Read only the password generation settings from a QSettings store.
static void save(QSettings &qs, const AppSettings &settings)
Write all flat settings to a QSettings store.
static auto load(QSettings &qs) -> AppSettings
Read all flat settings from a QSettings store.
static auto mkpathForStore(const QString &path) -> bool
Create path and any missing parents as pass would.
Definition util.cpp:615
static auto findBinaryInPath(const QString &binary) -> QString
Locate an executable by searching the process PATH and (on Windows) falling back to WSL.
Definition util.cpp:651
Pass, the abstract password-store backend that RealPass and ImitatePass implement,...
PassBackendFactory, which constructs the two Pass backends on demand and hands out the one the settin...
QMap< QString, Profile > Profiles
All profiles by name. QMap so iteration order is the name order.
Definition profile.h:81
QtPassSettings, the QSettings singleton behind every saved setting, the profiles and the Pass backend...
SettingsSerializer: the flat AppSettings fields to and from their QSettings keys, without side effect...
Plain value-object holding all flat QtPass configuration.
Definition appsettings.h:36
QString gpgExecutable
Path to the gpg/gpg2 executable.
Definition appsettings.h:66
QString passSigningKey
GPG key used to sign .gpg-id files.
Definition appsettings.h:61
QString pwgenExecutable
Path to the pwgen executable.
Definition appsettings.h:67
QString passStore
Password-store root path.
Definition appsettings.h:60
QString gitExecutable
Path to the git executable.
Definition appsettings.h:65
bool autoPull
git pull before an entry is edited and before a re-encryption.
QString passExecutable
Path to the pass executable.
Definition appsettings.h:64
bool useGit
Enable git integration.
QString activeProfile
Name of the active profile.
Definition appsettings.h:56
Holds the password generator settings: which character set is selected, the alphabet of every set,...
One named password store: where it is, how its .gpg-id is signed and, optionally, its own Git switche...
Definition profile.h:26
std::optional< bool > autoPush
Push after commits; unset = global.
Definition profile.h:30
QString path
Password store directory.
Definition profile.h:27
std::optional< bool > autoPull
Pull on start; unset = global.
Definition profile.h:31
std::optional< bool > useGit
Git on/off; unset follows the global.
Definition profile.h:29
static auto flagToString(std::optional< bool > flag) -> QString
Format a flag the way it is stored.
Definition profile.h:53
static auto flagFromString(const QString &value) -> std::optional< bool >
Parse the on-disk tri-state.
Definition profile.h:38
QString signingKey
Key(s) that sign this store's .gpg-id.
Definition profile.h:28
Util: static helpers for the process environment, binary discovery, store paths, URL safety and the l...