logspecter 0.1.0__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.
Files changed (43) hide show
  1. logspecter-0.1.0/.gitignore +24 -0
  2. logspecter-0.1.0/LICENSE +202 -0
  3. logspecter-0.1.0/PKG-INFO +349 -0
  4. logspecter-0.1.0/README.md +315 -0
  5. logspecter-0.1.0/pyproject.toml +94 -0
  6. logspecter-0.1.0/src/logspecter/__init__.py +34 -0
  7. logspecter-0.1.0/src/logspecter/__main__.py +12 -0
  8. logspecter-0.1.0/src/logspecter/baseline.py +121 -0
  9. logspecter-0.1.0/src/logspecter/cli.py +742 -0
  10. logspecter-0.1.0/src/logspecter/cloud.py +380 -0
  11. logspecter-0.1.0/src/logspecter/engine.py +483 -0
  12. logspecter-0.1.0/src/logspecter/entropy.py +546 -0
  13. logspecter-0.1.0/src/logspecter/findings.py +208 -0
  14. logspecter-0.1.0/src/logspecter/ingest.py +384 -0
  15. logspecter-0.1.0/src/logspecter/prefilter.py +723 -0
  16. logspecter-0.1.0/src/logspecter/redact.py +50 -0
  17. logspecter-0.1.0/src/logspecter/report/__init__.py +23 -0
  18. logspecter-0.1.0/src/logspecter/report/console.py +342 -0
  19. logspecter-0.1.0/src/logspecter/report/exporters.py +245 -0
  20. logspecter-0.1.0/src/logspecter/rules/aws.yaml +107 -0
  21. logspecter-0.1.0/src/logspecter/rules/azure.yaml +87 -0
  22. logspecter-0.1.0/src/logspecter/rules/database.yaml +86 -0
  23. logspecter-0.1.0/src/logspecter/rules/gcp.yaml +94 -0
  24. logspecter-0.1.0/src/logspecter/rules/generic.yaml +148 -0
  25. logspecter-0.1.0/src/logspecter/rules/private_keys.yaml +67 -0
  26. logspecter-0.1.0/src/logspecter/rules/vendors.yaml +329 -0
  27. logspecter-0.1.0/src/logspecter/rules.py +434 -0
  28. logspecter-0.1.0/src/logspecter/samples.py +450 -0
  29. logspecter-0.1.0/src/logspecter/scanner.py +763 -0
  30. logspecter-0.1.0/src/logspecter/structured.py +168 -0
  31. logspecter-0.1.0/src/logspecter/sysinfo.py +134 -0
  32. logspecter-0.1.0/tests/_fixtures.py +18 -0
  33. logspecter-0.1.0/tests/conftest.py +41 -0
  34. logspecter-0.1.0/tests/test_cli.py +447 -0
  35. logspecter-0.1.0/tests/test_cloud.py +198 -0
  36. logspecter-0.1.0/tests/test_engine.py +269 -0
  37. logspecter-0.1.0/tests/test_entropy.py +182 -0
  38. logspecter-0.1.0/tests/test_ingest.py +199 -0
  39. logspecter-0.1.0/tests/test_prefilter.py +183 -0
  40. logspecter-0.1.0/tests/test_report.py +308 -0
  41. logspecter-0.1.0/tests/test_rules.py +201 -0
  42. logspecter-0.1.0/tests/test_scanner.py +274 -0
  43. logspecter-0.1.0/tests/test_structured.py +94 -0
@@ -0,0 +1,24 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ *.egg-info/
4
+ .eggs/
5
+ build/
6
+ dist/
7
+ .venv/
8
+ venv/
9
+ .pytest_cache/
10
+ .ruff_cache/
11
+ .coverage
12
+ coverage.xml
13
+ htmlcov/
14
+ .idea/
15
+ .vscode/
16
+ *.log
17
+ *.log.gz
18
+ bench/
19
+ scratch/
20
+ .logspecter-baseline.json
21
+
22
+ # 但示例日志需要入库
23
+ !examples/*.log
24
+ !examples/*.jsonl
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,349 @@
1
+ Metadata-Version: 2.5
2
+ Name: logspecter
3
+ Version: 0.1.0
4
+ Summary: Schema-aware, entropy-validated secret scanner for cloud logs. Streams tens of GB with a flat ~50 MB memory ceiling.
5
+ Project-URL: Homepage, https://github.com/logspecter/logspecter
6
+ Project-URL: Repository, https://github.com/logspecter/logspecter
7
+ Project-URL: Issues, https://github.com/logspecter/logspecter/issues
8
+ Author: LogSpecter Contributors
9
+ License: Apache-2.0
10
+ License-File: LICENSE
11
+ Keywords: cloudtrail,dfir,logging,secret-scanning,security,shannon-entropy,soc2
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: System Administrators
16
+ Classifier: License :: OSI Approved :: Apache Software License
17
+ Classifier: Operating System :: OS Independent
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Topic :: Security
23
+ Classifier: Topic :: System :: Logging
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: orjson>=3.9
26
+ Requires-Dist: pyyaml>=6.0
27
+ Requires-Dist: rich>=13.0
28
+ Requires-Dist: typer>=0.12
29
+ Provides-Extra: dev
30
+ Requires-Dist: pytest-cov>=5.0; extra == 'dev'
31
+ Requires-Dist: pytest>=8.0; extra == 'dev'
32
+ Requires-Dist: ruff>=0.6; extra == 'dev'
33
+ Description-Content-Type: text/markdown
34
+
35
+ # LogSpecter
36
+
37
+ **Schema-aware secret scanner for cloud logs.** Regex finds candidates; Shannon entropy and a
38
+ heuristic layer decide whether they are real keys; a JSON-structure layer tells you *who* leaked
39
+ *what* through *which field*. Streams tens of gigabytes with a flat memory ceiling.
40
+
41
+ ```
42
+ $ logspecter scan cloudtrail-2026-08-30.json.gz --stats
43
+
44
+ CRITICAL openai-api-key AWS IAM User (Alice) → action: AssumeRole
45
+ → requestParameters.headers.Authorization
46
+ cloudtrail-2026-08-30.json.gz:81421 @byte 24118904
47
+ sk-p********kAyS (len=64) conf 1.00 / H 5.19
48
+ ```
49
+
50
+ Not "a suspicious string on line 800". The actual identity, the actual API call, the actual JSON path.
51
+
52
+ ---
53
+
54
+ ## Why another secret scanner
55
+
56
+ Most log scanners are a pile of regexes. That fails in production for three reasons, and
57
+ LogSpecter attacks each one directly.
58
+
59
+ ### 1. Regex alone cannot tell a key from a session token
60
+
61
+ A rule like "base64 string of 32+ chars" fires on every pagination cursor, every trace ID, every
62
+ base64-encoded JSON blob in your logs. LogSpecter runs a second stage on every candidate:
63
+
64
+ | Check | What it kills |
65
+ | --- | --- |
66
+ | Shannon entropy + charset-normalised entropy | low-diversity strings that merely *look* long |
67
+ | Charset coverage (unique chars ÷ *achievable* unique chars) | `aaaa…`, `ababab…`, and it does **not** penalise 64-char hex hashes |
68
+ | Repeat / sequential runs | `xxxxxxxx`, `abcdefgh`, `987654321` |
69
+ | Natural-language likeness (bigram + vowel ratio) | `SpringBootApplicationConfigurationLoader` |
70
+ | Base64 decode-back | strings that decode to readable text or JSON — encoded *data*, not keys |
71
+ | Placeholder & vendor-doc detection | `AKIAIOSFODNN7EXAMPLE`, `changeme`, `<your-api-key>`, `${VAR}` |
72
+ | Keyword proximity | a 32-char hex blob only counts near `key`/`secret`/`hmac` |
73
+
74
+ Every decision is recorded on the finding, so you can audit *why* something was reported or
75
+ dropped:
76
+
77
+ ```json
78
+ "evidence": ["entropy=5.61/6.00(base64url)", "charset_coverage=0.85",
79
+ "non-linguistic", "keyword-nearby", "also-matched:authorization-header-bearer"]
80
+ ```
81
+
82
+ Entropy thresholds are **per rule**, not global. `Authorization: Basic` intentionally disables the
83
+ decode-back check (Basic auth *is* base64 text); database URLs relax entropy to catch weak human
84
+ passwords while relying on the `scheme://user:pass@host` shape for precision.
85
+
86
+ ### 2. Treating logs as plain text throws away all the context
87
+
88
+ LogSpecter parses records with [orjson](https://github.com/ijl/orjson) (Rust-backed) and
89
+ recognises the schema it is looking at:
90
+
91
+ * AWS CloudTrail — IAM identity, `eventName`, region, source IP, account
92
+ * GCP Cloud Logging — `principalEmail`, `methodName`, resource, project
93
+ * Kubernetes audit — user, verb, `objectRef`
94
+ * Azure Activity Log — identity claims, `operationName`, result
95
+ * Elastic Common Schema, Logback / Log4j2 JSON (including MDC)
96
+
97
+ Nested JSON-inside-a-JSON-string is expanded too, because `requestParameters` and MDC fields are
98
+ full of it. You get a precise path (`protoPayload.request.credential`) instead of a line number,
99
+ plus the actor and action needed to actually respond to the incident.
100
+
101
+ ### 3. `readlines()` on a 30 GB log is an OOM
102
+
103
+ The input layer plans **line-aligned byte ranges** without reading the file (a few seeks and small
104
+ tail reads), then hands one range per worker. Compressed files and stdin go through a
105
+ producer/consumer path with a bounded submission window. Resident memory is a function of chunk
106
+ size, never of file size:
107
+
108
+ | Scan | Wall time | Throughput | Main RSS | Peak worker RSS |
109
+ | --- | --- | --- | --- | --- |
110
+ | 256 MiB, 1 worker | 20.7 s | 12.4 MiB/s | 45 MiB | — |
111
+ | 256 MiB, 8 workers | 5.1 s | 49.9 MiB/s | 42 MiB | 34 MiB |
112
+ | 1 GiB, 8 workers | 18.6 s | 55.0 MiB/s | 43 MiB | 35 MiB |
113
+
114
+ Same memory for 1 GiB as for 256 MiB. Measured with `GetProcessMemoryInfo` /
115
+ `/proc/self/status` and reported by `--stats` — not a claim, an output field.
116
+ Numbers from `logspecter benchmark` on 8 cores / Windows / CPython 3.13, scanning a synthetic mix
117
+ of CloudTrail records, application logs, and high-entropy-but-harmless noise. Reproduce with
118
+ `logspecter benchmark --size 1GB -j 8`; pure-Python throughput is CPU-bound, so expect it to track
119
+ your single-core speed times the worker count.
120
+
121
+ <details>
122
+ <summary><b>How it gets there in pure Python</b> (the part that took the most work)</summary>
123
+
124
+ A naive "for each line, for each rule, run the regex" loop benchmarks at **3.4 MiB/s**. Three
125
+ changes took it to 12.4 MiB/s per core:
126
+
127
+ 1. **Bytes end to end.** Rules compile to `bytes` patterns, so there is no per-chunk decode, match
128
+ offsets *are* file offsets, and `\b`/`\w` get predictable ASCII semantics.
129
+
130
+ 2. **Occurrence-driven scanning instead of line iteration.** Each rule's regex AST is statically
131
+ analysed for literals that *must* appear in any match (`\b((?:AKIA|ASIA)[A-Z0-9]{16})\b` →
132
+ `AKIA|ASIA`). Those literals are located with `bytes.find` (~3.7 GiB/s) and the regex runs only
133
+ on the lines that contain them. A monotonic cursor per literal means an absent literal is
134
+ scanned once, not once per line — getting this wrong cost a 50× slowdown before it was fixed.
135
+
136
+ 3. **Anchored matching.** The analyser also computes how many bytes of the match may precede the
137
+ literal. `_live_` in `(?:sk|rk)_live_…` is always at offset 2, so instead of `search()`-ing a
138
+ whole line the scanner tries `match()` at one exact position. This is what removed most of the
139
+ remaining cost: "literal present but regex does not match" is the single most common case in
140
+ real logs (every CloudTrail S3 record contains `"key":`).
141
+
142
+ Literals are merged into prefix-tree regexes (`key|keystore|kms` → `k(?:ey(?:store)?|ms)`) so
143
+ CPython's `INFO` first-character-set optimisation applies: an 8 MiB buffer with no match at all is
144
+ rejected in 2.5 ms. That gives the fast path for clean or binary data.
145
+
146
+ The analyser only emits a literal when it can *prove* it is mandatory; otherwise the rule falls
147
+ back to a full scan. `tests/test_prefilter.py` asserts, for every built-in rule, that the prefilter
148
+ never rejects an input the regex would have matched, and that anchor windows always contain the
149
+ real match offset.
150
+
151
+ </details>
152
+
153
+ ---
154
+
155
+ ## Install
156
+
157
+ ```bash
158
+ pip install logspecter
159
+ ```
160
+
161
+ From source:
162
+
163
+ ```bash
164
+ git clone https://github.com/logspecter/logspecter
165
+ cd logspecter
166
+ pip install -e ".[dev]"
167
+ ```
168
+
169
+ Requires Python 3.10+. Runtime dependencies: `typer`, `rich`, `PyYAML`, `orjson`.
170
+
171
+ ## Usage
172
+
173
+ ```bash
174
+ # a file, a directory, a compressed archive
175
+ logspecter scan /var/log/app.log
176
+ logspecter scan /var/log/ --recursive
177
+ logspecter scan cloudtrail-2026-08-30.json.gz
178
+
179
+ # a pipe
180
+ kubectl logs deploy/api --since=1h | logspecter scan -
181
+ aws logs tail /aws/lambda/api --format short | logspecter scan -
182
+
183
+ # CI gate: fail only on new critical leaks
184
+ logspecter scan ./logs --baseline .logspecter-baseline.json --fail-on critical
185
+
186
+ # machine-readable output
187
+ logspecter scan ./logs -f json -o findings.json
188
+ logspecter scan ./logs -f csv -o soc2-evidence.csv
189
+ logspecter scan ./logs -f sarif -o results.sarif # GitHub code scanning
190
+ ```
191
+
192
+ Exit codes: `0` clean, `1` findings at or above `--fail-on` (default `high`), `2` bad input.
193
+
194
+ ### Options worth knowing
195
+
196
+ | Flag | Effect |
197
+ | --- | --- |
198
+ | `-j, --workers N` | processes; default `min(8, cpu)`, `1` disables multiprocessing |
199
+ | `--chunk-size 4MB` | the memory knob — resident data ≈ 2 × chunk × workers |
200
+ | `--min-entropy 4.5` | raise the global entropy floor (precision over recall) |
201
+ | `--min-confidence 0.8` | drop low-confidence findings |
202
+ | `--aggressive` | enable noisy entropy-only rules (recall over precision) |
203
+ | `--pack aws --tag github` | narrow the rule set |
204
+ | `--no-structured` | skip JSON parsing entirely; fastest, loses cloud context |
205
+ | `--show-secrets` | print plaintext (off by default — reports are redacted) |
206
+ | `--stats` | throughput, memory, and the full noise-reduction breakdown |
207
+
208
+ ### Other commands
209
+
210
+ ```bash
211
+ logspecter rules list # 64 built-in rules across 7 packs
212
+ logspecter rules show aws-secret-access-key # pattern, entropy gate, prefilter
213
+ logspecter rules validate ./my-rules.yaml # lint custom rules
214
+ logspecter selftest # 64 positive + 25 negative samples
215
+ logspecter benchmark --size 1GB -j 8 # throughput and memory on your box
216
+ ```
217
+
218
+ ## Custom rules
219
+
220
+ Rules are plain YAML. A rule with the same `id` as a built-in one overrides it, which is the
221
+ recommended way to retune thresholds for your environment.
222
+
223
+ ```yaml
224
+ version: 1
225
+ pack: acme
226
+
227
+ rules:
228
+ - id: acme-internal-token
229
+ name: ACME Internal Service Token
230
+ severity: critical
231
+ confidence: high
232
+ pattern: '\bacme_(?:live|prod)_([A-Za-z0-9]{40})\b'
233
+ capture: 1
234
+ tags: [acme, internal]
235
+ entropy:
236
+ min_entropy: 4.4
237
+ min_normalized: 0.72 # entropy ÷ log2(charset size)
238
+ min_length: 40
239
+ min_charset_coverage: 0.6 # unique chars ÷ achievable unique chars
240
+ reject_encoded_text: true
241
+
242
+ - id: acme-mdc-secret
243
+ name: Secret in ACME MDC field
244
+ severity: high
245
+ pattern: '\A\s*(\S{12,4096})\s*\Z'
246
+ capture: 1
247
+ json_keys: [acme_token, acme_signature] # only applied to these JSON keys
248
+ entropy:
249
+ min_entropy: 3.5
250
+ ```
251
+
252
+ ```bash
253
+ logspecter rules validate acme.yaml
254
+ logspecter scan ./logs --rules acme.yaml
255
+ ```
256
+
257
+ Full field reference: [`docs/rules.md`](docs/rules.md).
258
+
259
+ ## Library use
260
+
261
+ ```python
262
+ from logspecter import engine
263
+ from logspecter.rules import load_ruleset
264
+ from logspecter.scanner import ScanOptions
265
+
266
+ config = engine.ScanConfig(ruleset=load_ruleset(), options=ScanOptions())
267
+ result = engine.scan(["/var/log/app.log"], config, workers=4)
268
+
269
+ for group in result.groups:
270
+ f = group.representative
271
+ print(f.severity.value, f.rule_id, f.context_summary(), f"×{group.occurrences}")
272
+
273
+ print(result.stats.throughput_mb_s, result.stats.peak_rss_max_process)
274
+ ```
275
+
276
+ ## Accuracy
277
+
278
+ `logspecter selftest` runs the bundled corpus with **every** rule enabled:
279
+
280
+ ```
281
+ 检出率 64/64 · 负样本零误报 25/25
282
+ ```
283
+
284
+ 64 positive samples (one per rule, generated from a fixed seed — no real credentials in the repo)
285
+ and 25 negative samples drawn from the shapes that actually fool regex-only scanners: UUID request
286
+ IDs, git SHAs, base64-encoded JSON cursors, camel-case class names, template placeholders,
287
+ `AKIAIOSFODNN7EXAMPLE`, ISO timestamps, CSS colours, service-account token paths, and unkeyed
288
+ SHA-256 digests. Each of these is a distinct rejection reason in the entropy layer, and each is a
289
+ regression test.
290
+
291
+ `--stats` reports the funnel on your own data, so the numbers are yours rather than ours:
292
+
293
+ ```
294
+ 降噪 正则候选 1,245 → 熵值/上下文层拦下 16 条(1.3%)
295
+ ```
296
+
297
+ ## Design notes
298
+
299
+ ```
300
+ logspecter/
301
+ ├── ingest.py byte-range planning, mmap window reads, gz/bz2/xz/stdin streaming
302
+ ├── engine.py chunk scheduling, bounded-window multiprocessing, line-number prefix sums,
303
+ │ fingerprint aggregation
304
+ ├── prefilter.py regex AST → mandatory literals + prefix widths, trie merging, screen tree
305
+ ├── scanner.py the detection pipeline
306
+ ├── entropy.py Shannon entropy and the heuristic gate
307
+ ├── rules.py YAML loading, validation, bytes compilation
308
+ ├── cloud.py cloud log schema detection and context extraction
309
+ ├── structured.py orjson parsing and JSON flattening
310
+ ├── report/ Rich console, JSON, CSV, SARIF
311
+ └── rules/*.yaml built-in rule packs
312
+ ```
313
+
314
+ Two details that are easy to get wrong and are worth knowing about:
315
+
316
+ **Line numbers under multiprocessing.** Workers only know their offset in the file, so they report
317
+ a chunk-local line number plus that chunk's total line count. The parent computes a prefix sum
318
+ over chunk line counts and rewrites the findings. No pre-pass over the file, exact `file:line`.
319
+
320
+ **Report readability.** One leaked key repeated 50 000 times is one finding, not 50 000 rows.
321
+ Findings are aggregated by `SHA-256(rule_id ‖ secret)[:16]` with an occurrence count and a few
322
+ sample locations. Overlapping rules on the same value collapse to the most specific one
323
+ (`openai-api-key` beats `authorization-header-bearer` beats `sensitive-json-key-value`), with the
324
+ others preserved in the evidence chain.
325
+
326
+ ## Security
327
+
328
+ Reports are redacted by default: masked value plus real length, never plaintext, unless you pass
329
+ `--show-secrets`. Baseline files store only fingerprints. The scanner makes no network calls.
330
+
331
+ If you find a vulnerability, please open a private security advisory rather than a public issue.
332
+
333
+ ## Contributing
334
+
335
+ ```bash
336
+ pip install -e ".[dev]"
337
+ pytest # 360 tests
338
+ ruff check .
339
+ logspecter selftest
340
+ ```
341
+
342
+ New rules need a positive sample in `src/logspecter/samples.py`; the test suite fails if any rule
343
+ lacks one, and `tests/test_prefilter.py` will tell you if your pattern defeats the prefilter.
344
+
345
+ Chinese documentation: [README.zh-CN.md](README.zh-CN.md).
346
+
347
+ ## License
348
+
349
+ Apache-2.0.