mdbkit 0.8.1__tar.gz → 0.8.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- {mdbkit-0.8.1 → mdbkit-0.8.2}/PKG-INFO +17 -5
- {mdbkit-0.8.1 → mdbkit-0.8.2}/README.md +16 -4
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/__init__.py +1 -1
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/advisor.py +4 -2
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/cli.py +15 -13
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/indexusage.py +5 -3
- mdbkit-0.8.2/mdbkit/quoting.py +86 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/rebuild.py +59 -36
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/render.py +20 -13
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/triage.py +4 -2
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit.egg-info/PKG-INFO +17 -5
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit.egg-info/SOURCES.txt +2 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/pyproject.toml +1 -1
- mdbkit-0.8.2/tests/test_printed_commands.py +246 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/LICENSE +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/analysis.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/audit.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/compare.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/demo.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/explain.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/filtering.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/ftdc.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/host.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/lab.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/oslog.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/parser.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/report.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/scripts.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/serverstatus.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/sharding.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit/shelljson.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit.egg-info/dependency_links.txt +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit.egg-info/entry_points.txt +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit.egg-info/requires.txt +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/mdbkit.egg-info/top_level.txt +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/setup.cfg +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_demo_lab.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_explain.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_ftdc.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_host.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_indexes.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_mdbkit.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_oslog_serverstatus.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_query_hash.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_real_failures.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_real_servers.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_rebuild_report.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_render_e2e.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_sharded.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_triage.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_v060_hardening.py +0 -0
- {mdbkit-0.8.1 → mdbkit-0.8.2}/tests/test_v080.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: mdbkit
|
|
3
|
-
Version: 0.8.
|
|
3
|
+
Version: 0.8.2
|
|
4
4
|
Summary: Offline toolkit for MongoDB 4.4 to 9.0 logs and diagnostics: slow-query shapes, index advice and index usage, incident triage, sharded clusters, multi-instance hosts, startup configuration audit, FTDC decoding. A spiritual successor to mtools' log tools.
|
|
5
5
|
Author: Saqib Ameen Subhan
|
|
6
6
|
License: MIT
|
|
@@ -1595,6 +1595,15 @@ Linux box the database actually runs on.
|
|
|
1595
1595
|
are still read, and misread log lines are still the most useful thing to
|
|
1596
1596
|
send.
|
|
1597
1597
|
|
|
1598
|
+
**v0.8.2 is a security fix: upgrade.** The commands mdbkit prints for you
|
|
1599
|
+
to paste (`--as-explain`, the plan cache lookup, `hideIndex`, the `--ns`
|
|
1600
|
+
hints) put names from the log or export in as they were. A crafted
|
|
1601
|
+
collection name, or a regex built from an application user's search text,
|
|
1602
|
+
could turn the printed line into one that runs something else when pasted.
|
|
1603
|
+
Every such value is now quoted. It also fixes `--explain-script` for updates
|
|
1604
|
+
and deletes, which wrote a script mongosh could not run. Details:
|
|
1605
|
+
[SECURITY.md](SECURITY.md#security-fixes).
|
|
1606
|
+
|
|
1598
1607
|
**Shipped in v0.8.1:** the `queryHash` of each shape in the `queries`
|
|
1599
1608
|
table, `queries --shape <hash>` and `filter --query-hash`, to go from a
|
|
1600
1609
|
shape back to its full log lines
|
|
@@ -1643,10 +1652,13 @@ the most valuable bug reports of all (redact literals first!).
|
|
|
1643
1652
|
|
|
1644
1653
|
## Security
|
|
1645
1654
|
|
|
1646
|
-
mdbkit is offline by design:
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1655
|
+
mdbkit is offline by design: no analysis command contains network code
|
|
1656
|
+
(`lab` is the documented exception), nothing it reads is ever executed or
|
|
1657
|
+
evaluated, and every log line is treated as untrusted data (strict JSON
|
|
1658
|
+
parsing only — shell constructors are never evaluated). Commands it prints
|
|
1659
|
+
for you to paste quote every name taken from a log or export, so a crafted
|
|
1660
|
+
name cannot become code (fixed in 0.8.2). See [SECURITY.md](SECURITY.md)
|
|
1661
|
+
for what every release is checked for and the reporting process.
|
|
1650
1662
|
|
|
1651
1663
|
## Non-affiliation
|
|
1652
1664
|
|
|
@@ -1559,6 +1559,15 @@ Linux box the database actually runs on.
|
|
|
1559
1559
|
are still read, and misread log lines are still the most useful thing to
|
|
1560
1560
|
send.
|
|
1561
1561
|
|
|
1562
|
+
**v0.8.2 is a security fix: upgrade.** The commands mdbkit prints for you
|
|
1563
|
+
to paste (`--as-explain`, the plan cache lookup, `hideIndex`, the `--ns`
|
|
1564
|
+
hints) put names from the log or export in as they were. A crafted
|
|
1565
|
+
collection name, or a regex built from an application user's search text,
|
|
1566
|
+
could turn the printed line into one that runs something else when pasted.
|
|
1567
|
+
Every such value is now quoted. It also fixes `--explain-script` for updates
|
|
1568
|
+
and deletes, which wrote a script mongosh could not run. Details:
|
|
1569
|
+
[SECURITY.md](SECURITY.md#security-fixes).
|
|
1570
|
+
|
|
1562
1571
|
**Shipped in v0.8.1:** the `queryHash` of each shape in the `queries`
|
|
1563
1572
|
table, `queries --shape <hash>` and `filter --query-hash`, to go from a
|
|
1564
1573
|
shape back to its full log lines
|
|
@@ -1607,10 +1616,13 @@ the most valuable bug reports of all (redact literals first!).
|
|
|
1607
1616
|
|
|
1608
1617
|
## Security
|
|
1609
1618
|
|
|
1610
|
-
mdbkit is offline by design:
|
|
1611
|
-
|
|
1612
|
-
|
|
1613
|
-
|
|
1619
|
+
mdbkit is offline by design: no analysis command contains network code
|
|
1620
|
+
(`lab` is the documented exception), nothing it reads is ever executed or
|
|
1621
|
+
evaluated, and every log line is treated as untrusted data (strict JSON
|
|
1622
|
+
parsing only — shell constructors are never evaluated). Commands it prints
|
|
1623
|
+
for you to paste quote every name taken from a log or export, so a crafted
|
|
1624
|
+
name cannot become code (fixed in 0.8.2). See [SECURITY.md](SECURITY.md)
|
|
1625
|
+
for what every release is checked for and the reporting process.
|
|
1614
1626
|
|
|
1615
1627
|
## Non-affiliation
|
|
1616
1628
|
|
|
@@ -25,6 +25,7 @@ from .analysis import (
|
|
|
25
25
|
RANGE_OPS,
|
|
26
26
|
ShapeStats,
|
|
27
27
|
)
|
|
28
|
+
from .quoting import js_key, js_str, sh_arg
|
|
28
29
|
|
|
29
30
|
Confidence = str # "high" | "medium" | "low"
|
|
30
31
|
|
|
@@ -46,7 +47,8 @@ class Recommendation:
|
|
|
46
47
|
)
|
|
47
48
|
|
|
48
49
|
def candidate_str(self) -> str:
|
|
49
|
-
return "{ " + ", ".join(
|
|
50
|
+
return "{ " + ", ".join("%s: %s" % (js_key(f), d if isinstance(d, int) else js_str(d))
|
|
51
|
+
for f, d in self.candidate) + " }"
|
|
50
52
|
|
|
51
53
|
def to_dict(self) -> dict:
|
|
52
54
|
return {
|
|
@@ -234,7 +236,7 @@ def advise(
|
|
|
234
236
|
caveats.append(
|
|
235
237
|
"Based on a single explain document — confirm this query shape "
|
|
236
238
|
"is frequent enough to justify an index "
|
|
237
|
-
"(mdbkit queries <log> --ns %s)." % shape.ns
|
|
239
|
+
"(mdbkit queries <log> --ns %s)." % sh_arg(shape.ns)
|
|
238
240
|
)
|
|
239
241
|
|
|
240
242
|
# Flags from the shape.
|
|
@@ -24,6 +24,7 @@ from .render import (
|
|
|
24
24
|
render_summary,
|
|
25
25
|
)
|
|
26
26
|
from .scripts import INDEXES_SCRIPT, SCHEMA_SCRIPT
|
|
27
|
+
from .quoting import sh_arg
|
|
27
28
|
|
|
28
29
|
|
|
29
30
|
def _warn_if_pre44(stats: ParseStats) -> None:
|
|
@@ -149,14 +150,14 @@ def _emit(entry, as_explain: bool, wrap: bool):
|
|
|
149
150
|
not abort a filter run over a million-line file."""
|
|
150
151
|
if not as_explain:
|
|
151
152
|
return entry.raw
|
|
152
|
-
from .rebuild import to_mongosh, wrap_for_export
|
|
153
|
+
from .rebuild import rebuild_parts, to_mongosh, wrap_for_export
|
|
153
154
|
try:
|
|
154
|
-
|
|
155
|
+
if wrap:
|
|
156
|
+
parts = rebuild_parts(entry)
|
|
157
|
+
return wrap_for_export(*parts) if parts else None
|
|
158
|
+
return to_mongosh(entry)
|
|
155
159
|
except Exception:
|
|
156
160
|
return None
|
|
157
|
-
if cmd is None:
|
|
158
|
-
return None
|
|
159
|
-
return wrap_for_export(cmd) if wrap else cmd
|
|
160
161
|
|
|
161
162
|
|
|
162
163
|
def cmd_filter(args) -> int:
|
|
@@ -666,12 +667,13 @@ def cmd_demo(args) -> int:
|
|
|
666
667
|
msg.append("wrote %s" % path)
|
|
667
668
|
msg.append("")
|
|
668
669
|
msg.append("Try:")
|
|
669
|
-
|
|
670
|
-
msg.append(" mdbkit
|
|
671
|
-
msg.append(" mdbkit
|
|
670
|
+
out = sh_arg(args.out)
|
|
671
|
+
msg.append(" mdbkit loginfo %s" % out)
|
|
672
|
+
msg.append(" mdbkit queries %s" % out)
|
|
673
|
+
msg.append(" mdbkit triage %s --window 0 --no-sysprobe" % out)
|
|
672
674
|
if args.with_extras:
|
|
673
675
|
msg.append(" mdbkit advise %s --indexes indexes.json "
|
|
674
|
-
"--schema schema.json" %
|
|
676
|
+
"--schema schema.json" % out)
|
|
675
677
|
msg.append(" mdbkit explain explain.json")
|
|
676
678
|
print("\n".join(msg), file=sys.stderr)
|
|
677
679
|
else:
|
|
@@ -715,7 +717,7 @@ def cmd_lab(args) -> int:
|
|
|
715
717
|
print("")
|
|
716
718
|
print("Next:")
|
|
717
719
|
print(" mdbkit lab seed # sample data + workload")
|
|
718
|
-
print(" mdbkit queries %s" % lab.log_paths(state)[0])
|
|
720
|
+
print(" mdbkit queries %s" % sh_arg(lab.log_paths(state)[0]))
|
|
719
721
|
print(" mdbkit lab destroy --yes # remove it all")
|
|
720
722
|
elif args.lab_action == "status":
|
|
721
723
|
state = lab.status(args.dir)
|
|
@@ -737,12 +739,12 @@ def cmd_lab(args) -> int:
|
|
|
737
739
|
print("")
|
|
738
740
|
print("Now analyse what it produced:")
|
|
739
741
|
first = lab.log_paths(state)[0]
|
|
740
|
-
print(" mdbkit queries %s" % first)
|
|
741
|
-
print(" mdbkit advise %s" % first)
|
|
742
|
+
print(" mdbkit queries %s" % sh_arg(first))
|
|
743
|
+
print(" mdbkit advise %s" % sh_arg(first))
|
|
742
744
|
if state.get("sharded"):
|
|
743
745
|
from .lab import DEFAULT_DIR
|
|
744
746
|
print(" mdbkit triage $(mdbkit lab logs%s | head -1) --window 0"
|
|
745
|
-
% ("" if args.dir == DEFAULT_DIR else " --dir %s" % args.dir))
|
|
747
|
+
% ("" if args.dir == DEFAULT_DIR else " --dir %s" % sh_arg(args.dir)))
|
|
746
748
|
elif args.lab_action == "stop":
|
|
747
749
|
n = lab.stop(args.dir, echo=_lab_echo)
|
|
748
750
|
print("stopped %d node(s)" % n)
|
|
@@ -24,6 +24,7 @@ from datetime import datetime, timezone
|
|
|
24
24
|
from typing import Dict, List, Optional, Tuple
|
|
25
25
|
|
|
26
26
|
from .parser import num, text
|
|
27
|
+
from .quoting import js_key, js_str
|
|
27
28
|
|
|
28
29
|
SPECIAL = ("text", "2d", "2dsphere", "hashed", "geoHaystack")
|
|
29
30
|
|
|
@@ -64,7 +65,7 @@ class IndexInfo:
|
|
|
64
65
|
any(f.endswith("$**") or f == "$**" for f, _ in self.key)
|
|
65
66
|
|
|
66
67
|
def key_str(self) -> str:
|
|
67
|
-
return "{ %s }" % ", ".join("%s: %s" % (f, _fmt(v)) for f, v in self.key)
|
|
68
|
+
return "{ %s }" % ", ".join("%s: %s" % (js_key(f), _fmt(v)) for f, v in self.key)
|
|
68
69
|
|
|
69
70
|
|
|
70
71
|
@dataclass
|
|
@@ -104,7 +105,7 @@ class Report:
|
|
|
104
105
|
|
|
105
106
|
def _fmt(v) -> str:
|
|
106
107
|
if isinstance(v, str):
|
|
107
|
-
return
|
|
108
|
+
return js_str(v)
|
|
108
109
|
if isinstance(v, float) and v.is_integer():
|
|
109
110
|
return str(int(v))
|
|
110
111
|
return str(v)
|
|
@@ -131,7 +132,8 @@ def _date(v) -> Optional[datetime]:
|
|
|
131
132
|
|
|
132
133
|
def hide_command(i: IndexInfo) -> str:
|
|
133
134
|
db, coll = i.ns.split(".", 1) if "." in i.ns else ("<db>", i.ns)
|
|
134
|
-
return
|
|
135
|
+
return "db.getSiblingDB(%s).getCollection(%s).hideIndex(%s)" % (
|
|
136
|
+
js_str(db), js_str(coll), js_str(i.name))
|
|
135
137
|
|
|
136
138
|
|
|
137
139
|
def load(paths: List[str]) -> Tuple[Dict[str, List[IndexInfo]], List[dict],
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""Quoting for the commands mdbkit prints for a person to copy and run.
|
|
2
|
+
|
|
3
|
+
A namespace, an index name, a field name or a hash inside a printed command
|
|
4
|
+
comes from a log or an export, and both are attacker-influenced: anyone who
|
|
5
|
+
can create a collection or an index chooses its name, an application can put
|
|
6
|
+
an end user's search text into a query, and a log someone sends you can say
|
|
7
|
+
anything. Pasted into mongosh or a shell unescaped, a quote, slash, semicolon
|
|
8
|
+
or backtick in such a value would end the string it sits in and run whatever
|
|
9
|
+
follows. So every value that came from a file goes through one of these
|
|
10
|
+
before it is printed inside a command. Plain values print exactly as before.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import json
|
|
14
|
+
import math
|
|
15
|
+
import re
|
|
16
|
+
import shlex
|
|
17
|
+
|
|
18
|
+
_IDENT = re.compile(r"[A-Za-z_$][A-Za-z0-9_$]*\Z")
|
|
19
|
+
_HEX = re.compile(r"[0-9A-Fa-f]+\Z")
|
|
20
|
+
_NUMBER = re.compile(r"-?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][-+]?\d+)?\Z")
|
|
21
|
+
_JS_SPECIAL = ("NaN", "Infinity", "-Infinity")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def js_str(value) -> str:
|
|
25
|
+
"""A JavaScript string literal that holds exactly `value`."""
|
|
26
|
+
return json.dumps(str(value), ensure_ascii=False)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def js_key(name) -> str:
|
|
30
|
+
"""An object key: bare when it is a plain identifier, quoted otherwise.
|
|
31
|
+
|
|
32
|
+
A dotted path such as customer.id has to be quoted to be valid
|
|
33
|
+
JavaScript anyway, so this also fixes those."""
|
|
34
|
+
name = str(name)
|
|
35
|
+
return name if _IDENT.match(name) else js_str(name)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def js_number(value) -> str:
|
|
39
|
+
"""A number as JavaScript; anything that is not a number is quoted."""
|
|
40
|
+
if isinstance(value, bool):
|
|
41
|
+
return js_str(value)
|
|
42
|
+
if isinstance(value, int):
|
|
43
|
+
return str(value)
|
|
44
|
+
if isinstance(value, float):
|
|
45
|
+
if math.isnan(value):
|
|
46
|
+
return "NaN"
|
|
47
|
+
if math.isinf(value):
|
|
48
|
+
return "Infinity" if value > 0 else "-Infinity"
|
|
49
|
+
return repr(value)
|
|
50
|
+
text = str(value)
|
|
51
|
+
if _NUMBER.match(text) or text in _JS_SPECIAL:
|
|
52
|
+
return text
|
|
53
|
+
return js_str(text)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def js_regex(pattern, options) -> str:
|
|
57
|
+
"""A regular expression as JavaScript.
|
|
58
|
+
|
|
59
|
+
The /pattern/flags literal is kept when it cannot end early: no slash or
|
|
60
|
+
line break in the pattern, no trailing backslash, no leading * (which
|
|
61
|
+
would open a comment) and letters-only flags. Anything else is written as
|
|
62
|
+
RegExp("pattern", "flags"), which matches the same strings."""
|
|
63
|
+
pattern = "" if pattern is None else str(pattern)
|
|
64
|
+
options = "" if options is None else str(options)
|
|
65
|
+
trailing = len(pattern) - len(pattern.rstrip("\\"))
|
|
66
|
+
literal_ok = (pattern and not pattern.startswith("*")
|
|
67
|
+
and not any(c in pattern for c in "/\n\r
")
|
|
68
|
+
and trailing % 2 == 0
|
|
69
|
+
and re.match(r"[a-z]*\Z", options))
|
|
70
|
+
if literal_ok:
|
|
71
|
+
return "/%s/%s" % (pattern, options)
|
|
72
|
+
return "RegExp(%s, %s)" % (js_str(pattern), js_str(options))
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def sh_arg(value) -> str:
|
|
76
|
+
"""One word for a POSIX shell (sh, bash, zsh). Plain words are unchanged."""
|
|
77
|
+
return shlex.quote(str(value))
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def hex_id(value):
|
|
81
|
+
"""`value` as text if it is a hex identifier (queryHash, planCacheKey,
|
|
82
|
+
queryShapeHash), otherwise None, so no command is printed for it."""
|
|
83
|
+
if value is None:
|
|
84
|
+
return None
|
|
85
|
+
text = str(value)
|
|
86
|
+
return text if _HEX.match(text) else None
|
|
@@ -11,20 +11,21 @@ sensitive: it is a query, not a redacted shape.
|
|
|
11
11
|
from __future__ import annotations
|
|
12
12
|
|
|
13
13
|
import json
|
|
14
|
-
from typing import Optional
|
|
14
|
+
from typing import Optional, Tuple
|
|
15
15
|
|
|
16
16
|
from .parser import LogEntry, num
|
|
17
|
+
from .quoting import js_number, js_regex, js_str
|
|
17
18
|
|
|
18
19
|
# BSON/Extended-JSON wrappers we can render as mongosh constructors.
|
|
19
20
|
_EJSON = {
|
|
20
|
-
"$oid": lambda v:
|
|
21
|
-
"$date": lambda v:
|
|
22
|
-
else "new Date(%s)" % v,
|
|
23
|
-
"$numberLong": lambda v: "NumberLong(%s)" % v,
|
|
24
|
-
"$numberInt":
|
|
25
|
-
"$numberDouble":
|
|
26
|
-
"$numberDecimal": lambda v:
|
|
27
|
-
"$uuid": lambda v:
|
|
21
|
+
"$oid": lambda v: "ObjectId(%s)" % js_str(v),
|
|
22
|
+
"$date": lambda v: "ISODate(%s)" % js_str(v) if isinstance(v, str)
|
|
23
|
+
else "new Date(%s)" % js_number(v),
|
|
24
|
+
"$numberLong": lambda v: "NumberLong(%s)" % js_str(v),
|
|
25
|
+
"$numberInt": js_number,
|
|
26
|
+
"$numberDouble": js_number,
|
|
27
|
+
"$numberDecimal": lambda v: "NumberDecimal(%s)" % js_str(v),
|
|
28
|
+
"$uuid": lambda v: "UUID(%s)" % js_str(v),
|
|
28
29
|
}
|
|
29
30
|
|
|
30
31
|
|
|
@@ -43,9 +44,8 @@ def _js(value, depth: int = 0) -> str:
|
|
|
43
44
|
if key == "$binary":
|
|
44
45
|
return '"<binary>"'
|
|
45
46
|
if key == "$regularExpression" and isinstance(value[key], dict):
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
return "/%s/%s" % (pat, opts)
|
|
47
|
+
return js_regex(value[key].get("pattern", ""),
|
|
48
|
+
value[key].get("options", ""))
|
|
49
49
|
if key == "$timestamp":
|
|
50
50
|
return "Timestamp(0, 0)"
|
|
51
51
|
parts = ["%s: %s" % (json.dumps(k), _js(v, depth + 1))
|
|
@@ -58,7 +58,7 @@ def _js(value, depth: int = 0) -> str:
|
|
|
58
58
|
if value is None:
|
|
59
59
|
return "null"
|
|
60
60
|
if isinstance(value, (int, float)):
|
|
61
|
-
return
|
|
61
|
+
return js_number(value)
|
|
62
62
|
return json.dumps(value)
|
|
63
63
|
|
|
64
64
|
|
|
@@ -68,13 +68,31 @@ def to_mongosh(entry: LogEntry, explain: bool = True,
|
|
|
68
68
|
|
|
69
69
|
Returns None if the entry is not a reconstructible operation.
|
|
70
70
|
"""
|
|
71
|
+
parts = rebuild_parts(entry, explain, verbosity)
|
|
72
|
+
if parts is None:
|
|
73
|
+
return None
|
|
74
|
+
code, note = parts
|
|
75
|
+
return code + (" // " + note if note else "")
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def rebuild_parts(entry: LogEntry, explain: bool = True,
|
|
79
|
+
verbosity: str = "executionStats"
|
|
80
|
+
) -> Optional[Tuple[str, Optional[str]]]:
|
|
81
|
+
"""The rebuilt command and an optional note for a comment, kept apart so
|
|
82
|
+
a wrapper such as EJSON.stringify(...) never closes inside the comment.
|
|
83
|
+
|
|
84
|
+
Every name and value from the log is quoted (see quoting.py): a
|
|
85
|
+
collection called x"); db.dropDatabase(); // must stay a string.
|
|
86
|
+
"""
|
|
71
87
|
attr = entry.attr or {}
|
|
72
88
|
command = attr.get("command")
|
|
73
89
|
if not isinstance(command, dict):
|
|
74
90
|
return None
|
|
75
91
|
|
|
76
92
|
ns = str(attr.get("ns") or "")
|
|
77
|
-
db = command.get("$db")
|
|
93
|
+
db = command.get("$db")
|
|
94
|
+
if not isinstance(db, str) or not db:
|
|
95
|
+
db = ns.split(".", 1)[0] if "." in ns else ""
|
|
78
96
|
coll = None
|
|
79
97
|
for key in ("find", "aggregate", "count", "distinct", "findAndModify",
|
|
80
98
|
"update", "delete"):
|
|
@@ -86,8 +104,8 @@ def to_mongosh(entry: LogEntry, explain: bool = True,
|
|
|
86
104
|
if not coll or not db:
|
|
87
105
|
return None
|
|
88
106
|
|
|
89
|
-
base =
|
|
90
|
-
suffix =
|
|
107
|
+
base = "db.getSiblingDB(%s).getCollection(%s)" % (js_str(db), js_str(coll))
|
|
108
|
+
suffix = ".explain(%s)" % js_str(verbosity) if explain else ""
|
|
91
109
|
|
|
92
110
|
# A single update or delete logged by the WRITE component (every real
|
|
93
111
|
# update line from 7.0 to 9.0): the command is the statement itself,
|
|
@@ -110,9 +128,9 @@ def to_mongosh(entry: LogEntry, explain: bool = True,
|
|
|
110
128
|
stmt = "%s.%s(%s)" % (base, method, _js(q))
|
|
111
129
|
what = "delete"
|
|
112
130
|
if explain:
|
|
113
|
-
return "%s.find(%s)%s
|
|
114
|
-
|
|
115
|
-
return stmt
|
|
131
|
+
return ("%s.find(%s)%s" % (base, _js(q), suffix),
|
|
132
|
+
"%s predicate; the %s itself: %s" % (what, what, stmt))
|
|
133
|
+
return stmt, None
|
|
116
134
|
|
|
117
135
|
if "find" in command:
|
|
118
136
|
filt = command.get("filter")
|
|
@@ -124,13 +142,13 @@ def to_mongosh(entry: LogEntry, explain: bool = True,
|
|
|
124
142
|
if isinstance(command.get("sort"), dict) and command["sort"]:
|
|
125
143
|
call += ".sort(%s)" % _js(command["sort"])
|
|
126
144
|
if command.get("skip"):
|
|
127
|
-
call += ".skip(%s)" % command["skip"]
|
|
145
|
+
call += ".skip(%s)" % js_number(command["skip"])
|
|
128
146
|
if command.get("limit"):
|
|
129
|
-
call += ".limit(%s)" % command["limit"]
|
|
147
|
+
call += ".limit(%s)" % js_number(command["limit"])
|
|
130
148
|
if command.get("hint"):
|
|
131
149
|
call += ".hint(%s)" % _js(command["hint"])
|
|
132
150
|
# skip/limit are numbers in the log; render only if they are
|
|
133
|
-
return call + suffix
|
|
151
|
+
return call + suffix, None
|
|
134
152
|
|
|
135
153
|
if "aggregate" in command:
|
|
136
154
|
pipeline = command.get("pipeline")
|
|
@@ -142,21 +160,22 @@ def to_mongosh(entry: LogEntry, explain: bool = True,
|
|
|
142
160
|
args = _js(pipeline)
|
|
143
161
|
if opts:
|
|
144
162
|
args += ", " + _js(opts)
|
|
145
|
-
return "%s.aggregate(%s)%s" % (base, args, suffix)
|
|
163
|
+
return "%s.aggregate(%s)%s" % (base, args, suffix), None
|
|
146
164
|
|
|
147
165
|
if "count" in command:
|
|
148
166
|
qq = command.get("query")
|
|
149
167
|
return "%s.count(%s)%s" % (base, _js(qq if isinstance(qq, dict) else {}),
|
|
150
|
-
suffix)
|
|
168
|
+
suffix), None
|
|
151
169
|
|
|
152
170
|
if "distinct" in command:
|
|
153
|
-
return
|
|
154
|
-
base, command.get("key", "")
|
|
171
|
+
return "%s.distinct(%s, %s)%s" % (
|
|
172
|
+
base, js_str(command.get("key", "")),
|
|
173
|
+
_js(command.get("query") or {}), suffix), None
|
|
155
174
|
|
|
156
175
|
if "findAndModify" in command:
|
|
157
176
|
spec = {k: command[k] for k in ("query", "sort", "update", "remove",
|
|
158
177
|
"new", "upsert") if k in command}
|
|
159
|
-
return "%s.findAndModify(%s)%s" % (base, _js(spec), suffix)
|
|
178
|
+
return "%s.findAndModify(%s)%s" % (base, _js(spec), suffix), None
|
|
160
179
|
|
|
161
180
|
if "update" in command:
|
|
162
181
|
# Real logs sometimes carry a count here rather than the array, so
|
|
@@ -175,10 +194,10 @@ def to_mongosh(entry: LogEntry, explain: bool = True,
|
|
|
175
194
|
if explain:
|
|
176
195
|
# explain() on a cursor is the reliable way to see the plan for
|
|
177
196
|
# the update's query predicate.
|
|
178
|
-
return (
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
return "%s.updateMany(%s, %s)" % (base, _js(q), _js(u))
|
|
197
|
+
return ("%s.find(%s)%s" % (base, _js(q), suffix),
|
|
198
|
+
"update predicate; the update itself: %s.updateMany(%s, %s)"
|
|
199
|
+
% (base, _js(q), _js(u)))
|
|
200
|
+
return "%s.updateMany(%s, %s)" % (base, _js(q), _js(u)), None
|
|
182
201
|
|
|
183
202
|
if "delete" in command:
|
|
184
203
|
deletes = command.get("deletes")
|
|
@@ -190,8 +209,8 @@ def to_mongosh(entry: LogEntry, explain: bool = True,
|
|
|
190
209
|
if not isinstance(q, dict):
|
|
191
210
|
return None
|
|
192
211
|
if explain:
|
|
193
|
-
return "%s.find(%s)%s
|
|
194
|
-
return "%s.deleteMany(%s)" % (base, _js(q))
|
|
212
|
+
return "%s.find(%s)%s" % (base, _js(q), suffix), "delete predicate"
|
|
213
|
+
return "%s.deleteMany(%s)" % (base, _js(q)), None
|
|
195
214
|
|
|
196
215
|
return None
|
|
197
216
|
|
|
@@ -205,6 +224,10 @@ HEADER = """// Rebuilt by mdbkit from a slow-query log line.
|
|
|
205
224
|
"""
|
|
206
225
|
|
|
207
226
|
|
|
208
|
-
def wrap_for_export(command: str) -> str:
|
|
209
|
-
"""Wrap a rebuilt command so its output is valid JSON for `mdbkit explain`.
|
|
210
|
-
|
|
227
|
+
def wrap_for_export(command: str, note: Optional[str] = None) -> str:
|
|
228
|
+
"""Wrap a rebuilt command so its output is valid JSON for `mdbkit explain`.
|
|
229
|
+
|
|
230
|
+
The note goes on its own comment line above: on the same line it would
|
|
231
|
+
swallow the closing bracket of EJSON.stringify(...)."""
|
|
232
|
+
lead = "// %s\n" % note if note else ""
|
|
233
|
+
return "%s%sEJSON.stringify(%s)\n" % (HEADER, lead, command)
|
|
@@ -8,6 +8,7 @@ from typing import List, Sequence
|
|
|
8
8
|
from .advisor import Recommendation
|
|
9
9
|
from .analysis import ConnectionReport, LogSummary, ShapeStats
|
|
10
10
|
from .parser import ParseStats
|
|
11
|
+
from .quoting import hex_id, js_str, sh_arg
|
|
11
12
|
|
|
12
13
|
|
|
13
14
|
def dump_json(obj) -> str:
|
|
@@ -676,24 +677,30 @@ def render_shape_detail(s, stats) -> str:
|
|
|
676
677
|
parts.append(" planCacheKey : %s" % listed(s.plan_cache_keys))
|
|
677
678
|
if s.query_shape_hashes:
|
|
678
679
|
parts.append(" queryShapeHash : %s" % listed(s.query_shape_hashes, 2))
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
680
|
+
# Hashes and names below come from the log: a hash is only used in a
|
|
681
|
+
# command when it is hex, and names are quoted (see quoting.py).
|
|
682
|
+
first = hex_id((s.plan_cache_hashes or s.query_shape_hashes).most_common(1)[0][0])
|
|
683
|
+
if first:
|
|
684
|
+
parts.append(" the full log lines : mdbkit filter <log> --query-hash %s --last 5"
|
|
685
|
+
% first)
|
|
686
|
+
parts.append(" as runnable explain: mdbkit filter <log> --query-hash %s --last 1 "
|
|
687
|
+
"--as-explain" % first)
|
|
688
|
+
qh = hex_id(s.plan_cache_hashes.most_common(1)[0][0]) if s.plan_cache_hashes else None
|
|
689
|
+
if qh and not s.routed:
|
|
684
690
|
db, _, coll = s.shape.ns.partition(".")
|
|
685
|
-
parts.append(" plan cache entry : db.getSiblingDB(
|
|
686
|
-
".aggregate([{$planCacheStats: {}}, {$match: {queryHash:
|
|
687
|
-
% (db, coll,
|
|
691
|
+
parts.append(" plan cache entry : db.getSiblingDB(%s).getCollection(%s)"
|
|
692
|
+
".aggregate([{$planCacheStats: {}}, {$match: {queryHash: %s}}])"
|
|
693
|
+
% (js_str(db), js_str(coll), js_str(qh)))
|
|
688
694
|
parts.append(" (run on the member that logged it; only queries that had "
|
|
689
695
|
"more than one candidate plan are cached)")
|
|
690
|
-
if s.query_shape_hashes
|
|
691
|
-
|
|
696
|
+
h = hex_id(s.query_shape_hashes.most_common(1)[0][0]) if s.query_shape_hashes else None
|
|
697
|
+
if h:
|
|
692
698
|
# Query settings apply to find, distinct and aggregate only.
|
|
693
699
|
base_op = s.shape.operation.replace("getMore(", "").rstrip(")")
|
|
694
700
|
if base_op in ("find", "distinct", "aggregate"):
|
|
695
701
|
parts.append(" pin or block this shape without a code change (8.0+):")
|
|
696
|
-
parts.append(" db.adminCommand({setQuerySettings:
|
|
702
|
+
parts.append(" db.adminCommand({setQuerySettings: %s, settings: {...}})"
|
|
703
|
+
% js_str(h))
|
|
697
704
|
parts.append("")
|
|
698
705
|
if s.shape.operation == "insert":
|
|
699
706
|
if s.waiting_pct is not None and s.waiting_pct >= 40:
|
|
@@ -706,9 +713,9 @@ def render_shape_detail(s, stats) -> str:
|
|
|
706
713
|
"write concern.")
|
|
707
714
|
elif s.routed:
|
|
708
715
|
parts.append("next: the plan is on the shards: mdbkit queries <shard log> "
|
|
709
|
-
"--ns %s" % s.shape.ns)
|
|
716
|
+
"--ns %s" % sh_arg(s.shape.ns))
|
|
710
717
|
else:
|
|
711
|
-
parts.append("next: mdbkit advise <log> --ns %s" % s.shape.ns)
|
|
718
|
+
parts.append("next: mdbkit advise <log> --ns %s" % sh_arg(s.shape.ns))
|
|
712
719
|
return "\n".join(parts)
|
|
713
720
|
|
|
714
721
|
|
|
@@ -35,6 +35,7 @@ from .audit import KNOWN as _AUDIT_KNOWN
|
|
|
35
35
|
from .parser import (ID_CONN_ACCEPTED, ID_LISTENING, ID_SHUTDOWN,
|
|
36
36
|
ID_SLOW_IN_PROGRESS, ID_STARTUP, LogEntry, ParseStats,
|
|
37
37
|
expand_paths, iter_entries, iter_entries_multi, num, text)
|
|
38
|
+
from .quoting import sh_arg
|
|
38
39
|
|
|
39
40
|
AUDIT_IDS = frozenset(_AUDIT_KNOWN)
|
|
40
41
|
# "mongod startup complete", whose attr says whether the previous shutdown
|
|
@@ -836,8 +837,9 @@ class TriageEngine:
|
|
|
836
837
|
s.shape.ns, s.shape.operation, s.count, _ms(s.total_ms),
|
|
837
838
|
s.shape.pretty()[:60])
|
|
838
839
|
for s in shapes[:3]],
|
|
839
|
-
("Plans are in the shard logs: mdbkit advise <shard log> --ns %s" % ns
|
|
840
|
-
if self.sharding.role == "mongos"
|
|
840
|
+
("Plans are in the shard logs: mdbkit advise <shard log> --ns %s" % sh_arg(ns)
|
|
841
|
+
if self.sharding.role == "mongos"
|
|
842
|
+
else "mdbkit advise <log> --ns %s" % sh_arg(ns))))
|
|
841
843
|
|
|
842
844
|
out.extend(self._waiting_findings(shapes))
|
|
843
845
|
return out
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: mdbkit
|
|
3
|
-
Version: 0.8.
|
|
3
|
+
Version: 0.8.2
|
|
4
4
|
Summary: Offline toolkit for MongoDB 4.4 to 9.0 logs and diagnostics: slow-query shapes, index advice and index usage, incident triage, sharded clusters, multi-instance hosts, startup configuration audit, FTDC decoding. A spiritual successor to mtools' log tools.
|
|
5
5
|
Author: Saqib Ameen Subhan
|
|
6
6
|
License: MIT
|
|
@@ -1595,6 +1595,15 @@ Linux box the database actually runs on.
|
|
|
1595
1595
|
are still read, and misread log lines are still the most useful thing to
|
|
1596
1596
|
send.
|
|
1597
1597
|
|
|
1598
|
+
**v0.8.2 is a security fix: upgrade.** The commands mdbkit prints for you
|
|
1599
|
+
to paste (`--as-explain`, the plan cache lookup, `hideIndex`, the `--ns`
|
|
1600
|
+
hints) put names from the log or export in as they were. A crafted
|
|
1601
|
+
collection name, or a regex built from an application user's search text,
|
|
1602
|
+
could turn the printed line into one that runs something else when pasted.
|
|
1603
|
+
Every such value is now quoted. It also fixes `--explain-script` for updates
|
|
1604
|
+
and deletes, which wrote a script mongosh could not run. Details:
|
|
1605
|
+
[SECURITY.md](SECURITY.md#security-fixes).
|
|
1606
|
+
|
|
1598
1607
|
**Shipped in v0.8.1:** the `queryHash` of each shape in the `queries`
|
|
1599
1608
|
table, `queries --shape <hash>` and `filter --query-hash`, to go from a
|
|
1600
1609
|
shape back to its full log lines
|
|
@@ -1643,10 +1652,13 @@ the most valuable bug reports of all (redact literals first!).
|
|
|
1643
1652
|
|
|
1644
1653
|
## Security
|
|
1645
1654
|
|
|
1646
|
-
mdbkit is offline by design:
|
|
1647
|
-
|
|
1648
|
-
|
|
1649
|
-
|
|
1655
|
+
mdbkit is offline by design: no analysis command contains network code
|
|
1656
|
+
(`lab` is the documented exception), nothing it reads is ever executed or
|
|
1657
|
+
evaluated, and every log line is treated as untrusted data (strict JSON
|
|
1658
|
+
parsing only — shell constructors are never evaluated). Commands it prints
|
|
1659
|
+
for you to paste quote every name taken from a log or export, so a crafted
|
|
1660
|
+
name cannot become code (fixed in 0.8.2). See [SECURITY.md](SECURITY.md)
|
|
1661
|
+
for what every release is checked for and the reporting process.
|
|
1650
1662
|
|
|
1651
1663
|
## Non-affiliation
|
|
1652
1664
|
|
|
@@ -16,6 +16,7 @@ mdbkit/indexusage.py
|
|
|
16
16
|
mdbkit/lab.py
|
|
17
17
|
mdbkit/oslog.py
|
|
18
18
|
mdbkit/parser.py
|
|
19
|
+
mdbkit/quoting.py
|
|
19
20
|
mdbkit/rebuild.py
|
|
20
21
|
mdbkit/render.py
|
|
21
22
|
mdbkit/report.py
|
|
@@ -37,6 +38,7 @@ tests/test_host.py
|
|
|
37
38
|
tests/test_indexes.py
|
|
38
39
|
tests/test_mdbkit.py
|
|
39
40
|
tests/test_oslog_serverstatus.py
|
|
41
|
+
tests/test_printed_commands.py
|
|
40
42
|
tests/test_query_hash.py
|
|
41
43
|
tests/test_real_failures.py
|
|
42
44
|
tests/test_real_servers.py
|
|
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
|
|
|
7
7
|
|
|
8
8
|
[project]
|
|
9
9
|
name = "mdbkit"
|
|
10
|
-
version = "0.8.
|
|
10
|
+
version = "0.8.2"
|
|
11
11
|
description = "Offline toolkit for MongoDB 4.4 to 9.0 logs and diagnostics: slow-query shapes, index advice and index usage, incident triage, sharded clusters, multi-instance hosts, startup configuration audit, FTDC decoding. A spiritual successor to mtools' log tools."
|
|
12
12
|
readme = "README.md"
|
|
13
13
|
requires-python = ">=3.8"
|
|
@@ -0,0 +1,246 @@
|
|
|
1
|
+
"""Commands mdbkit prints for a person to copy must not be hijackable.
|
|
2
|
+
|
|
3
|
+
A collection, index or field name in a log or export is chosen by whoever
|
|
4
|
+
created it, and a log someone sends you can say anything. Before 0.8.2 a
|
|
5
|
+
collection named x"); db.dropDatabase(); (" turned the printed plan-cache
|
|
6
|
+
line into a command that dropped the database when pasted into mongosh, and
|
|
7
|
+
a namespace with ; or backticks did the same to a printed shell hint. These
|
|
8
|
+
tests feed such names through every command that prints one and check that
|
|
9
|
+
each name comes back out exactly, as one string or one shell word.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import contextlib
|
|
13
|
+
import io
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import re
|
|
17
|
+
import shlex
|
|
18
|
+
import shutil
|
|
19
|
+
import subprocess
|
|
20
|
+
|
|
21
|
+
import pytest
|
|
22
|
+
|
|
23
|
+
from mdbkit.cli import main
|
|
24
|
+
from mdbkit.quoting import hex_id, js_key, js_number, js_regex, js_str, sh_arg
|
|
25
|
+
|
|
26
|
+
COLL = 'x\'"); db.dropDatabase(); ("`id` ; touch PWNED //'
|
|
27
|
+
NS = "shop." + COLL
|
|
28
|
+
INDEX = 'i"); db.dropDatabase(); ("'
|
|
29
|
+
FIELD = 'f"); x(); ("'
|
|
30
|
+
T = {"$date": "2026-12-03T10:00:00.000+00:00"}
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def run(argv, cwd=None):
|
|
34
|
+
out, err = io.StringIO(), io.StringIO()
|
|
35
|
+
old = os.getcwd()
|
|
36
|
+
if cwd:
|
|
37
|
+
os.chdir(cwd)
|
|
38
|
+
try:
|
|
39
|
+
with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
|
|
40
|
+
try:
|
|
41
|
+
rc = main(argv)
|
|
42
|
+
except SystemExit as exc:
|
|
43
|
+
rc = exc.code
|
|
44
|
+
finally:
|
|
45
|
+
os.chdir(old)
|
|
46
|
+
return rc, out.getvalue(), err.getvalue()
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def slow(ns, command, **attr):
|
|
50
|
+
a = {"type": "command", "ns": ns, "appName": "a", "command": command,
|
|
51
|
+
"planSummary": "COLLSCAN", "keysExamined": 0, "docsExamined": 500000,
|
|
52
|
+
"nreturned": 1, "durationMillis": 9000, "remote": "10.0.0.9:1"}
|
|
53
|
+
a.update(attr)
|
|
54
|
+
return {"t": T, "s": "I", "c": "COMMAND", "id": 51803, "ctx": "conn7",
|
|
55
|
+
"msg": "Slow query", "attr": a}
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
@pytest.fixture
|
|
59
|
+
def hostile(tmp_path):
|
|
60
|
+
lines = [slow(NS, {"find": COLL, "$db": "shop", "sort": {"ts": -1},
|
|
61
|
+
"skip": "1); db.dropDatabase(); (1", "limit": 5,
|
|
62
|
+
"filter": {FIELD: "v'\"`id`",
|
|
63
|
+
"re": {"$regularExpression": {
|
|
64
|
+
"pattern": "^/api/v1/", "options": "i"}},
|
|
65
|
+
"bad": {"$regularExpression": {
|
|
66
|
+
"pattern": "^ok", "options": "i); x(); //"}},
|
|
67
|
+
"oid": {"$oid": '"); db.dropDatabase(); ("'},
|
|
68
|
+
"n": {"$numberLong": "1); db.dropDatabase(); (1"}}},
|
|
69
|
+
queryHash="DEADBEEF", planCacheShapeHash="DEADBEEF",
|
|
70
|
+
planCacheKey="0BADF00D", queryShapeHash="AB" * 32)
|
|
71
|
+
for _ in range(3)]
|
|
72
|
+
lines.append(slow("shop.forged", {"find": "forged", "$db": "shop", "filter": {"a": 1}},
|
|
73
|
+
queryHash='"); db.dropDatabase(); ("',
|
|
74
|
+
queryShapeHash='"}); db.dropDatabase(); ({"'))
|
|
75
|
+
lines.append(slow(NS, {"distinct": COLL, "$db": "shop",
|
|
76
|
+
"key": 'k"); db.dropDatabase(); ("', "query": {}},
|
|
77
|
+
queryHash="CAFEBABE"))
|
|
78
|
+
lines.append({"t": T, "s": "I", "c": "WRITE", "id": 51803, "ctx": "conn7",
|
|
79
|
+
"msg": "Slow query", "attr": {
|
|
80
|
+
"type": "update", "ns": NS, "queryHash": "1234ABCD",
|
|
81
|
+
"command": {"q": {"_id": 1}, "u": {"$set": {"a": 1}},
|
|
82
|
+
"multi": False, "upsert": False},
|
|
83
|
+
"planSummary": "IDHACK", "keysExamined": 1, "docsExamined": 1,
|
|
84
|
+
"durationMillis": 800}})
|
|
85
|
+
path = tmp_path / "hostile.log"
|
|
86
|
+
path.write_text("\n".join(json.dumps(l) for l in lines) + "\n")
|
|
87
|
+
return str(path)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
STRING = r'"(?:[^"\\]|\\.)*"'
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def call_args(js, method):
|
|
94
|
+
"""The string arguments of every .method("...") call in a line of JS."""
|
|
95
|
+
return [json.loads(m) for m in re.findall(r"\.%s\((%s)" % (method, STRING), js)]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def shell_words(line):
|
|
99
|
+
cmd = line[line.index("mdbkit "):].rstrip(").")
|
|
100
|
+
return shlex.split(cmd.replace("<shard log>", "LOG").replace("<log>", "LOG"))
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
# --------------------------------------------------------------- helpers --
|
|
104
|
+
|
|
105
|
+
def test_js_str_round_trips_any_name():
|
|
106
|
+
for name in (COLL, INDEX, "a\nb", "tab\there", "back\\slash", "日本語", ""):
|
|
107
|
+
assert json.loads(js_str(name)) == name
|
|
108
|
+
assert js_str("orders") == '"orders"'
|
|
109
|
+
|
|
110
|
+
|
|
111
|
+
def test_js_key_quotes_only_what_needs_it():
|
|
112
|
+
assert js_key("status") == "status"
|
|
113
|
+
assert js_key("a.b") == '"a.b"' # a bare a.b is not valid JavaScript
|
|
114
|
+
assert js_key("$**") == '"$**"'
|
|
115
|
+
assert json.loads(js_key(FIELD)) == FIELD
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def test_js_number_never_emits_code():
|
|
119
|
+
assert js_number(5) == "5" and js_number("42") == "42"
|
|
120
|
+
assert js_number("-1.5e3") == "-1.5e3" and js_number("NaN") == "NaN"
|
|
121
|
+
assert js_number(float("inf")) == "Infinity"
|
|
122
|
+
assert json.loads(js_number("1); x(); (1")) == "1); x(); (1"
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
def test_js_regex_keeps_simple_literals_and_quotes_the_rest():
|
|
126
|
+
assert js_regex("^abc", "i") == "/^abc/i"
|
|
127
|
+
assert js_regex("^/api/", "i") == 'RegExp("^/api/", "i")'
|
|
128
|
+
assert js_regex("", "") == 'RegExp("", "")' # // would be a comment
|
|
129
|
+
assert js_regex("*x", "") == 'RegExp("*x", "")' # /* would open one
|
|
130
|
+
assert js_regex("a\\", "") == 'RegExp("a\\\\", "")' # trailing backslash
|
|
131
|
+
assert js_regex("ok", "i); x(); //").startswith("RegExp(")
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def test_sh_arg_is_one_word():
|
|
135
|
+
for value in (NS, "a b", "$(touch x)", "`id`", "it's"):
|
|
136
|
+
assert shlex.split("cmd --ns " + sh_arg(value)) == ["cmd", "--ns", value]
|
|
137
|
+
assert sh_arg("shop.orders") == "shop.orders"
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def test_hex_id_rejects_anything_but_hex():
|
|
141
|
+
assert hex_id("DEADBEEF") == "DEADBEEF" and hex_id("ab" * 32) == "ab" * 32
|
|
142
|
+
assert hex_id('"); x(); //') is None and hex_id("") is None and hex_id(None) is None
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
# ------------------------------------------------------------ end to end --
|
|
146
|
+
|
|
147
|
+
def test_queries_detail_quotes_names_and_shell_hints(hostile):
|
|
148
|
+
rc, out, _ = run(["queries", hostile, "--shape", "DEADBEEF"])
|
|
149
|
+
assert rc == 0
|
|
150
|
+
plan = [l for l in out.splitlines() if "$planCacheStats" in l][0]
|
|
151
|
+
assert call_args(plan, "getSiblingDB") == ["shop"]
|
|
152
|
+
assert call_args(plan, "getCollection") == [COLL]
|
|
153
|
+
settings = [l for l in out.splitlines() if "setQuerySettings" in l][0]
|
|
154
|
+
assert '"%s"' % ("AB" * 32) in settings
|
|
155
|
+
hint = [l for l in out.splitlines() if l.startswith("next:")][0]
|
|
156
|
+
words = shell_words(hint)
|
|
157
|
+
assert words[words.index("--ns") + 1] == NS
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def test_a_forged_hash_is_never_put_in_a_command(hostile):
|
|
161
|
+
details = [run(["queries", hostile, "--shape", str(n)])[1] for n in range(1, 4)]
|
|
162
|
+
forged = [d for d in details if "namespace : shop.forged" in d]
|
|
163
|
+
assert len(forged) == 1
|
|
164
|
+
for marker in ("--query-hash", "$planCacheStats", "setQuerySettings"):
|
|
165
|
+
assert marker not in forged[0]
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def test_as_explain_quotes_every_value(hostile):
|
|
169
|
+
rc, out, _ = run(["filter", hostile, "--query-hash", "DEADBEEF", "--last", "1",
|
|
170
|
+
"--as-explain"])
|
|
171
|
+
line = out.strip().splitlines()[-1]
|
|
172
|
+
assert call_args(line, "getCollection") == [COLL]
|
|
173
|
+
assert '.skip("1); db.dropDatabase(); (1")' in line
|
|
174
|
+
assert 'ObjectId("\\"); db.dropDatabase(); (\\"")' in line
|
|
175
|
+
assert 'NumberLong("1); db.dropDatabase(); (1")' in line
|
|
176
|
+
assert 'RegExp("^/api/v1/", "i")' in line
|
|
177
|
+
assert 'RegExp("^ok", "i); x(); //")' in line
|
|
178
|
+
rc, out, _ = run(["filter", hostile, "--query-hash", "CAFEBABE", "--as-explain"])
|
|
179
|
+
assert call_args(out, "distinct") == ['k"); db.dropDatabase(); ("']
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def test_a_search_box_regex_stays_a_regex(tmp_path):
|
|
183
|
+
# The most exposed route: an app that turns a user's search text into a
|
|
184
|
+
# regex puts that text in the slow-query log. This pattern is a valid
|
|
185
|
+
# regex for the server, and before 0.8.2 the printed /.../ literal ran
|
|
186
|
+
# db.dropDatabase() when the --as-explain line was pasted into mongosh.
|
|
187
|
+
pattern = "a/+(db.dropDatabase())+/b"
|
|
188
|
+
p = tmp_path / "s.log"
|
|
189
|
+
p.write_text(json.dumps(slow("shop.products", {
|
|
190
|
+
"find": "products", "$db": "shop",
|
|
191
|
+
"filter": {"name": {"$regularExpression": {"pattern": pattern, "options": "i"}}}},
|
|
192
|
+
queryHash="C0FFEE11")) + "\n")
|
|
193
|
+
rc, out, _ = run(["filter", str(p), "--as-explain"])
|
|
194
|
+
assert 'RegExp(%s, "i")' % json.dumps(pattern) in out
|
|
195
|
+
assert "/a/+(" not in out
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def test_explain_script_for_an_update_closes_its_brackets(hostile):
|
|
199
|
+
# The update itself used to sit in a trailing // comment, which swallowed
|
|
200
|
+
# the closing bracket of EJSON.stringify( and broke the script.
|
|
201
|
+
rc, out, _ = run(["filter", hostile, "--query-hash", "1234ABCD", "--as-explain",
|
|
202
|
+
"--explain-script"])
|
|
203
|
+
body = [l for l in out.splitlines() if l and not l.startswith("//")]
|
|
204
|
+
assert len(body) == 1
|
|
205
|
+
assert body[0].startswith("EJSON.stringify(") and body[0].endswith(")")
|
|
206
|
+
assert any(l.startswith("// update predicate; the update itself:")
|
|
207
|
+
for l in out.splitlines())
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def test_indexes_hide_command_and_key_are_quoted(tmp_path):
|
|
211
|
+
p = tmp_path / "ix.json"
|
|
212
|
+
p.write_text(json.dumps({
|
|
213
|
+
"db": "", "generatedAt": "2026-12-01T00:00:00Z",
|
|
214
|
+
"collections": {NS: [{"name": "_id_", "key": {"_id": 1}},
|
|
215
|
+
{"name": INDEX, "key": {FIELD: 1, "a.b": "hashed"}}]},
|
|
216
|
+
"usage": {NS: [{"name": INDEX, "host": "h", "ops": 0,
|
|
217
|
+
"since": "2026-09-01T00:00:00Z"}]}}))
|
|
218
|
+
rc, out, _ = run(["indexes", str(p), "--json"])
|
|
219
|
+
finding = [f for f in json.loads(out)["findings"] if f["index"] == INDEX][0]
|
|
220
|
+
assert call_args(finding["hideCommand"], "getCollection") == [COLL]
|
|
221
|
+
assert call_args(finding["hideCommand"], "hideIndex") == [INDEX]
|
|
222
|
+
assert finding["key"] == '{ %s: 1, "a.b": "hashed" }' % json.dumps(FIELD)
|
|
223
|
+
|
|
224
|
+
|
|
225
|
+
def test_advise_candidate_quotes_odd_field_names(hostile):
|
|
226
|
+
rc, out, _ = run(["advise", hostile])
|
|
227
|
+
cand = [l for l in out.splitlines() if "candidate" in l and "dropDatabase" not in l
|
|
228
|
+
and FIELD.split('"')[0] in l]
|
|
229
|
+
assert cand and json.dumps(FIELD) in cand[0]
|
|
230
|
+
|
|
231
|
+
|
|
232
|
+
def test_demo_hints_keep_an_odd_path_as_one_word(tmp_path):
|
|
233
|
+
rc, out, err = run(["demo", "-o", "my logs;touch PWNED.log"], cwd=str(tmp_path))
|
|
234
|
+
hints = [l.strip() for l in err.splitlines() if l.strip().startswith("mdbkit ")]
|
|
235
|
+
assert hints
|
|
236
|
+
for h in hints:
|
|
237
|
+
assert shlex.split(h)[2] == "my logs;touch PWNED.log"
|
|
238
|
+
|
|
239
|
+
|
|
240
|
+
@pytest.mark.skipif(not shutil.which("node"), reason="node not installed")
|
|
241
|
+
def test_printed_mongosh_parses_as_javascript(hostile):
|
|
242
|
+
"""With node available, check the printed lines really are valid JS."""
|
|
243
|
+
rc, out, _ = run(["filter", hostile, "--as-explain", "--explain-script"])
|
|
244
|
+
res = subprocess.run(["node", "--check", "-"], input=out, capture_output=True,
|
|
245
|
+
text=True)
|
|
246
|
+
assert res.returncode == 0, res.stderr
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|