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

IJHack / QtPass / 45510373638

24 Nov 2026 11:29PM UTC coverage: 94.819%. Remained the same
45510373638

push

github

web-flow
Import key: show only text laid out like armor (#2328)

"From file..." bounded the key file to 16 MiB and checked the armor
header, then loaded it whole into the input field on the GUI thread.
One long line without break opportunity takes Qt time growing with the
square of its length to wrap (577 s for 2 MiB), and each line costs the
editor some 440 bytes (2 MiB of line breaks: 926 MB). "From clipboard"
loaded clipboard text the same way.

ImportKeyDialog::fitsTheEditor() refuses text with a line longer than
1024 characters or more lines than a 16 MiB file in armor's
64-character lines holds. A line ends wherever the editor starts a new
one: LF, CR (CRLF once), U+2028, U+2029, U+FDD0 and U+FDD1. Both
buttons check it before setPlainText() and say which limit was broken.

Scan: ANT-2026-8KAWLSYI

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

20 of 20 new or added lines in 1 file covered. (100.0%)

1 existing line in 1 file now uncovered.

9919 of 10461 relevant lines covered (94.82%)

22057.17 hits per line

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

93.38
/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 "filecontent.h"
11
#include "pass.h"
12
#include "util.h"
13
#include <QDir>
14
#include <QElapsedTimer>
15
#include <QPointer>
16
#include <QProcess>
17
#include <QRegularExpression>
18
#include <QStringTokenizer>
19
#include <QThread>
20
#include <algorithm>
21
#include <utility>
22

23
NativeGrep::NativeGrep(QObject *parent) : QObject(parent) {}
265 ✔
24

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

40
/**
41
 * @brief Decrypt one .gpg file and return lines matching rx.
42
 */
43
auto NativeGrep::matchFile(const QProcessEnvironment &env,
431 ✔
44
                           const QString &gpgExe, const QString &filePath,
45
                           const QRegularExpression &rx,
46
                           const std::atomic_bool *cancel) -> QStringList {
47
  const QString translatedPath =
48
      Executor::translatePathForWsl(filePath, gpgExe);
431 ✔
49
  QString plaintext;
431 ✔
50
  // The QProcess overload is the one that takes the cancel flag; it polls
51
  // the flag while waiting and terminates (then kills) gpg from this thread,
52
  // the one that owns the process.
53
  QProcess gpg;
431 ✔
54
  gpg.setProcessEnvironment(env);
431 ✔
55
  const int rc = Executor::executeBlocking(
431 ✔
56
      gpg, gpgExe,
57
      QStringList{"-d", "--quiet", "--yes", "--no-encrypt-to", "--batch",
431 ✔
58
                  "--use-agent"} +
6,034 ✔
59
          Pass::maxOutputArgs() + QStringList{translatedPath},
2,155 ✔
60
      QString(), &plaintext, nullptr, cancel);
431 ✔
61
  if (rc != 0 || plaintext.isEmpty())
431 ✔
62
    return {};
46 ✔
63
  // Line by line over the text, never a list of every line (a compressed
64
  // entry can expand into tens of millions), and a bounded number taken.
65
  QStringList matches;
385 ✔
66
  bool first = true;
67
  for (QStringView line : QStringView(plaintext).tokenize(u'\n')) {
60,921 ✔
68
    // The password is the first line, empty or not.
69
    const bool password = std::exchange(first, false);
70
    if (line.endsWith(u'\r'))
71
      line.chop(1);
72
    const QStringView t = line.trimmed();
60,637 ✔
73
    if (t.isEmpty())
60,637 ✔
74
      continue;
60,531 ✔
75
    const QRegularExpressionMatch m = rx.matchView(line);
30,267 ✔
76
    if (!m.hasMatch())
30,267 ✔
77
      continue;
9 ✔
78
    if (matches.size() == kMaxMatchesPerEntry) {
30,258 ✔
79
      matches << QString(); // isMoreMarker(): not a match, not counted
101 ✔
80
      break;
81
    }
82
    // A shared secret is never shown, as in the display panel: only that
83
    // there was a match (isOtpMarker()).
84
    const QString whole = t.toString();
85
    if (password ? FileContent::isOtpPasswordLine(whole)
59,938 ✔
86
                 : FileContent::isOtpLine(whole)) {
29,781 ✔
87
      matches << QStringLiteral("\n");
3 ✔
88
      continue;
3 ✔
89
    }
90
    // Marked, so the window shows it only where the panel would
91
    // (isPasswordMatch()).
92
    const QString mark = password ? QStringLiteral("\n") : QString();
30,154 ✔
93
    if (t.size() <= kMaxPreviewLength) {
30,154 ✔
94
      matches << mark + whole;
30,148 ✔
95
      continue;
30,148 ✔
96
    }
97
    // A window of the line that holds the match, a little context before
98
    // it; "…" marks what was left out on either side.
99
    const qsizetype at =
100
        qMax<qsizetype>(0, m.capturedStart() - (t.data() - line.data()));
6 ✔
101
    qsizetype start = qBound<qsizetype>(0, at - kMaxPreviewLength / 4,
6 ✔
102
                                        t.size() - kMaxPreviewLength);
6 ✔
103
    qsizetype end = start + kMaxPreviewLength;
6 ✔
104
    // Never half a surrogate pair (an emoji, CJK Extension B) at either
105
    // edge: the window takes the whole character.
106
    if (start > 0 && t[start].isLowSurrogate())
6 ✔
107
      --start;
1 ✔
108
    if (end < t.size() && t[end - 1].isHighSurrogate())
6 ✔
109
      ++end;
1 ✔
110
    // A field's name decides whether its value is hidden, so a window that
111
    // cuts into a `name: value` line keeps the whole name in front. A name
112
    // too long for that is shown cut, and then none of the value is.
113
    const qsizetype colon = password ? -1 : t.indexOf(u':');
6 ✔
114
    QString preview;
6 ✔
115
    qsizetype from = start;
6 ✔
116
    if (colon > 0 && start > 0) {
6 ✔
117
      if (colon >= kMaxPreviewLength / 2) {
3 ✔
118
        matches << t.first(kMaxPreviewLength / 2).toString() + QChar(0x2026) +
3 ✔
119
                       QStringLiteral(": ") + QChar(0x2026);
3 ✔
120
        continue;
121
      }
122
      from = std::max(start, colon + 1);
2 ✔
123
      preview = t.first(colon + 1).toString() + u' ';
4 ✔
124
      if (from > colon + 1)
2 ✔
125
        preview += QChar(0x2026);
1 ✔
126
    } else if (start > 0) {
3 ✔
127
      preview = QChar(0x2026);
2 ✔
128
    }
129
    preview += t.sliced(from, end - from).toString();
5 ✔
130
    if (end < t.size())
5 ✔
131
      preview.append(QChar(0x2026));
4 ✔
132
    matches << mark + preview;
10 ✔
133
  }
30,267 ✔
134
  return matches;
135
}
431 ✔
136

137
/**
138
 * @brief Walk the store, decrypt every .gpg file, collect matches.
139
 */
140
auto NativeGrep::scanStore(const QProcessEnvironment &env,
19 ✔
141
                           const QString &gpgExe, const QString &storeDir,
142
                           const QRegularExpression &rx,
143
                           const std::atomic_bool *cancel)
144
    -> QList<QPair<QString, QStringList>> {
145
  QList<QPair<QString, QStringList>> results;
19 ✔
146
  int total = 0; // matching lines, the markers not counted
147
  // Regular files only: a link or junction is not an entry, and searching
148
  // through one would decrypt files outside the store.
149
  const QStringList files =
150
      Util::regularFilesUnder(storeDir, QStringList() << "*.gpg");
57 ✔
151
  for (const QString &filePath : files) {
443 ✔
152
    if (QThread::currentThread()->isInterruptionRequested() ||
433 ✔
153
        (cancel != nullptr && cancel->load()))
81 ✔
154
      return {};
7 ✔
155
    if (total == kMaxMatches) {
426 ✔
156
      // The budget is spent and entries remain: the search stopped here.
157
      results.append({QString(), {}});
4 ✔
158
      break;
2 ✔
159
    }
160
    QStringList matches = matchFile(env, gpgExe, filePath, rx, cancel);
424 ✔
161
    if (matches.isEmpty())
424 ✔
162
      continue;
163
    const bool more = isMoreMarker(matches.constLast());
164
    if (more)
379 ✔
165
      matches.removeLast();
100 ✔
166
    // The store-wide budget: what still fits, and a marker when that cut
167
    // the entry short.
168
    const int room = kMaxMatches - total;
379 ✔
169
    if (matches.size() > room) {
379 ✔
170
      matches = matches.mid(0, room);
1 ✔
171
      matches << QString();
2 ✔
172
    } else if (more) {
378 ✔
173
      matches << QString();
200 ✔
174
    }
175
    total += static_cast<int>(matches.size()) -
379 ✔
176
             (isMoreMarker(matches.constLast()) ? 1 : 0);
379 ✔
177
    QString entry = QDir(storeDir).relativeFilePath(filePath);
379 ✔
178
    if (entry.endsWith(QLatin1String(".gpg")))
379 ✔
179
      entry.chop(4);
379 ✔
180
    results.append({entry, matches});
379 ✔
181
  }
182
  return results;
183
}
184

185
/**
186
 * @brief Start a search on a worker thread.
187
 *
188
 * Results are emitted on the owner's thread via QMetaObject::invokeMethod. A
189
 * sequence counter discards results from superseded searches; the previous
190
 * search is asked to stop but not waited for, since blocking the UI thread
191
 * while gpg decrypts would freeze the interface.
192
 */
193
void NativeGrep::search(const QString &pattern, bool caseInsensitive,
16 ✔
194
                        const QString &gpgExe, const QString &storeDir,
195
                        const QProcessEnvironment &env) {
196
  cancel();
16 ✔
197

198
  // Advance the sequence before any early return so in-flight workers from the
199
  // previous query fail the seq check and cannot publish stale results.
200
  const int seq = ++m_seq;
16 ✔
201

202
  // Use trimmed() rather than isEmpty(): a whitespace-only string is a valid
203
  // regex that matches every non-empty line, which is almost never intentional
204
  // and would decrypt the entire store.
205
  //
206
  // Both early returns post finished() via Qt::QueuedConnection so that the
207
  // signal is always delivered asynchronously after search() returns, matching
208
  // the contract of the threaded path.
209
  if (pattern.trimmed().isEmpty()) {
16 ✔
210
    QMetaObject::invokeMethod(
×
211
        this,
212
        [this, seq]() {
×
213
          if (m_seq == seq)
×
214
            emit finished({});
×
215
        },
×
216
        Qt::QueuedConnection);
217
    return;
1 ✔
218
  }
219

220
  const QRegularExpression rx(
221
      pattern, caseInsensitive ? QRegularExpression::CaseInsensitiveOption
222
                               : QRegularExpression::PatternOptions{});
16 ✔
223
  if (!rx.isValid()) {
16 ✔
224
    QMetaObject::invokeMethod(
1 ✔
225
        this,
226
        [this, seq]() {
1 ✔
227
          if (m_seq == seq)
1 ✔
228
            emit finished({});
2 ✔
229
        },
1 ✔
230
        Qt::QueuedConnection);
231
    return;
232
  }
233
  QPointer<NativeGrep> self(this);
234

235
  auto emitResults = [self, seq](QList<QPair<QString, QStringList>> results) {
30 ✔
236
    if (!self)
15 ✔
237
      return;
238
    QMetaObject::invokeMethod(
15 ✔
239
        self,
240
        [self, seq, results = std::move(results)]() {
45 ✔
241
          if (self && self->m_seq == seq)
30 ✔
242
            emit self->finished(results);
15 ✔
243
        },
15 ✔
244
        Qt::QueuedConnection);
245
  };
15 ✔
246

247
  auto cancelFlag = std::make_shared<std::atomic_bool>(false);
15 ✔
248
  QThread *thread = QThread::create([gpgExe, storeDir, env, rx, cancelFlag,
30 ✔
249
                                     emitResults = std::move(emitResults)]() {
250
    std::move(emitResults)(
15 ✔
251
        scanStore(env, gpgExe, storeDir, rx, cancelFlag.get()));
15 ✔
252
  });
15 ✔
253

254
  m_workers.append({thread, cancelFlag});
30 ✔
255
  connect(thread, &QThread::finished, thread, &QObject::deleteLater);
15 ✔
256
  connect(thread, &QThread::finished, this, [this, thread]() {
15 ✔
257
    m_workers.removeIf(
15 ✔
258
        [thread](const Worker &w) { return w.thread == thread; });
15 ✔
259
  });
260
  thread->start();
15 ✔
261
}
31 ✔
262

263
void NativeGrep::cancel() {
602 ✔
264
  for (const Worker &w : std::as_const(m_workers)) {
610 ✔
265
    w.cancel->store(true);
266
    if (w.thread && w.thread->isRunning())
8 ✔
267
      w.thread->requestInterruption();
8 ✔
268
  }
269
}
602 ✔
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