• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

IJHack / QtPass / 43728208630

15 Nov 2026 03:08PM UTC coverage: 96.275% (-0.03%) from 96.303%
43728208630

push

github

web-flow
OTP field on the first line: only when it holds a seed (#2191)

#2190 made an entry's first line a TOTP secret whenever it read as an
OTP:/TOTP: field (isOtpLine(), the rule for body lines). Review found the
false positive: a real password that only starts like one, such as
"totp:Secr3t!", was then hidden, refused by Ctrl+C and "Always copy", and
its tail fed to the code generator. The first line is the password in the
pass format, so it needs a stricter test.

FileContent::isOtpPasswordLine() decides for the first line: a bare
otpauth:// line, a field whose value is an otpauth URI, or an OTP:/TOTP:
field whose value is written as a base32 seed: base32 letters and the
digits 2 to 7 only (either case; white space, dashes and "=" between or
after the groups), at least 16 of them, that Totp::isValid() takes.
Totp::parse() alone is too lenient for this (it drops punctuation and
reads 0, 1 and 8 as letters). parse(), getPasswordForDisplay(), the
panel's defence in depth and the Ctrl+C handler use it; body lines keep
isOtpLine(). A long password of letters and the digits 2 to 7 still reads
as a seed; the docs say so.

A second review caught that a first draft skipped only spaces, so a seed
grouped with dashes, a tab or a no-break space was shown and copied again;
those separators are skipped now.

Tests otpFieldOnTheFirstLineIsNotThePassword (seed forms incl. grouped,
dashed, tab, NBSP; controls totp:Secr3t!, OTP: hunter2!, a short
ABCDEFGH, a seed with 0), passwordFromFileToClipboardSkipsOtpSecret and
otpUriAsPasswordIsNeverRendered (the controls are copied and shown as
the password). Dropping the seed test, its character check, its length
check, the separator handling, or putting any of the four places back on
isOtpLine() fails a test. Follow-up FU-2190 from the #2190 review.

Signed-off-by: Anne Jan Brouwer <brouwer@annejan.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

19 of 19 new or added lines in 3 files covered. (100.0%)

3 existing lines in 1 file now uncovered.

8607 of 8940 relevant lines covered (96.28%)

596.56 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

93.22
/src/nativegrep.cpp
1
// SPDX-FileCopyrightText: 2026 Anne Jan Brouwer
2
// SPDX-License-Identifier: GPL-3.0-or-later
3
/**
4
 * @file
5
 * @brief Implements NativeGrep: the store walk, the per-file gpg runs and the
6
 * hand-over of results from the worker thread.
7
 */
8
#include "nativegrep.h"
9
#include "executor.h"
10
#include "pass.h"
11
#include "util.h"
12
#include <QDir>
13
#include <QElapsedTimer>
14
#include <QPointer>
15
#include <QProcess>
16
#include <QRegularExpression>
17
#include <QStringTokenizer>
18
#include <QThread>
19
#include <utility>
20

21
NativeGrep::NativeGrep(QObject *parent) : QObject(parent) {}
227 ✔
22

23
NativeGrep::~NativeGrep() {
227 ✔
24
  static constexpr int kThreadTimeoutMs = 5000;
25
  cancel();
227 ✔
26
  QElapsedTimer elapsed;
227 ✔
27
  elapsed.start();
227 ✔
28
  for (const Worker &w : std::as_const(m_workers)) {
228 ✔
29
    if (w.thread && w.thread->isRunning()) {
1 ✔
30
      const int remaining =
UNCOV
31
          kThreadTimeoutMs - static_cast<int>(elapsed.elapsed());
×
UNCOV
32
      if (remaining > 0)
×
UNCOV
33
        w.thread->wait(remaining);
×
34
    }
35
  }
36
}
227 ✔
37

38
/**
39
 * @brief Decrypt one .gpg file and return lines matching rx.
40
 */
41
auto NativeGrep::matchFile(const QProcessEnvironment &env,
421 ✔
42
                           const QString &gpgExe, const QString &filePath,
43
                           const QRegularExpression &rx,
44
                           const std::atomic_bool *cancel) -> QStringList {
45
  const QString translatedPath =
46
      Executor::translatePathForWsl(filePath, gpgExe);
421 ✔
47
  QString plaintext;
421 ✔
48
  // The QProcess overload is the one that takes the cancel flag; it polls
49
  // the flag while waiting and terminates (then kills) gpg from this thread,
50
  // the one that owns the process.
51
  QProcess gpg;
421 ✔
52
  gpg.setProcessEnvironment(env);
421 ✔
53
  const int rc = Executor::executeBlocking(
421 ✔
54
      gpg, gpgExe,
55
      QStringList{"-d", "--quiet", "--yes", "--no-encrypt-to", "--batch",
421 ✔
56
                  "--use-agent"} +
5,894 ✔
57
          Pass::maxOutputArgs() + QStringList{translatedPath},
2,105 ✔
58
      QString(), &plaintext, nullptr, cancel);
421 ✔
59
  if (rc != 0 || plaintext.isEmpty())
421 ✔
60
    return {};
41 ✔
61
  // Line by line over the text, never a list of every line (a compressed
62
  // entry can expand into tens of millions), and a bounded number taken.
63
  QStringList matches;
380 ✔
64
  for (QStringView line : QStringView(plaintext).tokenize(u'\n')) {
60,899 ✔
65
    if (line.endsWith(u'\r'))
66
      line.chop(1);
67
    const QStringView t = line.trimmed();
68
    if (t.isEmpty())
60,620 ✔
69
      continue;
60,516 ✔
70
    const QRegularExpressionMatch m = rx.matchView(line);
30,253 ✔
71
    if (!m.hasMatch())
30,253 ✔
72
      continue;
6 ✔
73
    if (matches.size() == kMaxMatchesPerEntry) {
30,247 ✔
74
      matches << QString(); // isMoreMarker(): not a match, not counted
101 ✔
75
      break;
76
    }
77
    if (t.size() <= kMaxPreviewLength) {
30,146 ✔
78
      matches << t.toString();
30,143 ✔
79
      continue;
30,143 ✔
80
    }
81
    // A window of the line that holds the match, a little context before
82
    // it; "…" marks what was left out on either side.
83
    const qsizetype at =
84
        qMax<qsizetype>(0, m.capturedStart() - (t.data() - line.data()));
3 ✔
85
    qsizetype start = qBound<qsizetype>(0, at - kMaxPreviewLength / 4,
3 ✔
86
                                        t.size() - kMaxPreviewLength);
3 ✔
87
    qsizetype end = start + kMaxPreviewLength;
3 ✔
88
    // Never half a surrogate pair (an emoji, CJK Extension B) at either
89
    // edge: the window takes the whole character.
90
    if (start > 0 && t[start].isLowSurrogate())
3 ✔
91
      --start;
1 ✔
92
    if (end < t.size() && t[end - 1].isHighSurrogate())
3 ✔
93
      ++end;
1 ✔
94
    QString preview = t.sliced(start, end - start).toString();
3 ✔
95
    if (start > 0)
3 ✔
96
      preview.prepend(QChar(0x2026));
2 ✔
97
    if (end < t.size())
3 ✔
98
      preview.append(QChar(0x2026));
3 ✔
99
    matches << preview;
100
  }
30,253 ✔
101
  return matches;
102
}
421 ✔
103

104
/**
105
 * @brief Walk the store, decrypt every .gpg file, collect matches.
106
 */
107
auto NativeGrep::scanStore(const QProcessEnvironment &env,
18 ✔
108
                           const QString &gpgExe, const QString &storeDir,
109
                           const QRegularExpression &rx,
110
                           const std::atomic_bool *cancel)
111
    -> QList<QPair<QString, QStringList>> {
112
  QList<QPair<QString, QStringList>> results;
18 ✔
113
  int total = 0; // matching lines, the markers not counted
114
  // Regular files only: a link or junction is not an entry, and searching
115
  // through one would decrypt files outside the store.
116
  const QStringList files =
117
      Util::regularFilesUnder(storeDir, QStringList() << "*.gpg");
54 ✔
118
  for (const QString &filePath : files) {
434 ✔
119
    if (QThread::currentThread()->isInterruptionRequested() ||
424 ✔
120
        (cancel != nullptr && cancel->load()))
73 ✔
121
      return {};
6 ✔
122
    if (total == kMaxMatches) {
418 ✔
123
      // The budget is spent and entries remain: the search stopped here.
124
      results.append({QString(), {}});
4 ✔
125
      break;
2 ✔
126
    }
127
    QStringList matches = matchFile(env, gpgExe, filePath, rx, cancel);
416 ✔
128
    if (matches.isEmpty())
416 ✔
129
      continue;
130
    const bool more = isMoreMarker(matches.constLast());
131
    if (more)
376 ✔
132
      matches.removeLast();
100 ✔
133
    // The store-wide budget: what still fits, and a marker when that cut
134
    // the entry short.
135
    const int room = kMaxMatches - total;
376 ✔
136
    if (matches.size() > room) {
376 ✔
137
      matches = matches.mid(0, room);
1 ✔
138
      matches << QString();
2 ✔
139
    } else if (more) {
375 ✔
140
      matches << QString();
200 ✔
141
    }
142
    total += static_cast<int>(matches.size()) -
376 ✔
143
             (isMoreMarker(matches.constLast()) ? 1 : 0);
376 ✔
144
    QString entry = QDir(storeDir).relativeFilePath(filePath);
376 ✔
145
    if (entry.endsWith(QLatin1String(".gpg")))
376 ✔
146
      entry.chop(4);
376 ✔
147
    results.append({entry, matches});
376 ✔
148
  }
149
  return results;
150
}
151

152
/**
153
 * @brief Start a search on a worker thread.
154
 *
155
 * Results are emitted on the owner's thread via QMetaObject::invokeMethod. A
156
 * sequence counter discards results from superseded searches; the previous
157
 * search is asked to stop but not waited for, since blocking the UI thread
158
 * while gpg decrypts would freeze the interface.
159
 */
160
void NativeGrep::search(const QString &pattern, bool caseInsensitive,
15 ✔
161
                        const QString &gpgExe, const QString &storeDir,
162
                        const QProcessEnvironment &env) {
163
  cancel();
15 ✔
164

165
  // Advance the sequence before any early return so in-flight workers from the
166
  // previous query fail the seq check and cannot publish stale results.
167
  const int seq = ++m_seq;
15 ✔
168

169
  // Use trimmed() rather than isEmpty(): a whitespace-only string is a valid
170
  // regex that matches every non-empty line, which is almost never intentional
171
  // and would decrypt the entire store.
172
  //
173
  // Both early returns post finished() via Qt::QueuedConnection so that the
174
  // signal is always delivered asynchronously after search() returns, matching
175
  // the contract of the threaded path.
176
  if (pattern.trimmed().isEmpty()) {
15 ✔
177
    QMetaObject::invokeMethod(
×
178
        this,
179
        [this, seq]() {
×
180
          if (m_seq == seq)
×
181
            emit finished({});
×
182
        },
×
183
        Qt::QueuedConnection);
184
    return;
1 ✔
185
  }
186

187
  const QRegularExpression rx(
188
      pattern, caseInsensitive ? QRegularExpression::CaseInsensitiveOption
189
                               : QRegularExpression::PatternOptions{});
15 ✔
190
  if (!rx.isValid()) {
15 ✔
191
    QMetaObject::invokeMethod(
1 ✔
192
        this,
193
        [this, seq]() {
1 ✔
194
          if (m_seq == seq)
1 ✔
195
            emit finished({});
2 ✔
196
        },
1 ✔
197
        Qt::QueuedConnection);
198
    return;
199
  }
200
  QPointer<NativeGrep> self(this);
201

202
  auto emitResults = [self, seq](QList<QPair<QString, QStringList>> results) {
28 ✔
203
    if (!self)
14 ✔
204
      return;
205
    QMetaObject::invokeMethod(
14 ✔
206
        self,
207
        [self, seq, results = std::move(results)]() {
42 ✔
208
          if (self && self->m_seq == seq)
28 ✔
209
            emit self->finished(results);
14 ✔
210
        },
14 ✔
211
        Qt::QueuedConnection);
212
  };
14 ✔
213

214
  auto cancelFlag = std::make_shared<std::atomic_bool>(false);
14 ✔
215
  QThread *thread = QThread::create([gpgExe, storeDir, env, rx, cancelFlag,
28 ✔
216
                                     emitResults = std::move(emitResults)]() {
217
    std::move(emitResults)(
14 ✔
218
        scanStore(env, gpgExe, storeDir, rx, cancelFlag.get()));
14 ✔
219
  });
14 ✔
220

221
  m_workers.append({thread, cancelFlag});
28 ✔
222
  connect(thread, &QThread::finished, thread, &QObject::deleteLater);
14 ✔
223
  connect(thread, &QThread::finished, this, [this, thread]() {
14 ✔
224
    m_workers.removeIf(
13 ✔
225
        [thread](const Worker &w) { return w.thread == thread; });
13 ✔
226
  });
227
  thread->start();
14 ✔
228
}
29 ✔
229

230
void NativeGrep::cancel() {
499 ✔
231
  for (const Worker &w : std::as_const(m_workers)) {
507 ✔
232
    w.cancel->store(true);
233
    if (w.thread && w.thread->isRunning())
8 ✔
234
      w.thread->requestInterruption();
7 ✔
235
  }
236
}
499 ✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE TRIAL · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc