llm-keyguard 0.2.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.
- llm_keyguard-0.2.0/LICENSE +21 -0
- llm_keyguard-0.2.0/PKG-INFO +143 -0
- llm_keyguard-0.2.0/README.md +109 -0
- llm_keyguard-0.2.0/pyproject.toml +59 -0
- llm_keyguard-0.2.0/setup.cfg +4 -0
- llm_keyguard-0.2.0/src/llm_keyguard/__init__.py +39 -0
- llm_keyguard-0.2.0/src/llm_keyguard/cli.py +136 -0
- llm_keyguard-0.2.0/src/llm_keyguard/py.typed +1 -0
- llm_keyguard-0.2.0/src/llm_keyguard/remediator.py +95 -0
- llm_keyguard-0.2.0/src/llm_keyguard/sarif.py +86 -0
- llm_keyguard-0.2.0/src/llm_keyguard/scanner.py +341 -0
- llm_keyguard-0.2.0/src/llm_keyguard/signatures.py +230 -0
- llm_keyguard-0.2.0/src/llm_keyguard.egg-info/PKG-INFO +143 -0
- llm_keyguard-0.2.0/src/llm_keyguard.egg-info/SOURCES.txt +17 -0
- llm_keyguard-0.2.0/src/llm_keyguard.egg-info/dependency_links.txt +1 -0
- llm_keyguard-0.2.0/src/llm_keyguard.egg-info/entry_points.txt +2 -0
- llm_keyguard-0.2.0/src/llm_keyguard.egg-info/requires.txt +5 -0
- llm_keyguard-0.2.0/src/llm_keyguard.egg-info/top_level.txt +1 -0
- llm_keyguard-0.2.0/tests/test_llm_keyguard.py +165 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 llm-keyguard contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: llm-keyguard
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Zero-dependency secret scanner, MCP config auditor, and Git pre-commit guard for LLM & AI API keys.
|
|
5
|
+
License: MIT
|
|
6
|
+
Project-URL: Homepage, https://github.com/Edimilson22/llm-keyguard
|
|
7
|
+
Project-URL: Repository, https://github.com/Edimilson22/llm-keyguard
|
|
8
|
+
Project-URL: Issues, https://github.com/Edimilson22/llm-keyguard/issues
|
|
9
|
+
Project-URL: Changelog, https://github.com/Edimilson22/llm-keyguard/blob/main/CHANGELOG.md
|
|
10
|
+
Keywords: security,secrets,pre-commit,llm,openai,anthropic,mcp,api-keys,sarif,devsecops
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Operating System :: OS Independent
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
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 :: Software Development :: Quality Assurance
|
|
24
|
+
Classifier: Topic :: Software Development :: Version Control :: Git
|
|
25
|
+
Classifier: Typing :: Typed
|
|
26
|
+
Requires-Python: >=3.9
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Provides-Extra: dev
|
|
30
|
+
Requires-Dist: pytest>=8.0; extra == "dev"
|
|
31
|
+
Requires-Dist: build>=1.0; extra == "dev"
|
|
32
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
33
|
+
Dynamic: license-file
|
|
34
|
+
|
|
35
|
+
# llm-keyguard
|
|
36
|
+
|
|
37
|
+
**Zero-dependency secret scanner, MCP configuration auditor, and `<35ms` Git pre-commit guard for LLM & AI API keys.**
|
|
38
|
+
|
|
39
|
+
Modern AI engineering introduces new credential leak vectors beyond traditional web apps: developers frequently commit `.mcp.json`, `.cursor/mcp.json`, Jupyter notebooks, and agent configuration files containing live keys for OpenAI, Anthropic, Gemini, Groq, OpenRouter, Pinecone, LangSmith, HuggingFace, and ElevenLabs.
|
|
40
|
+
|
|
41
|
+
`llm-keyguard` is a pure-Python, zero-dependency CLI and library designed to stop AI credential leaks before they enter Git history—without requiring external Go binaries or Docker containers.
|
|
42
|
+
|
|
43
|
+
---
|
|
44
|
+
|
|
45
|
+
## Features
|
|
46
|
+
|
|
47
|
+
- **20+ AI, Vector DB & Cloud Signatures + Shannon Entropy Filtering:** Detects OpenAI (`sk-proj-`, `sk-svcacct-`, `sk-admin-`), Anthropic (`sk-ant-`), Google Gemini (`AIzaSy`), Groq (`gsk_`), OpenRouter (`sk-or-v1-`), HuggingFace (`hf_`), Replicate (`r8_`), Perplexity (`pplx-`), Fireworks (`fw_`), Tavily (`tvly-`), Pinecone (`pcsk_`), LangSmith (`lsv2_`), ElevenLabs, Supabase, GitHub PATs, AWS IAM, Stripe Live, Slack, and PEM private keys while ignoring low-entropy placeholders.
|
|
48
|
+
- **Dedicated MCP Config Auditor (`audit-mcp`):** Parses `mcp.json`, `.mcp.json`, `.cursor/mcp.json`, and `claude_desktop_config.json` to pinpoint exact JSON paths (e.g. `mcpServers.search.env.OPENAI_API_KEY`) containing literal credentials instead of environment references.
|
|
49
|
+
- **One-Command Repository Hardening (`init`):** Automatically hardens `.gitignore` (blocking `.env` and key files while allowing `.env.example`) and installs a fast native Git `pre-commit` hook.
|
|
50
|
+
- **Safe `.env.example` Generator (`env-example`):** Generates sanitized `.env.example` templates from local `.env` files without exposing real credentials.
|
|
51
|
+
- **OASIS SARIF v2.1.0 Export (`--format sarif`):** Integrates directly with GitHub Code Scanning and CI pipelines.
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## Quickstart
|
|
56
|
+
|
|
57
|
+
```bash
|
|
58
|
+
pip install llm-keyguard
|
|
59
|
+
|
|
60
|
+
# 1. Harden .gitignore and install the Git pre-commit guard
|
|
61
|
+
llm-keyguard init
|
|
62
|
+
|
|
63
|
+
# 2. Scan your project directory (including MCP configs)
|
|
64
|
+
llm-keyguard scan .
|
|
65
|
+
|
|
66
|
+
# 3. Audit MCP configuration files specifically
|
|
67
|
+
llm-keyguard audit-mcp .
|
|
68
|
+
|
|
69
|
+
# 4. Generate a safe .env.example from your local .env
|
|
70
|
+
llm-keyguard env-example --source .env --output .env.example
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
---
|
|
74
|
+
|
|
75
|
+
## Using with `pre-commit`
|
|
76
|
+
|
|
77
|
+
Add `llm-keyguard` to your `.pre-commit-config.yaml`:
|
|
78
|
+
|
|
79
|
+
```yaml
|
|
80
|
+
repos:
|
|
81
|
+
- repo: https://github.com/Edimilson22/llm-keyguard
|
|
82
|
+
rev: v0.2.0
|
|
83
|
+
hooks:
|
|
84
|
+
- id: llm-keyguard
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
---
|
|
88
|
+
|
|
89
|
+
## GitHub Actions & Code Scanning (SARIF)
|
|
90
|
+
|
|
91
|
+
```yaml
|
|
92
|
+
name: AI Credential Scan
|
|
93
|
+
on: [push, pull_request]
|
|
94
|
+
|
|
95
|
+
jobs:
|
|
96
|
+
keyguard:
|
|
97
|
+
runs-on: ubuntu-latest
|
|
98
|
+
permissions:
|
|
99
|
+
security-events: write
|
|
100
|
+
contents: read
|
|
101
|
+
steps:
|
|
102
|
+
- uses: actions/checkout@v4
|
|
103
|
+
- uses: actions/setup-python@v5
|
|
104
|
+
with:
|
|
105
|
+
python-version: "3.12"
|
|
106
|
+
- run: pip install llm-keyguard
|
|
107
|
+
- run: llm-keyguard scan . --format sarif > results.sarif || true
|
|
108
|
+
- uses: github/codeql-action/upload-sarif@v3
|
|
109
|
+
with:
|
|
110
|
+
sarif_file: results.sarif
|
|
111
|
+
```
|
|
112
|
+
|
|
113
|
+
---
|
|
114
|
+
|
|
115
|
+
## Python API
|
|
116
|
+
|
|
117
|
+
```python
|
|
118
|
+
from pathlib import Path
|
|
119
|
+
from llm_keyguard import scan_path, audit_mcp_configs, build_sarif_report
|
|
120
|
+
|
|
121
|
+
findings = scan_path(Path("."))
|
|
122
|
+
for item in findings:
|
|
123
|
+
print(f"[{item.rule_id}] {item.file}:{item.line} -> {item.provider} ({item.masked})")
|
|
124
|
+
|
|
125
|
+
mcp_issues = audit_mcp_configs(Path("."))
|
|
126
|
+
sarif_payload = build_sarif_report(findings)
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
---
|
|
130
|
+
|
|
131
|
+
## Inline Suppression
|
|
132
|
+
|
|
133
|
+
For intentional synthetic test fixtures, append `# keyguard: ignore` (or `# pragma: allowlist secret`) to the line:
|
|
134
|
+
|
|
135
|
+
```python
|
|
136
|
+
TEST_FIXTURE = "sk-proj-..." # keyguard: ignore
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
---
|
|
140
|
+
|
|
141
|
+
## License
|
|
142
|
+
|
|
143
|
+
MIT License. See [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# llm-keyguard
|
|
2
|
+
|
|
3
|
+
**Zero-dependency secret scanner, MCP configuration auditor, and `<35ms` Git pre-commit guard for LLM & AI API keys.**
|
|
4
|
+
|
|
5
|
+
Modern AI engineering introduces new credential leak vectors beyond traditional web apps: developers frequently commit `.mcp.json`, `.cursor/mcp.json`, Jupyter notebooks, and agent configuration files containing live keys for OpenAI, Anthropic, Gemini, Groq, OpenRouter, Pinecone, LangSmith, HuggingFace, and ElevenLabs.
|
|
6
|
+
|
|
7
|
+
`llm-keyguard` is a pure-Python, zero-dependency CLI and library designed to stop AI credential leaks before they enter Git history—without requiring external Go binaries or Docker containers.
|
|
8
|
+
|
|
9
|
+
---
|
|
10
|
+
|
|
11
|
+
## Features
|
|
12
|
+
|
|
13
|
+
- **20+ AI, Vector DB & Cloud Signatures + Shannon Entropy Filtering:** Detects OpenAI (`sk-proj-`, `sk-svcacct-`, `sk-admin-`), Anthropic (`sk-ant-`), Google Gemini (`AIzaSy`), Groq (`gsk_`), OpenRouter (`sk-or-v1-`), HuggingFace (`hf_`), Replicate (`r8_`), Perplexity (`pplx-`), Fireworks (`fw_`), Tavily (`tvly-`), Pinecone (`pcsk_`), LangSmith (`lsv2_`), ElevenLabs, Supabase, GitHub PATs, AWS IAM, Stripe Live, Slack, and PEM private keys while ignoring low-entropy placeholders.
|
|
14
|
+
- **Dedicated MCP Config Auditor (`audit-mcp`):** Parses `mcp.json`, `.mcp.json`, `.cursor/mcp.json`, and `claude_desktop_config.json` to pinpoint exact JSON paths (e.g. `mcpServers.search.env.OPENAI_API_KEY`) containing literal credentials instead of environment references.
|
|
15
|
+
- **One-Command Repository Hardening (`init`):** Automatically hardens `.gitignore` (blocking `.env` and key files while allowing `.env.example`) and installs a fast native Git `pre-commit` hook.
|
|
16
|
+
- **Safe `.env.example` Generator (`env-example`):** Generates sanitized `.env.example` templates from local `.env` files without exposing real credentials.
|
|
17
|
+
- **OASIS SARIF v2.1.0 Export (`--format sarif`):** Integrates directly with GitHub Code Scanning and CI pipelines.
|
|
18
|
+
|
|
19
|
+
---
|
|
20
|
+
|
|
21
|
+
## Quickstart
|
|
22
|
+
|
|
23
|
+
```bash
|
|
24
|
+
pip install llm-keyguard
|
|
25
|
+
|
|
26
|
+
# 1. Harden .gitignore and install the Git pre-commit guard
|
|
27
|
+
llm-keyguard init
|
|
28
|
+
|
|
29
|
+
# 2. Scan your project directory (including MCP configs)
|
|
30
|
+
llm-keyguard scan .
|
|
31
|
+
|
|
32
|
+
# 3. Audit MCP configuration files specifically
|
|
33
|
+
llm-keyguard audit-mcp .
|
|
34
|
+
|
|
35
|
+
# 4. Generate a safe .env.example from your local .env
|
|
36
|
+
llm-keyguard env-example --source .env --output .env.example
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Using with `pre-commit`
|
|
42
|
+
|
|
43
|
+
Add `llm-keyguard` to your `.pre-commit-config.yaml`:
|
|
44
|
+
|
|
45
|
+
```yaml
|
|
46
|
+
repos:
|
|
47
|
+
- repo: https://github.com/Edimilson22/llm-keyguard
|
|
48
|
+
rev: v0.2.0
|
|
49
|
+
hooks:
|
|
50
|
+
- id: llm-keyguard
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
---
|
|
54
|
+
|
|
55
|
+
## GitHub Actions & Code Scanning (SARIF)
|
|
56
|
+
|
|
57
|
+
```yaml
|
|
58
|
+
name: AI Credential Scan
|
|
59
|
+
on: [push, pull_request]
|
|
60
|
+
|
|
61
|
+
jobs:
|
|
62
|
+
keyguard:
|
|
63
|
+
runs-on: ubuntu-latest
|
|
64
|
+
permissions:
|
|
65
|
+
security-events: write
|
|
66
|
+
contents: read
|
|
67
|
+
steps:
|
|
68
|
+
- uses: actions/checkout@v4
|
|
69
|
+
- uses: actions/setup-python@v5
|
|
70
|
+
with:
|
|
71
|
+
python-version: "3.12"
|
|
72
|
+
- run: pip install llm-keyguard
|
|
73
|
+
- run: llm-keyguard scan . --format sarif > results.sarif || true
|
|
74
|
+
- uses: github/codeql-action/upload-sarif@v3
|
|
75
|
+
with:
|
|
76
|
+
sarif_file: results.sarif
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
81
|
+
## Python API
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
from pathlib import Path
|
|
85
|
+
from llm_keyguard import scan_path, audit_mcp_configs, build_sarif_report
|
|
86
|
+
|
|
87
|
+
findings = scan_path(Path("."))
|
|
88
|
+
for item in findings:
|
|
89
|
+
print(f"[{item.rule_id}] {item.file}:{item.line} -> {item.provider} ({item.masked})")
|
|
90
|
+
|
|
91
|
+
mcp_issues = audit_mcp_configs(Path("."))
|
|
92
|
+
sarif_payload = build_sarif_report(findings)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
---
|
|
96
|
+
|
|
97
|
+
## Inline Suppression
|
|
98
|
+
|
|
99
|
+
For intentional synthetic test fixtures, append `# keyguard: ignore` (or `# pragma: allowlist secret`) to the line:
|
|
100
|
+
|
|
101
|
+
```python
|
|
102
|
+
TEST_FIXTURE = "sk-proj-..." # keyguard: ignore
|
|
103
|
+
```
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
## License
|
|
108
|
+
|
|
109
|
+
MIT License. See [LICENSE](LICENSE) for details.
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "llm-keyguard"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
description = "Zero-dependency secret scanner, MCP config auditor, and Git pre-commit guard for LLM & AI API keys."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = { text = "MIT" }
|
|
11
|
+
requires-python = ">=3.9"
|
|
12
|
+
keywords = [
|
|
13
|
+
"security",
|
|
14
|
+
"secrets",
|
|
15
|
+
"pre-commit",
|
|
16
|
+
"llm",
|
|
17
|
+
"openai",
|
|
18
|
+
"anthropic",
|
|
19
|
+
"mcp",
|
|
20
|
+
"api-keys",
|
|
21
|
+
"sarif",
|
|
22
|
+
"devsecops",
|
|
23
|
+
]
|
|
24
|
+
classifiers = [
|
|
25
|
+
"Development Status :: 4 - Beta",
|
|
26
|
+
"Environment :: Console",
|
|
27
|
+
"Intended Audience :: Developers",
|
|
28
|
+
"License :: OSI Approved :: MIT License",
|
|
29
|
+
"Operating System :: OS Independent",
|
|
30
|
+
"Programming Language :: Python :: 3",
|
|
31
|
+
"Programming Language :: Python :: 3.9",
|
|
32
|
+
"Programming Language :: Python :: 3.10",
|
|
33
|
+
"Programming Language :: Python :: 3.11",
|
|
34
|
+
"Programming Language :: Python :: 3.12",
|
|
35
|
+
"Programming Language :: Python :: 3.13",
|
|
36
|
+
"Topic :: Security",
|
|
37
|
+
"Topic :: Software Development :: Quality Assurance",
|
|
38
|
+
"Topic :: Software Development :: Version Control :: Git",
|
|
39
|
+
"Typing :: Typed",
|
|
40
|
+
]
|
|
41
|
+
dependencies = []
|
|
42
|
+
|
|
43
|
+
[project.urls]
|
|
44
|
+
Homepage = "https://github.com/Edimilson22/llm-keyguard"
|
|
45
|
+
Repository = "https://github.com/Edimilson22/llm-keyguard"
|
|
46
|
+
Issues = "https://github.com/Edimilson22/llm-keyguard/issues"
|
|
47
|
+
Changelog = "https://github.com/Edimilson22/llm-keyguard/blob/main/CHANGELOG.md"
|
|
48
|
+
|
|
49
|
+
[project.optional-dependencies]
|
|
50
|
+
dev = ["pytest>=8.0", "build>=1.0", "twine>=5.0"]
|
|
51
|
+
|
|
52
|
+
[project.scripts]
|
|
53
|
+
llm-keyguard = "llm_keyguard.cli:main"
|
|
54
|
+
|
|
55
|
+
[tool.setuptools.packages.find]
|
|
56
|
+
where = ["src"]
|
|
57
|
+
|
|
58
|
+
[tool.setuptools.package-data]
|
|
59
|
+
llm_keyguard = ["py.typed"]
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Public Python API for llm-keyguard."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from .remediator import generate_env_example, harden_gitignore, install_pre_commit_hook
|
|
6
|
+
from .sarif import build_sarif_report
|
|
7
|
+
from .scanner import (
|
|
8
|
+
Finding,
|
|
9
|
+
audit_mcp_configs,
|
|
10
|
+
audit_mcp_file,
|
|
11
|
+
scan_file,
|
|
12
|
+
scan_git_history,
|
|
13
|
+
scan_git_staged,
|
|
14
|
+
scan_path,
|
|
15
|
+
scan_text,
|
|
16
|
+
)
|
|
17
|
+
from .signatures import RULES, SecretRule, mask_secret, shannon_entropy
|
|
18
|
+
|
|
19
|
+
__version__ = "0.2.0"
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"__version__",
|
|
23
|
+
"Finding",
|
|
24
|
+
"RULES",
|
|
25
|
+
"SecretRule",
|
|
26
|
+
"audit_mcp_configs",
|
|
27
|
+
"audit_mcp_file",
|
|
28
|
+
"build_sarif_report",
|
|
29
|
+
"generate_env_example",
|
|
30
|
+
"harden_gitignore",
|
|
31
|
+
"install_pre_commit_hook",
|
|
32
|
+
"mask_secret",
|
|
33
|
+
"scan_file",
|
|
34
|
+
"scan_git_history",
|
|
35
|
+
"scan_git_staged",
|
|
36
|
+
"scan_path",
|
|
37
|
+
"scan_text",
|
|
38
|
+
"shannon_entropy",
|
|
39
|
+
]
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
"""Command-line interface for llm-keyguard."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import argparse
|
|
6
|
+
import json
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import List, Optional, Sequence
|
|
10
|
+
|
|
11
|
+
from . import __version__
|
|
12
|
+
from .remediator import generate_env_example, harden_gitignore, install_pre_commit_hook
|
|
13
|
+
from .sarif import build_sarif_report
|
|
14
|
+
from .scanner import (
|
|
15
|
+
Finding,
|
|
16
|
+
audit_mcp_configs,
|
|
17
|
+
scan_git_history,
|
|
18
|
+
scan_git_staged,
|
|
19
|
+
scan_path,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def _emit_findings(findings: Sequence[Finding], fmt: str) -> None:
|
|
24
|
+
if fmt == "json":
|
|
25
|
+
payload = {
|
|
26
|
+
"version": __version__,
|
|
27
|
+
"count": len(findings),
|
|
28
|
+
"findings": [f.to_dict() for f in findings],
|
|
29
|
+
}
|
|
30
|
+
print(json.dumps(payload, indent=2))
|
|
31
|
+
return
|
|
32
|
+
if fmt == "sarif":
|
|
33
|
+
print(json.dumps(build_sarif_report(findings, version=__version__), indent=2))
|
|
34
|
+
return
|
|
35
|
+
|
|
36
|
+
if not findings:
|
|
37
|
+
print("llm-keyguard: OK (0 exposed credentials found)")
|
|
38
|
+
return
|
|
39
|
+
|
|
40
|
+
print(f"llm-keyguard: BLOCKED ({len(findings)} credential issue(s) detected)", file=sys.stderr)
|
|
41
|
+
for item in findings:
|
|
42
|
+
ctx = f" [{item.context_path}]" if item.context_path else ""
|
|
43
|
+
print(
|
|
44
|
+
f" [{item.rule_id}] {item.file}:{item.line}:{item.column}{ctx} -> "
|
|
45
|
+
f"{item.provider}: {item.masked}",
|
|
46
|
+
file=sys.stderr,
|
|
47
|
+
)
|
|
48
|
+
print(f" Fix: {item.remediation}", file=sys.stderr)
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def build_parser() -> argparse.ArgumentParser:
|
|
52
|
+
parser = argparse.ArgumentParser(
|
|
53
|
+
prog="llm-keyguard",
|
|
54
|
+
description="Zero-dependency secret scanner, MCP config auditor, and Git pre-commit guard for LLM & AI API keys.",
|
|
55
|
+
)
|
|
56
|
+
parser.add_argument("--version", action="version", version=f"%(prog)s {__version__}")
|
|
57
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
58
|
+
|
|
59
|
+
p_scan = sub.add_parser("scan", help="Scan a directory or file for hardcoded API keys and MCP leaks")
|
|
60
|
+
p_scan.add_argument("target", nargs="?", default=".", help="Directory or file to scan (default: .)")
|
|
61
|
+
p_scan.add_argument("--include-dotenv", action="store_true", help="Also scan local .env files")
|
|
62
|
+
p_scan.add_argument("--format", choices=("text", "json", "sarif"), default="text", help="Output format")
|
|
63
|
+
|
|
64
|
+
p_staged = sub.add_parser("staged", help="Scan staged Git changes (for pre-commit hooks)")
|
|
65
|
+
p_staged.add_argument("--repo", default=".", help="Git repository root (default: .)")
|
|
66
|
+
p_staged.add_argument("--format", choices=("text", "json", "sarif"), default="text", help="Output format")
|
|
67
|
+
|
|
68
|
+
p_hist = sub.add_parser("history", help="Scan recent Git commit patches for leaked credentials")
|
|
69
|
+
p_hist.add_argument("--repo", default=".", help="Git repository root (default: .)")
|
|
70
|
+
p_hist.add_argument("-n", "--max-commits", type=int, default=50, help="Commits to inspect (default: 50)")
|
|
71
|
+
p_hist.add_argument("--format", choices=("text", "json", "sarif"), default="text", help="Output format")
|
|
72
|
+
|
|
73
|
+
p_mcp = sub.add_parser("audit-mcp", help="Audit MCP configuration files for hardcoded credentials")
|
|
74
|
+
p_mcp.add_argument("target", nargs="?", default=".", help="Directory or MCP file to inspect")
|
|
75
|
+
p_mcp.add_argument("--format", choices=("text", "json", "sarif"), default="text", help="Output format")
|
|
76
|
+
|
|
77
|
+
p_init = sub.add_parser("init", help="Harden .gitignore and install Git pre-commit hook")
|
|
78
|
+
p_init.add_argument("--repo", default=".", help="Target repository directory (default: .)")
|
|
79
|
+
p_init.add_argument("--no-hook", action="store_true", help="Only update .gitignore without installing hook")
|
|
80
|
+
|
|
81
|
+
p_env = sub.add_parser("env-example", help="Generate a safe .env.example from a local .env file")
|
|
82
|
+
p_env.add_argument("--source", default=".env", help="Source .env file (default: .env)")
|
|
83
|
+
p_env.add_argument("--output", default=".env.example", help="Destination template file (default: .env.example)")
|
|
84
|
+
|
|
85
|
+
return parser
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def main(argv: Optional[Sequence[str]] = None) -> int:
|
|
89
|
+
parser = build_parser()
|
|
90
|
+
args = parser.parse_args(argv)
|
|
91
|
+
|
|
92
|
+
if args.command == "scan":
|
|
93
|
+
findings = scan_path(Path(args.target), include_dotenv=args.include_dotenv)
|
|
94
|
+
_emit_findings(findings, args.format)
|
|
95
|
+
return 1 if findings else 0
|
|
96
|
+
|
|
97
|
+
if args.command == "staged":
|
|
98
|
+
findings = scan_git_staged(Path(args.repo))
|
|
99
|
+
_emit_findings(findings, args.format)
|
|
100
|
+
return 1 if findings else 0
|
|
101
|
+
|
|
102
|
+
if args.command == "history":
|
|
103
|
+
findings = scan_git_history(Path(args.repo), max_commits=args.max_commits)
|
|
104
|
+
_emit_findings(findings, args.format)
|
|
105
|
+
return 1 if findings else 0
|
|
106
|
+
|
|
107
|
+
if args.command == "audit-mcp":
|
|
108
|
+
findings = audit_mcp_configs(Path(args.target))
|
|
109
|
+
_emit_findings(findings, args.format)
|
|
110
|
+
return 1 if findings else 0
|
|
111
|
+
|
|
112
|
+
if args.command == "init":
|
|
113
|
+
repo = Path(args.repo).resolve()
|
|
114
|
+
added = harden_gitignore(repo)
|
|
115
|
+
if added:
|
|
116
|
+
print(f"llm-keyguard: added {len(added)} secret-protection rule(s) to {repo / '.gitignore'}")
|
|
117
|
+
else:
|
|
118
|
+
print(f"llm-keyguard: {repo / '.gitignore'} already hardened")
|
|
119
|
+
if not args.no_hook:
|
|
120
|
+
try:
|
|
121
|
+
hook_path = install_pre_commit_hook(repo)
|
|
122
|
+
print(f"llm-keyguard: installed Git pre-commit hook at {hook_path}")
|
|
123
|
+
except FileNotFoundError as exc:
|
|
124
|
+
print(f"llm-keyguard: skipped hook installation ({exc})", file=sys.stderr)
|
|
125
|
+
return 0
|
|
126
|
+
|
|
127
|
+
if args.command == "env-example":
|
|
128
|
+
mapping = generate_env_example(Path(args.source), Path(args.output))
|
|
129
|
+
print(f"llm-keyguard: generated {args.output} with {len(mapping)} sanitized variable(s)")
|
|
130
|
+
return 0
|
|
131
|
+
|
|
132
|
+
return 0
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
if __name__ == "__main__":
|
|
136
|
+
sys.exit(main())
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# PEP 561 marker
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
"""Repository remediation utilities (.gitignore hardening, .env.example, and Git hooks)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
import stat
|
|
7
|
+
import sys
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Dict, List
|
|
10
|
+
|
|
11
|
+
GITIGNORE_ENTRIES: List[str] = [
|
|
12
|
+
".env",
|
|
13
|
+
".env.*",
|
|
14
|
+
"!.env.example",
|
|
15
|
+
"!.env.sample",
|
|
16
|
+
"!.env.template",
|
|
17
|
+
"*.pem",
|
|
18
|
+
"*.key",
|
|
19
|
+
"*credentials*.json",
|
|
20
|
+
"*client_secret*.json",
|
|
21
|
+
]
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def harden_gitignore(repo_dir: Path) -> List[str]:
|
|
25
|
+
"""Ensure .gitignore protects .env and secret key files while allowing .env.example."""
|
|
26
|
+
gitignore_path = repo_dir / ".gitignore"
|
|
27
|
+
existing = gitignore_path.read_text(encoding="utf-8", errors="ignore") if gitignore_path.exists() else ""
|
|
28
|
+
present = {ln.strip() for ln in existing.splitlines() if ln.strip()}
|
|
29
|
+
missing = [rule for rule in GITIGNORE_ENTRIES if rule not in present]
|
|
30
|
+
if not missing:
|
|
31
|
+
return []
|
|
32
|
+
|
|
33
|
+
header = "# llm-keyguard secret protection"
|
|
34
|
+
block = "\n".join([header] + missing) + "\n"
|
|
35
|
+
updated = f"{existing.rstrip()}\n\n{block}" if existing.strip() else block
|
|
36
|
+
gitignore_path.write_text(updated, encoding="utf-8")
|
|
37
|
+
return missing
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def install_pre_commit_hook(repo_dir: Path) -> Path:
|
|
41
|
+
"""Install a lightweight Git pre-commit hook invoking `llm-keyguard staged`."""
|
|
42
|
+
hooks_dir = repo_dir / ".git" / "hooks"
|
|
43
|
+
if not hooks_dir.is_dir():
|
|
44
|
+
raise FileNotFoundError(f"No .git/hooks directory found under {repo_dir}")
|
|
45
|
+
|
|
46
|
+
hook_path = hooks_dir / "pre-commit"
|
|
47
|
+
py_exe = Path(sys.executable).as_posix()
|
|
48
|
+
script = (
|
|
49
|
+
"#!/bin/sh\n"
|
|
50
|
+
"# Installed by llm-keyguard\n"
|
|
51
|
+
f'"{py_exe}" -m llm_keyguard.cli staged\n'
|
|
52
|
+
"exit $?\n"
|
|
53
|
+
)
|
|
54
|
+
hook_path.write_text(script, encoding="utf-8", newline="\n")
|
|
55
|
+
try:
|
|
56
|
+
mode = hook_path.stat().st_mode
|
|
57
|
+
hook_path.chmod(mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
|
|
58
|
+
except OSError:
|
|
59
|
+
pass
|
|
60
|
+
return hook_path
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def generate_env_example(dotenv_path: Path, output_path: Path) -> Dict[str, str]:
|
|
64
|
+
"""Create a sanitized .env.example from a local .env file without exposing secret values."""
|
|
65
|
+
if not dotenv_path.is_file():
|
|
66
|
+
raise FileNotFoundError(f"Source .env file not found: {dotenv_path}")
|
|
67
|
+
|
|
68
|
+
out_lines: List[str] = []
|
|
69
|
+
sanitized_map: Dict[str, str] = {}
|
|
70
|
+
|
|
71
|
+
for raw_line in dotenv_path.read_text(encoding="utf-8", errors="ignore").splitlines():
|
|
72
|
+
stripped = raw_line.strip()
|
|
73
|
+
if not stripped or stripped.startswith("#") or "=" not in stripped:
|
|
74
|
+
out_lines.append(raw_line)
|
|
75
|
+
continue
|
|
76
|
+
key, val = stripped.split("=", 1)
|
|
77
|
+
key_clean = key.strip()
|
|
78
|
+
val_clean = val.strip().strip('"').strip("'")
|
|
79
|
+
placeholder = _placeholder_for_key(key_clean, val_clean)
|
|
80
|
+
sanitized_map[key_clean] = placeholder
|
|
81
|
+
out_lines.append(f"{key_clean}={placeholder}")
|
|
82
|
+
|
|
83
|
+
output_path.write_text("\n".join(out_lines) + "\n", encoding="utf-8")
|
|
84
|
+
return sanitized_map
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def _placeholder_for_key(key: str, val: str) -> str:
|
|
88
|
+
upper = key.upper()
|
|
89
|
+
if any(tok in upper for tok in ("KEY", "TOKEN", "SECRET", "PASSWORD", "PASSWD", "PAT", "CREDENTIAL")):
|
|
90
|
+
return f"your_{key.lower()}_here"
|
|
91
|
+
if val.startswith(("http://", "https://")):
|
|
92
|
+
return val
|
|
93
|
+
if val.lower() in {"true", "false", "0", "1", "development", "production"} or val.isdigit():
|
|
94
|
+
return val
|
|
95
|
+
return f"your_{key.lower()}_here"
|