leakkill 0.3.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.
leakkill-0.3.0/LICENSE ADDED
@@ -0,0 +1,16 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Ayush
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
6
+ documentation files (the "Software"), to deal in the Software without restriction, including without limitation
7
+ the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and
8
+ to permit persons to whom the Software is furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions
11
+ of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
14
+ THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
16
+ TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,188 @@
1
+ Metadata-Version: 2.4
2
+ Name: leakkill
3
+ Version: 0.3.0
4
+ Summary: Find leaked secrets, check if they're live, revoke them in one command, and keep them out of AI coding agents
5
+ Author-email: Ayush <andymylove24@gmail.com>
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/ayushanand27/leakkill
8
+ Project-URL: Issues, https://github.com/ayushanand27/leakkill/issues
9
+ Project-URL: Changelog, https://github.com/ayushanand27/leakkill/blob/main/CHANGELOG.md
10
+ Keywords: secrets,security,leak,revoke,pre-commit,claude-code,ai-agents,devsecops
11
+ Classifier: Programming Language :: Python :: 3
12
+ Classifier: Operating System :: OS Independent
13
+ Classifier: Topic :: Security
14
+ Classifier: Environment :: Console
15
+ Requires-Python: >=3.9
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Dynamic: license-file
19
+
20
+ # leakkill
21
+
22
+ **Leaked a key? Find it, see if it's live, and kill it in one command. Free, local, zero dependencies.**
23
+
24
+ Free tools are great at *finding* secrets. What happens *after* a leak is usually left to paid
25
+ platforms: is this key still working, whose account is it, how do I revoke it right now, and how do
26
+ I clean it out of git history? leakkill does that part too, from your terminal, for free.
27
+
28
+ ```console
29
+ $ leakkill verify
30
+ #1 LIVE GitHub token ghp_************ config.py:3
31
+ octocat scopes: repo, workflow
32
+ #2 DEAD AWS access key AKIA************ deploy/old.sh:12
33
+ key id is unknown or deactivated
34
+ #3 UNVERIFIABLE Credentials in URL postgres://app:****@db.prod.internal .env.backup:1
35
+
36
+ 3 unique secret(s), 1 LIVE.
37
+
38
+ $ leakkill revoke --only 1 --yes
39
+ #1 GitHub token: REVOKED (HTTP 202)
40
+ ```
41
+
42
+ ## Install
43
+
44
+ ```sh
45
+ pip install leakkill
46
+ ```
47
+
48
+ Python 3.9+, no dependencies. Latest development version:
49
+ `pip install git+https://github.com/ayushanand27/leakkill`
50
+
51
+ ## Commands
52
+
53
+ | Command | What it does | Network? |
54
+ |---|---|---|
55
+ | `leakkill [scan] [PATH ...]` | Find secrets. Exit code 1 if any. | **Never** |
56
+ | `leakkill verify` | Also check each secret against the provider that issued it: live or dead, which account, which scopes | Read-only "who am I" calls |
57
+ | `leakkill revoke` | Show what can be revoked. With `--yes`, revoke the live ones (`--only 1,3` to pick) | Only with `--yes` |
58
+ | `leakkill report` | Write `leakkill-report.md`: every leak, its status and owner, and the cleanup steps in order | Same as `verify` (`--no-verify` to skip) |
59
+ | `leakkill install-hook` | Git pre-commit hook that blocks commits containing secrets | Never |
60
+ | `leakkill install-claude-hook` | Stop Claude Code reading `.env` and keys or writing secrets into code | Never |
61
+
62
+ Every scan command also accepts `--staged` (pre-commit), `--history` (every commit on every branch,
63
+ including secrets you already "deleted"), `--exclude-tests` and `--json`.
64
+
65
+ ## What it can verify and revoke
66
+
67
+ | Provider | Verify (live? whose?) | Revoke from the CLI |
68
+ |---|---|---|
69
+ | GitHub (`ghp_`, `github_pat_`, `gho_`, `ghu_`, `ghr_`) | ✅ user and scopes | ✅ via GitHub's [credential revocation API](https://docs.github.com/en/rest/credentials/revoke) (the owner is notified) |
70
+ | GitLab (`glpat-`) | ✅ token name, scopes, expiry | ✅ self-revoke |
71
+ | Slack tokens (`xox…`) | ✅ user and workspace | ✅ `auth.revoke` |
72
+ | Discord webhooks | ✅ server and channel | ✅ deletes the webhook |
73
+ | AWS access key and secret | ✅ IAM ARN and account (STS, needs no permissions) | ⚠️ deactivates the key if it has `iam:UpdateAccessKey`, otherwise console steps |
74
+ | Stripe, OpenAI, Anthropic, npm, Telegram, Slack webhooks | ✅ | ❌ the provider has no API for it, so you get the exact page or command |
75
+ | Google API keys, private keys, JWTs, credentials in URLs, generic high-entropy secrets | detected, not verifiable | step-by-step rotation guidance |
76
+
77
+ ## How it compares
78
+
79
+ | | leakkill | Gitleaks | TruffleHog OSS | GitGuardian | GitHub Secret Protection |
80
+ |---|---|---|---|---|---|
81
+ | Price | **Free (MIT)** | Free (MIT) | Free (AGPL) | Free for individuals, roughly $15–30/dev/month for teams | Free on public repos, $19/committer/month on private |
82
+ | Runs fully local | ✅ | ✅ | ✅ | ❌ SaaS | ❌ GitHub only |
83
+ | Detectors | ~17 | 150+ | 800+ | 550+ | [provider list](https://docs.github.com/en/code-security/secret-scanning/introduction/supported-secret-scanning-patterns) |
84
+ | Checks if a key is live | ✅ 11 providers | ❌ | ✅ (its main strength) | ✅ | ✅ some |
85
+ | Revokes from the CLI | ✅ 5 providers | ❌ | ❌ (Enterprise) | partial | ❌ |
86
+ | Incident report and history-purge steps | ✅ Markdown file | ❌ | ❌ | ✅ dashboard and playbooks | ❌ |
87
+ | Guards AI coding agents | ✅ Claude Code hooks | ❌ | ❌ | ❌ | ❌ |
88
+ | Dependencies | none | Go binary | Go binary | CLI + account | GitHub |
89
+
90
+ Detector and pricing figures come from public sources in October 2026. Use what fits your needs:
91
+ if breadth of detection matters most, run Gitleaks or TruffleHog alongside leakkill.
92
+
93
+ ### Tested with real credentials
94
+
95
+ End to end on Windows with a real GitHub token and a real Discord webhook: `verify` reported both
96
+ LIVE with the right account and channel, `revoke --yes` returned GitHub `202` and Discord `204`, and
97
+ re-running `verify` reported both DEAD. Against the real AWS, GitLab, Anthropic and npm APIs, invalid
98
+ keys are correctly reported DEAD. Providers not yet tested with a live key (Slack, Stripe, OpenAI,
99
+ Telegram) are covered by tests using simulated API responses.
100
+
101
+ ### Benchmark (reproducible, run October 2026)
102
+
103
+ Noise on clean, popular repos (unique secrets reported, default settings):
104
+
105
+ | Repo | leakkill | Gitleaks 8.28 |
106
+ |---|---|---|
107
+ | psf/requests | 1 (private-key test fixtures) | 4 (same fixtures, one per file) |
108
+ | pallets/flask | 2 (docs example `SECRET_KEY`s) | 2 (same) |
109
+ | django/django | 1 (a CSRF test fixture) | 8 |
110
+ | expressjs/express | 0 | 0 |
111
+
112
+ Recall on 17 planted realistic secrets: **leakkill 17/17, Gitleaks 14/17**. Gitleaks missed a
113
+ Postgres URL with a password, a Discord webhook and a Telegram bot token. The planted set was written
114
+ by us, so it is biased toward formats we support. Gitleaks detects many formats we don't.
115
+
116
+ ## Safety model
117
+
118
+ - `scan` never touches the network.
119
+ - A secret is only ever sent to **the provider that issued it**. Hosts are hard-coded, and HTTP
120
+ redirects are never followed, so a credential can't be bounced to another server (this is tested).
121
+ - Verification uses read-only identity calls: GitHub `GET /user`, Slack `auth.test`, AWS
122
+ `GetCallerIdentity` and so on.
123
+ - `revoke` is a dry run unless you pass `--yes`, and only touches keys that verified as live.
124
+ - Raw secrets are never printed or written to the report. The only exception is the opt-in
125
+ `report --replacements FILE` (needed by `git filter-repo`), which is created with permissions 600.
126
+
127
+ ## Cleaning git history
128
+
129
+ ```sh
130
+ leakkill revoke --history --yes # 1. kill live keys first: history rewrites don't help once copied
131
+ pip install git-filter-repo
132
+ leakkill report --history --replacements .leakkill-replacements.txt
133
+ git filter-repo --replace-text .leakkill-replacements.txt
134
+ rm .leakkill-replacements.txt
135
+ git push --force --all && git push --force --tags # every collaborator must re-clone
136
+ ```
137
+
138
+ ## AI coding agent guard (Claude Code)
139
+
140
+ `leakkill install-claude-hook` adds hooks to `.claude/settings.json` that block:
141
+
142
+ - prompts that contain secrets (before they reach the model)
143
+ - reading `.env`, `*.pem`, `id_rsa`, `.npmrc` and similar, whether through the Read tool or any
144
+ shell command that names such a file (`cat`, `grep`, `base64`, `python -c`, `cp` …).
145
+ `.env.example` is allowed.
146
+ - writing hard-coded keys into code (writing them into `.env` is allowed)
147
+
148
+ This was tested live with the Claude Code CLI: prompts with keys, `Read .env`, `cat .env`,
149
+ `grep . .env` and writing an AWS key into `app.py` were all blocked. The check is pattern-based: a
150
+ command that builds the file name at runtime can get past it. Pair it with OS-level permissions for
151
+ hard guarantees.
152
+
153
+ ## Use in CI (GitHub Actions)
154
+
155
+ ```yaml
156
+ - run: pip install leakkill
157
+ - run: leakkill scan --exclude-tests .
158
+ ```
159
+
160
+ ## Use with the pre-commit framework
161
+
162
+ ```yaml
163
+ # .pre-commit-config.yaml
164
+ repos:
165
+ - repo: https://github.com/ayushanand27/leakkill
166
+ rev: v0.3.0
167
+ hooks:
168
+ - id: leakkill
169
+ ```
170
+
171
+ Or without the framework: `leakkill install-hook`.
172
+
173
+ ## Suppressing false positives
174
+
175
+ - Add `leakkill:ignore` on a line.
176
+ - List paths or globs in `.leakkillignore` (for example `fixtures/` or `*.snap`).
177
+ - High-entropy matches ignore placeholders (`your_key`, `example`, `${VAR}`), variables named
178
+ test/example/fake/mock, password hashes and values without digits.
179
+
180
+ ## Known limitations
181
+
182
+ - Fewer detectors than Gitleaks or TruffleHog.
183
+ - Verification behind a proxy that injects its own credentials (some corporate and sandbox proxies
184
+ do) can report the proxy's identity. Run `verify` from a normal network.
185
+ - AWS keys can only be verified when the secret key is found too (any file in the scan).
186
+ - Stripe, OpenAI, Anthropic, npm and Telegram offer no revoke API, so those need a manual click.
187
+
188
+ MIT licensed.
@@ -0,0 +1,169 @@
1
+ # leakkill
2
+
3
+ **Leaked a key? Find it, see if it's live, and kill it in one command. Free, local, zero dependencies.**
4
+
5
+ Free tools are great at *finding* secrets. What happens *after* a leak is usually left to paid
6
+ platforms: is this key still working, whose account is it, how do I revoke it right now, and how do
7
+ I clean it out of git history? leakkill does that part too, from your terminal, for free.
8
+
9
+ ```console
10
+ $ leakkill verify
11
+ #1 LIVE GitHub token ghp_************ config.py:3
12
+ octocat scopes: repo, workflow
13
+ #2 DEAD AWS access key AKIA************ deploy/old.sh:12
14
+ key id is unknown or deactivated
15
+ #3 UNVERIFIABLE Credentials in URL postgres://app:****@db.prod.internal .env.backup:1
16
+
17
+ 3 unique secret(s), 1 LIVE.
18
+
19
+ $ leakkill revoke --only 1 --yes
20
+ #1 GitHub token: REVOKED (HTTP 202)
21
+ ```
22
+
23
+ ## Install
24
+
25
+ ```sh
26
+ pip install leakkill
27
+ ```
28
+
29
+ Python 3.9+, no dependencies. Latest development version:
30
+ `pip install git+https://github.com/ayushanand27/leakkill`
31
+
32
+ ## Commands
33
+
34
+ | Command | What it does | Network? |
35
+ |---|---|---|
36
+ | `leakkill [scan] [PATH ...]` | Find secrets. Exit code 1 if any. | **Never** |
37
+ | `leakkill verify` | Also check each secret against the provider that issued it: live or dead, which account, which scopes | Read-only "who am I" calls |
38
+ | `leakkill revoke` | Show what can be revoked. With `--yes`, revoke the live ones (`--only 1,3` to pick) | Only with `--yes` |
39
+ | `leakkill report` | Write `leakkill-report.md`: every leak, its status and owner, and the cleanup steps in order | Same as `verify` (`--no-verify` to skip) |
40
+ | `leakkill install-hook` | Git pre-commit hook that blocks commits containing secrets | Never |
41
+ | `leakkill install-claude-hook` | Stop Claude Code reading `.env` and keys or writing secrets into code | Never |
42
+
43
+ Every scan command also accepts `--staged` (pre-commit), `--history` (every commit on every branch,
44
+ including secrets you already "deleted"), `--exclude-tests` and `--json`.
45
+
46
+ ## What it can verify and revoke
47
+
48
+ | Provider | Verify (live? whose?) | Revoke from the CLI |
49
+ |---|---|---|
50
+ | GitHub (`ghp_`, `github_pat_`, `gho_`, `ghu_`, `ghr_`) | ✅ user and scopes | ✅ via GitHub's [credential revocation API](https://docs.github.com/en/rest/credentials/revoke) (the owner is notified) |
51
+ | GitLab (`glpat-`) | ✅ token name, scopes, expiry | ✅ self-revoke |
52
+ | Slack tokens (`xox…`) | ✅ user and workspace | ✅ `auth.revoke` |
53
+ | Discord webhooks | ✅ server and channel | ✅ deletes the webhook |
54
+ | AWS access key and secret | ✅ IAM ARN and account (STS, needs no permissions) | ⚠️ deactivates the key if it has `iam:UpdateAccessKey`, otherwise console steps |
55
+ | Stripe, OpenAI, Anthropic, npm, Telegram, Slack webhooks | ✅ | ❌ the provider has no API for it, so you get the exact page or command |
56
+ | Google API keys, private keys, JWTs, credentials in URLs, generic high-entropy secrets | detected, not verifiable | step-by-step rotation guidance |
57
+
58
+ ## How it compares
59
+
60
+ | | leakkill | Gitleaks | TruffleHog OSS | GitGuardian | GitHub Secret Protection |
61
+ |---|---|---|---|---|---|
62
+ | Price | **Free (MIT)** | Free (MIT) | Free (AGPL) | Free for individuals, roughly $15–30/dev/month for teams | Free on public repos, $19/committer/month on private |
63
+ | Runs fully local | ✅ | ✅ | ✅ | ❌ SaaS | ❌ GitHub only |
64
+ | Detectors | ~17 | 150+ | 800+ | 550+ | [provider list](https://docs.github.com/en/code-security/secret-scanning/introduction/supported-secret-scanning-patterns) |
65
+ | Checks if a key is live | ✅ 11 providers | ❌ | ✅ (its main strength) | ✅ | ✅ some |
66
+ | Revokes from the CLI | ✅ 5 providers | ❌ | ❌ (Enterprise) | partial | ❌ |
67
+ | Incident report and history-purge steps | ✅ Markdown file | ❌ | ❌ | ✅ dashboard and playbooks | ❌ |
68
+ | Guards AI coding agents | ✅ Claude Code hooks | ❌ | ❌ | ❌ | ❌ |
69
+ | Dependencies | none | Go binary | Go binary | CLI + account | GitHub |
70
+
71
+ Detector and pricing figures come from public sources in October 2026. Use what fits your needs:
72
+ if breadth of detection matters most, run Gitleaks or TruffleHog alongside leakkill.
73
+
74
+ ### Tested with real credentials
75
+
76
+ End to end on Windows with a real GitHub token and a real Discord webhook: `verify` reported both
77
+ LIVE with the right account and channel, `revoke --yes` returned GitHub `202` and Discord `204`, and
78
+ re-running `verify` reported both DEAD. Against the real AWS, GitLab, Anthropic and npm APIs, invalid
79
+ keys are correctly reported DEAD. Providers not yet tested with a live key (Slack, Stripe, OpenAI,
80
+ Telegram) are covered by tests using simulated API responses.
81
+
82
+ ### Benchmark (reproducible, run October 2026)
83
+
84
+ Noise on clean, popular repos (unique secrets reported, default settings):
85
+
86
+ | Repo | leakkill | Gitleaks 8.28 |
87
+ |---|---|---|
88
+ | psf/requests | 1 (private-key test fixtures) | 4 (same fixtures, one per file) |
89
+ | pallets/flask | 2 (docs example `SECRET_KEY`s) | 2 (same) |
90
+ | django/django | 1 (a CSRF test fixture) | 8 |
91
+ | expressjs/express | 0 | 0 |
92
+
93
+ Recall on 17 planted realistic secrets: **leakkill 17/17, Gitleaks 14/17**. Gitleaks missed a
94
+ Postgres URL with a password, a Discord webhook and a Telegram bot token. The planted set was written
95
+ by us, so it is biased toward formats we support. Gitleaks detects many formats we don't.
96
+
97
+ ## Safety model
98
+
99
+ - `scan` never touches the network.
100
+ - A secret is only ever sent to **the provider that issued it**. Hosts are hard-coded, and HTTP
101
+ redirects are never followed, so a credential can't be bounced to another server (this is tested).
102
+ - Verification uses read-only identity calls: GitHub `GET /user`, Slack `auth.test`, AWS
103
+ `GetCallerIdentity` and so on.
104
+ - `revoke` is a dry run unless you pass `--yes`, and only touches keys that verified as live.
105
+ - Raw secrets are never printed or written to the report. The only exception is the opt-in
106
+ `report --replacements FILE` (needed by `git filter-repo`), which is created with permissions 600.
107
+
108
+ ## Cleaning git history
109
+
110
+ ```sh
111
+ leakkill revoke --history --yes # 1. kill live keys first: history rewrites don't help once copied
112
+ pip install git-filter-repo
113
+ leakkill report --history --replacements .leakkill-replacements.txt
114
+ git filter-repo --replace-text .leakkill-replacements.txt
115
+ rm .leakkill-replacements.txt
116
+ git push --force --all && git push --force --tags # every collaborator must re-clone
117
+ ```
118
+
119
+ ## AI coding agent guard (Claude Code)
120
+
121
+ `leakkill install-claude-hook` adds hooks to `.claude/settings.json` that block:
122
+
123
+ - prompts that contain secrets (before they reach the model)
124
+ - reading `.env`, `*.pem`, `id_rsa`, `.npmrc` and similar, whether through the Read tool or any
125
+ shell command that names such a file (`cat`, `grep`, `base64`, `python -c`, `cp` …).
126
+ `.env.example` is allowed.
127
+ - writing hard-coded keys into code (writing them into `.env` is allowed)
128
+
129
+ This was tested live with the Claude Code CLI: prompts with keys, `Read .env`, `cat .env`,
130
+ `grep . .env` and writing an AWS key into `app.py` were all blocked. The check is pattern-based: a
131
+ command that builds the file name at runtime can get past it. Pair it with OS-level permissions for
132
+ hard guarantees.
133
+
134
+ ## Use in CI (GitHub Actions)
135
+
136
+ ```yaml
137
+ - run: pip install leakkill
138
+ - run: leakkill scan --exclude-tests .
139
+ ```
140
+
141
+ ## Use with the pre-commit framework
142
+
143
+ ```yaml
144
+ # .pre-commit-config.yaml
145
+ repos:
146
+ - repo: https://github.com/ayushanand27/leakkill
147
+ rev: v0.3.0
148
+ hooks:
149
+ - id: leakkill
150
+ ```
151
+
152
+ Or without the framework: `leakkill install-hook`.
153
+
154
+ ## Suppressing false positives
155
+
156
+ - Add `leakkill:ignore` on a line.
157
+ - List paths or globs in `.leakkillignore` (for example `fixtures/` or `*.snap`).
158
+ - High-entropy matches ignore placeholders (`your_key`, `example`, `${VAR}`), variables named
159
+ test/example/fake/mock, password hashes and values without digits.
160
+
161
+ ## Known limitations
162
+
163
+ - Fewer detectors than Gitleaks or TruffleHog.
164
+ - Verification behind a proxy that injects its own credentials (some corporate and sandbox proxies
165
+ do) can report the proxy's identity. Run `verify` from a normal network.
166
+ - AWS keys can only be verified when the secret key is found too (any file in the scan).
167
+ - Stripe, OpenAI, Anthropic, npm and Telegram offer no revoke API, so those need a manual click.
168
+
169
+ MIT licensed.
@@ -0,0 +1,37 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "leakkill"
7
+ dynamic = ["version"]
8
+ description = "Find leaked secrets, check if they're live, revoke them in one command, and keep them out of AI coding agents"
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ requires-python = ">=3.9"
12
+ authors = [{ name = "Ayush", email = "andymylove24@gmail.com" }]
13
+ keywords = ["secrets", "security", "leak", "revoke", "pre-commit", "claude-code", "ai-agents", "devsecops"]
14
+ classifiers = [
15
+ "Programming Language :: Python :: 3",
16
+ "Operating System :: OS Independent",
17
+ "Topic :: Security",
18
+ "Environment :: Console",
19
+ ]
20
+
21
+ [project.urls]
22
+ Homepage = "https://github.com/ayushanand27/leakkill"
23
+ Issues = "https://github.com/ayushanand27/leakkill/issues"
24
+ Changelog = "https://github.com/ayushanand27/leakkill/blob/main/CHANGELOG.md"
25
+
26
+ [project.scripts]
27
+ leakkill = "leakkill.cli:main_cli"
28
+
29
+ [tool.setuptools.dynamic]
30
+ version = { attr = "leakkill.__version__" }
31
+
32
+ [tool.setuptools.packages.find]
33
+ where = ["src"]
34
+
35
+ [tool.pytest.ini_options]
36
+ pythonpath = ["src"]
37
+ testpaths = ["tests"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,2 @@
1
+ """leakkill: find leaked secrets, check if they're live, revoke them, and guard AI coding agents."""
2
+ __version__ = "0.3.0"
@@ -0,0 +1,3 @@
1
+ from .cli import main_cli
2
+
3
+ main_cli()
@@ -0,0 +1,30 @@
1
+ """Minimal AWS Signature Version 4 signer (stdlib only)."""
2
+ import hashlib, hmac, urllib.parse
3
+ from datetime import datetime, timezone
4
+
5
+
6
+ def _hmac(key, msg):
7
+ return hmac.new(key, msg.encode(), hashlib.sha256).digest()
8
+
9
+
10
+ def sign(method, url, region, service, body, key_id, secret, headers=None, now=None):
11
+ """Return the headers (incl. Authorization) for a SigV4-signed request."""
12
+ t = now or datetime.now(timezone.utc)
13
+ amzdate, datestamp = t.strftime("%Y%m%dT%H%M%SZ"), t.strftime("%Y%m%d")
14
+ u = urllib.parse.urlsplit(url)
15
+ q = sorted(urllib.parse.parse_qsl(u.query, keep_blank_values=True))
16
+ canonical_qs = "&".join(f"{urllib.parse.quote(k, safe='-_.~')}={urllib.parse.quote(v, safe='-_.~')}" for k, v in q)
17
+ hdrs = {"host": u.netloc, "x-amz-date": amzdate, **{k.lower(): v for k, v in (headers or {}).items()}}
18
+ signed = ";".join(sorted(hdrs))
19
+ canonical_headers = "".join(f"{k}:{hdrs[k].strip()}\n" for k in sorted(hdrs))
20
+ creq = "\n".join([method, u.path or "/", canonical_qs, canonical_headers, signed,
21
+ hashlib.sha256(body).hexdigest()])
22
+ scope = f"{datestamp}/{region}/{service}/aws4_request"
23
+ to_sign = "\n".join(["AWS4-HMAC-SHA256", amzdate, scope, hashlib.sha256(creq.encode()).hexdigest()])
24
+ k = _hmac(("AWS4" + secret).encode(), datestamp)
25
+ for part in (region, service, "aws4_request"):
26
+ k = _hmac(k, part)
27
+ sig = hmac.new(k, to_sign.encode(), hashlib.sha256).hexdigest()
28
+ out = {k: v for k, v in hdrs.items() if k != "host"}
29
+ out["Authorization"] = f"AWS4-HMAC-SHA256 Credential={key_id}/{scope}, SignedHeaders={signed}, Signature={sig}"
30
+ return out
@@ -0,0 +1,202 @@
1
+ """leakkill: find leaked secrets, check if they're live, revoke them, and guard AI coding agents.
2
+
3
+ leakkill [scan] [PATH ...] find secrets (offline; exit 1 if any)
4
+ leakkill verify [PATH ...] ...and check which are live and whose they are (exit 1 if any live)
5
+ leakkill revoke [PATH ...] plan revocation of live secrets; add --yes to do it
6
+ leakkill report [PATH ...] write an incident report with step-by-step cleanup
7
+ leakkill install-hook block commits that contain secrets (git pre-commit)
8
+ leakkill install-claude-hook stop Claude Code reading .env/keys or writing secrets
9
+ leakkill guard hook entry point (reads Claude Code hook JSON on stdin)
10
+
11
+ Common options: --staged (pre-commit), --history (all commits), --exclude-tests, --json.
12
+ Ignore a line with `leakkill:ignore`; ignore paths with globs in .leakkillignore.
13
+ """
14
+ import argparse, json, os, sys
15
+ from concurrent.futures import ThreadPoolExecutor
16
+ from dataclasses import dataclass
17
+
18
+ from . import __version__, guard as guard_mod, providers, report, scanner
19
+
20
+ LEGACY = {"--guard": "guard", "--install-hook": "install-hook", "--install-claude-hook": "install-claude-hook"}
21
+ COMMANDS = {"scan", "verify", "revoke", "report", "guard", "install-hook", "install-claude-hook"}
22
+
23
+
24
+ @dataclass
25
+ class Item:
26
+ n: int
27
+ kind: str
28
+ secret: str
29
+ findings: list
30
+ result: providers.Result = None
31
+
32
+
33
+ def collect(args):
34
+ if args.history:
35
+ found = scanner.scan_history()
36
+ elif args.staged:
37
+ found = scanner.scan_staged()
38
+ else:
39
+ found = scanner.scan_paths(args.paths or ["."])
40
+ ignores = scanner.load_ignores()
41
+ found = [f for f in found if not scanner.ignored(f.path, ignores)]
42
+ if args.exclude_tests:
43
+ found = [f for f in found if not scanner.is_test_path(f.path)]
44
+ return [Item(n, k, s, fs) for n, (k, s, fs) in enumerate(scanner.group(found), 1)]
45
+
46
+
47
+ def verify_all(items):
48
+ aws_secrets = {}
49
+ for it in items:
50
+ if it.kind == "AWS secret key":
51
+ for f in it.findings:
52
+ aws_secrets.setdefault(f.path, []).append(it.secret)
53
+ all_aws = [it.secret for it in items if it.kind == "AWS secret key"]
54
+
55
+ def one(it):
56
+ ctx = {}
57
+ if it.kind == "AWS access key":
58
+ near = [s for f in it.findings for s in aws_secrets.get(f.path, [])]
59
+ ctx["aws_secrets"] = list(dict.fromkeys(near + all_aws))
60
+ it.result = providers.verify(it.kind, it.secret, ctx)
61
+
62
+ with ThreadPoolExecutor(8) as ex:
63
+ list(ex.map(one, items))
64
+
65
+
66
+ def as_json(items):
67
+ return json.dumps([{
68
+ "id": it.n, "type": it.kind, "value": it.findings[0].masked,
69
+ "status": it.result.status if it.result else None,
70
+ "identity": it.result.identity if it.result else None,
71
+ "note": it.result.note if it.result else None,
72
+ "locations": [f.location for f in it.findings],
73
+ } for it in items], indent=2)
74
+
75
+
76
+ def print_items(items):
77
+ for it in items:
78
+ r = it.result
79
+ status = f"{r.status:<13}" if r else ""
80
+ extra = " ".join(x for x in ((r.identity, r.note) if r else ()) if x)
81
+ locs = ", ".join(f.location for f in it.findings[:3]) + (f" (+{len(it.findings) - 3})" if len(it.findings) > 3 else "")
82
+ print(f"#{it.n:<3} {status}{it.kind:<22} {it.findings[0].masked:<20} {locs}" + (f"\n {extra}" if extra else ""))
83
+
84
+
85
+ def summary(items):
86
+ if not items:
87
+ return "Clean."
88
+ s = f"\n{len(items)} unique secret(s)"
89
+ if items[0].result:
90
+ live = sum(1 for i in items if i.result.status == providers.LIVE)
91
+ s += f", {live} LIVE"
92
+ return s + "."
93
+
94
+
95
+ def cmd_scan(args, verify=False):
96
+ items = collect(args)
97
+ if verify and items:
98
+ verify_all(items)
99
+ if args.json:
100
+ print(as_json(items))
101
+ else:
102
+ print_items(items)
103
+ print(summary(items))
104
+ if verify:
105
+ return 1 if any(i.result.status == providers.LIVE for i in items) else 0
106
+ return 1 if items else 0
107
+
108
+
109
+ def cmd_revoke(args):
110
+ items = collect(args)
111
+ only = {int(x) for x in args.only.split(",")} if args.only else None
112
+ if only:
113
+ items = [i for i in items if i.n in only]
114
+ if not items:
115
+ print("Nothing to revoke.")
116
+ return 0
117
+ verify_all(items)
118
+ live = [i for i in items if i.result.status == providers.LIVE]
119
+ print_items(items)
120
+ if not live:
121
+ print("\nNo live secrets: nothing to revoke.")
122
+ return 0
123
+ auto = [i for i in live if providers.PROVIDERS[i.kind].revoke]
124
+ manual = [i for i in live if i not in auto]
125
+ print(f"\n{len(live)} live secret(s): {len(auto)} can be revoked automatically, {len(manual)} need manual steps.")
126
+ for i in manual:
127
+ print(f" #{i.n} {i.kind}: {providers.PROVIDERS[i.kind].manual}")
128
+ if not args.yes:
129
+ if auto:
130
+ print(f"\nDry run. Re-run with --yes to revoke: " + ", ".join(f"#{i.n}" for i in auto))
131
+ return 1
132
+ failed = 0
133
+ for i in auto:
134
+ ok, msg = providers.revoke(i.kind, i.secret, i.result)
135
+ print(f" #{i.n} {i.kind}: {'REVOKED' if ok else 'FAILED'} ({msg})")
136
+ if not ok:
137
+ failed += 1
138
+ print(f" manual: {providers.PROVIDERS[i.kind].manual}")
139
+ return 1 if failed or manual else 0
140
+
141
+
142
+ def cmd_report(args):
143
+ items = collect(args)
144
+ if items and not args.no_verify:
145
+ verify_all(items)
146
+ target = "git history" if args.history else "staged changes" if args.staged else " ".join(args.paths or ["."])
147
+ with open(args.output, "w", encoding="utf-8") as f:
148
+ f.write(report.render(items, target, verified=not args.no_verify))
149
+ print(f"Report written to {os.path.abspath(args.output)} ({len(items)} unique secret(s)).")
150
+ if args.replacements:
151
+ report.write_replacements(items, args.replacements)
152
+ print(f"Replacements for git filter-repo written to {args.replacements}. "
153
+ "It contains the raw secrets: delete it when done and never commit it.")
154
+ return 1 if items else 0
155
+
156
+
157
+ def parser():
158
+ common = argparse.ArgumentParser(add_help=False)
159
+ common.add_argument("paths", nargs="*", help="files or directories (default: .)")
160
+ common.add_argument("--staged", action="store_true", help="scan staged git changes")
161
+ common.add_argument("--history", action="store_true", help="scan every commit on every branch")
162
+ common.add_argument("--exclude-tests", action="store_true", help="skip test_* files and tests/ dirs")
163
+ common.add_argument("--json", action="store_true", help="machine-readable output")
164
+ p = argparse.ArgumentParser(prog="leakkill", description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
165
+ p.add_argument("--version", action="version", version=f"leakkill {__version__}")
166
+ sub = p.add_subparsers(dest="cmd")
167
+ sub.add_parser("scan", parents=[common], help="find secrets (offline)")
168
+ sub.add_parser("verify", parents=[common], help="find secrets and check which are live")
169
+ r = sub.add_parser("revoke", parents=[common], help="revoke live secrets (dry run unless --yes)")
170
+ r.add_argument("--only", help="comma-separated ids from `leakkill verify`, e.g. 1,3")
171
+ r.add_argument("--yes", action="store_true", help="actually revoke")
172
+ rp = sub.add_parser("report", parents=[common], help="write a Markdown incident report")
173
+ rp.add_argument("-o", "--output", default="leakkill-report.md")
174
+ rp.add_argument("--no-verify", action="store_true", help="don't contact providers")
175
+ rp.add_argument("--replacements", metavar="FILE", help="also write a git filter-repo --replace-text file")
176
+ for name in ("guard", "install-hook", "install-claude-hook"):
177
+ sub.add_parser(name)
178
+ return p
179
+
180
+
181
+ def main(argv=None):
182
+ argv = list(sys.argv[1:] if argv is None else argv)
183
+ if argv and argv[0] in LEGACY:
184
+ argv[0] = LEGACY[argv[0]]
185
+ if not argv or (argv[0] not in COMMANDS and argv[0] not in ("-h", "--help", "--version")):
186
+ argv.insert(0, "scan")
187
+ args = parser().parse_args(argv)
188
+ if args.cmd == "guard":
189
+ return guard_mod.guard(sys.stdin.read())
190
+ if args.cmd == "install-hook":
191
+ return guard_mod.install_git_hook()
192
+ if args.cmd == "install-claude-hook":
193
+ return guard_mod.install_claude_hook()
194
+ if args.cmd == "revoke":
195
+ return cmd_revoke(args)
196
+ if args.cmd == "report":
197
+ return cmd_report(args)
198
+ return cmd_scan(args, verify=args.cmd == "verify")
199
+
200
+
201
+ def main_cli():
202
+ sys.exit(main())