leakkill 0.7.3__tar.gz → 0.8.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 (37) hide show
  1. {leakkill-0.7.3/src/leakkill.egg-info → leakkill-0.8.0}/PKG-INFO +11 -3
  2. {leakkill-0.7.3 → leakkill-0.8.0}/README.md +10 -2
  3. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill/__init__.py +1 -1
  4. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill/cli.py +50 -8
  5. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill/guard.py +4 -0
  6. leakkill-0.8.0/src/leakkill/onboard.py +72 -0
  7. leakkill-0.8.0/src/leakkill/remote.py +52 -0
  8. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill/report.py +2 -1
  9. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill/scanner.py +17 -8
  10. {leakkill-0.7.3 → leakkill-0.8.0/src/leakkill.egg-info}/PKG-INFO +11 -3
  11. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill.egg-info/SOURCES.txt +3 -0
  12. leakkill-0.8.0/tests/test_onboard_remote.py +145 -0
  13. {leakkill-0.7.3 → leakkill-0.8.0}/tests/test_real_world.py +55 -0
  14. {leakkill-0.7.3 → leakkill-0.8.0}/LICENSE +0 -0
  15. {leakkill-0.7.3 → leakkill-0.8.0}/THIRD_PARTY_NOTICES.md +0 -0
  16. {leakkill-0.7.3 → leakkill-0.8.0}/pyproject.toml +0 -0
  17. {leakkill-0.7.3 → leakkill-0.8.0}/setup.cfg +0 -0
  18. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill/__main__.py +0 -0
  19. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill/agents.py +0 -0
  20. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill/aws.py +0 -0
  21. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill/baseline.py +0 -0
  22. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill/gitleaks_rules.py +0 -0
  23. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill/providers.py +0 -0
  24. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill/sarif.py +0 -0
  25. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill.egg-info/dependency_links.txt +0 -0
  26. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill.egg-info/entry_points.txt +0 -0
  27. {leakkill-0.7.3 → leakkill-0.8.0}/src/leakkill.egg-info/top_level.txt +0 -0
  28. {leakkill-0.7.3 → leakkill-0.8.0}/tests/test_agents.py +0 -0
  29. {leakkill-0.7.3 → leakkill-0.8.0}/tests/test_cli.py +0 -0
  30. {leakkill-0.7.3 → leakkill-0.8.0}/tests/test_coverage_gaps.py +0 -0
  31. {leakkill-0.7.3 → leakkill-0.8.0}/tests/test_fuzz.py +0 -0
  32. {leakkill-0.7.3 → leakkill-0.8.0}/tests/test_guard.py +0 -0
  33. {leakkill-0.7.3 → leakkill-0.8.0}/tests/test_guard_agents.py +0 -0
  34. {leakkill-0.7.3 → leakkill-0.8.0}/tests/test_import_gitleaks.py +0 -0
  35. {leakkill-0.7.3 → leakkill-0.8.0}/tests/test_providers.py +0 -0
  36. {leakkill-0.7.3 → leakkill-0.8.0}/tests/test_redos.py +0 -0
  37. {leakkill-0.7.3 → leakkill-0.8.0}/tests/test_scanner.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: leakkill
3
- Version: 0.7.3
3
+ Version: 0.8.0
4
4
  Summary: Find leaked secrets, check if they're live, revoke them in one command, and keep them out of AI coding agents
5
5
  Author-email: Ayush <andymylove24@gmail.com>
6
6
  License-Expression: MIT
@@ -42,6 +42,10 @@ working, whose account is it, how do I revoke it right now, and how do I clean i
42
42
  with a plain `pip install` (no dependencies), runs locally, and can stop AI coding agents from reading or writing
43
43
  secrets in the first place.
44
44
 
45
+ ![A real terminal: leakkill finds a live GitHub token, revokes it, and confirms it is dead](https://raw.githubusercontent.com/ayushanand27/leakkill/main/docs/demo.png)
46
+
47
+ *A real run on a throwaway GitHub token: found **LIVE**, **REVOKED**, then **DEAD**.*
48
+
45
49
  ```console
46
50
  $ leakkill verify
47
51
  #1 LIVE GitHub token ghp_************ config.py:3
@@ -62,6 +66,8 @@ $ leakkill revoke --only 1 --yes
62
66
  pip install leakkill
63
67
  ```
64
68
 
69
+ Try it without installing: `uvx leakkill scan` or `pipx run leakkill scan` (scans the current folder).
70
+
65
71
  Python 3.9+, no dependencies. Latest development version:
66
72
  `pip install git+https://github.com/ayushanand27/leakkill`
67
73
 
@@ -76,7 +82,9 @@ docker run --rm -v "$PWD:/scan" ghcr.io/ayushanand27/leakkill --history # every
76
82
 
77
83
  | Command | What it does | Network? |
78
84
  |---|---|---|
85
+ | `leakkill init` | Set a project up in one step: the git hook, the guards for the AI agents you use, and a CI workflow. Adds only, never overwrites. | **Never** |
79
86
  | `leakkill [scan] [PATH ...]` | Find secrets. Exit code 1 if any. | **Never** |
87
+ | `leakkill scan <github-url>` | Check a repository **before you trust it**: clones read-only to a temp folder, scans, deletes it (`--history` for every commit). Only scans; `verify`/`revoke` are refused, because they would test keys that belong to someone else. | Only the clone |
80
88
  | `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 |
81
89
  | `leakkill revoke` | Show what can be revoked. With `--yes`, revoke the live ones (`--only 1,3` to pick) | Only with `--yes` |
82
90
  | `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) |
@@ -186,7 +194,7 @@ leakkill somewhat; false alarms on four clean repositories (requests, flask, dja
186
194
 
187
195
  ### How it's tested
188
196
 
189
- - 163 tests on Linux, macOS and Windows with Python 3.9 and 3.13; CI fails below 88% branch coverage (currently 93%).
197
+ - 191 tests on Linux, macOS and Windows with Python 3.9 and 3.13; CI fails below 88% branch coverage (currently 93%).
190
198
  - Property-based fuzz tests: the scanner never crashes on random input, never prints a raw secret, finds a
191
199
  planted token in any surrounding text, and gives the same answer scanning a whole file or line by line.
192
200
  (Fuzzing found two real bugs before release: a guard crash and a slow-input case, both fixed.)
@@ -338,7 +346,7 @@ baseline doesn't make it safe: revoke real keys first.
338
346
  # .pre-commit-config.yaml
339
347
  repos:
340
348
  - repo: https://github.com/ayushanand27/leakkill
341
- rev: v0.7.3
349
+ rev: v0.8.0
342
350
  hooks:
343
351
  - id: leakkill
344
352
  ```
@@ -9,6 +9,10 @@ working, whose account is it, how do I revoke it right now, and how do I clean i
9
9
  with a plain `pip install` (no dependencies), runs locally, and can stop AI coding agents from reading or writing
10
10
  secrets in the first place.
11
11
 
12
+ ![A real terminal: leakkill finds a live GitHub token, revokes it, and confirms it is dead](https://raw.githubusercontent.com/ayushanand27/leakkill/main/docs/demo.png)
13
+
14
+ *A real run on a throwaway GitHub token: found **LIVE**, **REVOKED**, then **DEAD**.*
15
+
12
16
  ```console
13
17
  $ leakkill verify
14
18
  #1 LIVE GitHub token ghp_************ config.py:3
@@ -29,6 +33,8 @@ $ leakkill revoke --only 1 --yes
29
33
  pip install leakkill
30
34
  ```
31
35
 
36
+ Try it without installing: `uvx leakkill scan` or `pipx run leakkill scan` (scans the current folder).
37
+
32
38
  Python 3.9+, no dependencies. Latest development version:
33
39
  `pip install git+https://github.com/ayushanand27/leakkill`
34
40
 
@@ -43,7 +49,9 @@ docker run --rm -v "$PWD:/scan" ghcr.io/ayushanand27/leakkill --history # every
43
49
 
44
50
  | Command | What it does | Network? |
45
51
  |---|---|---|
52
+ | `leakkill init` | Set a project up in one step: the git hook, the guards for the AI agents you use, and a CI workflow. Adds only, never overwrites. | **Never** |
46
53
  | `leakkill [scan] [PATH ...]` | Find secrets. Exit code 1 if any. | **Never** |
54
+ | `leakkill scan <github-url>` | Check a repository **before you trust it**: clones read-only to a temp folder, scans, deletes it (`--history` for every commit). Only scans; `verify`/`revoke` are refused, because they would test keys that belong to someone else. | Only the clone |
47
55
  | `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 |
48
56
  | `leakkill revoke` | Show what can be revoked. With `--yes`, revoke the live ones (`--only 1,3` to pick) | Only with `--yes` |
49
57
  | `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) |
@@ -153,7 +161,7 @@ leakkill somewhat; false alarms on four clean repositories (requests, flask, dja
153
161
 
154
162
  ### How it's tested
155
163
 
156
- - 163 tests on Linux, macOS and Windows with Python 3.9 and 3.13; CI fails below 88% branch coverage (currently 93%).
164
+ - 191 tests on Linux, macOS and Windows with Python 3.9 and 3.13; CI fails below 88% branch coverage (currently 93%).
157
165
  - Property-based fuzz tests: the scanner never crashes on random input, never prints a raw secret, finds a
158
166
  planted token in any surrounding text, and gives the same answer scanning a whole file or line by line.
159
167
  (Fuzzing found two real bugs before release: a guard crash and a slow-input case, both fixed.)
@@ -305,7 +313,7 @@ baseline doesn't make it safe: revoke real keys first.
305
313
  # .pre-commit-config.yaml
306
314
  repos:
307
315
  - repo: https://github.com/ayushanand27/leakkill
308
- rev: v0.7.3
316
+ rev: v0.8.0
309
317
  hooks:
310
318
  - id: leakkill
311
319
  ```
@@ -1,2 +1,2 @@
1
1
  """leakkill: find leaked secrets, check if they're live, revoke them, and guard AI coding agents."""
2
- __version__ = "0.7.3"
2
+ __version__ = "0.8.0"
@@ -4,6 +4,8 @@
4
4
  leakkill verify [PATH ...] ...and check which are live and whose they are (exit 1 if any live)
5
5
  leakkill revoke [PATH ...] plan revocation of live secrets; add --yes to do it
6
6
  leakkill report [PATH ...] write an incident report with step-by-step cleanup
7
+ leakkill init set this project up in one step: git hook, AI agent guards, CI workflow
8
+ leakkill scan <github-url> scan a repository before you trust it (clones to a temp folder, then deletes it)
7
9
  leakkill install-hook block commits that contain secrets (git pre-commit)
8
10
  leakkill install-agent-hooks [AGENT ...] [--global]
9
11
  stop AI agents (claude, cursor, copilot, codex) reading .env/keys,
@@ -20,10 +22,10 @@ import argparse, difflib, json, os, sys
20
22
  from concurrent.futures import ThreadPoolExecutor
21
23
  from dataclasses import dataclass
22
24
 
23
- from . import __version__, agents, baseline, guard as guard_mod, providers, report, sarif, scanner
25
+ from . import __version__, agents, baseline, guard as guard_mod, onboard, providers, remote, report, sarif, scanner
24
26
 
25
27
  LEGACY = {"--guard": "guard", "--install-hook": "install-hook", "--install-claude-hook": "install-claude-hook"}
26
- COMMANDS = {"scan", "verify", "revoke", "report", "guard", "install-hook", "install-claude-hook", "install-agent-hooks"}
28
+ COMMANDS = {"scan", "verify", "revoke", "report", "guard", "install-hook", "install-claude-hook", "install-agent-hooks", "init"}
27
29
 
28
30
 
29
31
  @dataclass
@@ -60,7 +62,7 @@ def collect(args):
60
62
  else:
61
63
  found = scanner.scan_paths(args.paths or ["."], include_ignored=args.include_ignored)
62
64
  note_skipped()
63
- ignores = scanner.load_ignores()
65
+ ignores = [] if getattr(args, "untrusted", False) else scanner.load_ignores()
64
66
  found = [f for f in found if not scanner.ignored(f.path, ignores)]
65
67
  if args.exclude_tests:
66
68
  found = [f for f in found if not scanner.is_test_path(f.path)]
@@ -256,6 +258,7 @@ def parser():
256
258
  rp.add_argument("--replacements", metavar="FILE", help="also write a git filter-repo --replace-text file")
257
259
  g = sub.add_parser("guard", help="AI agent hook entry point (reads hook JSON on stdin)")
258
260
  g.add_argument("--agent", choices=guard_mod.AGENTS, default="claude")
261
+ sub.add_parser("init", help="set this project up: git hook, AI agent guards, CI workflow")
259
262
  ia = sub.add_parser("install-agent-hooks", help="guard AI coding agents against secret leaks")
260
263
  ia.add_argument("agents", nargs="*", metavar="AGENT",
261
264
  help="claude, cursor, copilot, codex (default: all)")
@@ -276,6 +279,45 @@ def check_paths(paths):
276
279
  return not missing
277
280
 
278
281
 
282
+ def run_scan_command(args):
283
+ if args.cmd == "revoke":
284
+ return cmd_revoke(args)
285
+ if args.cmd == "report":
286
+ return cmd_report(args)
287
+ return cmd_scan(args, verify=args.cmd == "verify")
288
+
289
+
290
+ def scan_remote(args, url):
291
+ """Scan someone else's repository: read-only, never contacting providers about keys that aren't yours."""
292
+ if args.cmd in ("verify", "revoke"):
293
+ print(f"leakkill: `{args.cmd}` doesn't work on a remote repository: it would test or revoke keys that "
294
+ "belong to someone else. Run `leakkill scan <url>` to see what is in it; for a repository you own, "
295
+ f"clone it and run `leakkill {args.cmd}` on the local copy.", file=sys.stderr)
296
+ return 2
297
+ if args.agents or args.staged:
298
+ print("leakkill: --agents and --staged only apply to this machine, not a remote repository.", file=sys.stderr)
299
+ return 2
300
+ for name in ("output", "report", "sarif", "write_baseline", "baseline", "replacements"):
301
+ if getattr(args, name, None):
302
+ setattr(args, name, os.path.abspath(getattr(args, name))) # we change folder below
303
+ args.no_verify, args.untrusted = True, True
304
+ origin = os.getcwd()
305
+ print(f"Cloning {remote.safe_url(url)} read-only; the copy is deleted afterwards...", file=sys.stderr)
306
+ try:
307
+ with remote.checkout(url, full_history=args.history) as work:
308
+ try:
309
+ os.chdir(work)
310
+ args.paths = ["."]
311
+ scanner.INLINE_IGNORE = False # a repository you don't trust doesn't get to hide its own findings
312
+ return run_scan_command(args)
313
+ finally:
314
+ os.chdir(origin)
315
+ scanner.INLINE_IGNORE = True
316
+ except RuntimeError as e:
317
+ print(f"leakkill: could not clone {remote.safe_url(url)}: {e}", file=sys.stderr)
318
+ return 2
319
+
320
+
279
321
  def main(argv=None):
280
322
  argv = list(sys.argv[1:] if argv is None else argv)
281
323
  if argv and argv[0] in LEGACY:
@@ -283,8 +325,12 @@ def main(argv=None):
283
325
  if not argv or (argv[0] not in COMMANDS and argv[0] not in ("-h", "--help", "--version")):
284
326
  argv.insert(0, "scan")
285
327
  args = parser().parse_args(argv)
328
+ if args.cmd in ("scan", "verify", "revoke", "report") and len(args.paths) == 1 and remote.parse(args.paths[0]):
329
+ return scan_remote(args, remote.parse(args.paths[0]))
286
330
  if args.cmd in ("scan", "verify", "revoke", "report") and not check_paths(args.paths):
287
331
  return 2
332
+ if args.cmd == "init":
333
+ return onboard.run()
288
334
  if args.cmd == "guard":
289
335
  return guard_mod.guard(sys.stdin.read(), args.agent)
290
336
  if args.cmd == "install-agent-hooks":
@@ -297,11 +343,7 @@ def main(argv=None):
297
343
  return guard_mod.install_git_hook()
298
344
  if args.cmd == "install-claude-hook":
299
345
  return guard_mod.install_claude_hook()
300
- if args.cmd == "revoke":
301
- return cmd_revoke(args)
302
- if args.cmd == "report":
303
- return cmd_report(args)
304
- return cmd_scan(args, verify=args.cmd == "verify")
346
+ return run_scan_command(args)
305
347
 
306
348
 
307
349
  def main_cli():
@@ -273,6 +273,10 @@ def install_git_hook():
273
273
  print("Not a git repo root.", file=sys.stderr)
274
274
  return 1
275
275
  hook = os.path.join(".git", "hooks", "pre-commit")
276
+ if os.path.exists(hook) and "leakkill" not in open(hook, encoding="utf-8", errors="replace").read():
277
+ print(f"{hook} already exists and isn't leakkill's: not overwriting it. Add this line to it yourself:\n"
278
+ f" {_self_cmd('scan --staged')} || exit 1", file=sys.stderr)
279
+ return 1
276
280
  cmd = _self_cmd("scan --staged").replace("\\", "/")
277
281
  with open(hook, "w", newline="\n") as f:
278
282
  f.write(f'#!/bin/sh\n{cmd} || {{ echo "Commit blocked by leakkill."; exit 1; }}\n')
@@ -0,0 +1,72 @@
1
+ """`leakkill init`: set a project up in one command (git hook, AI agent guards, CI workflow), safely and repeatably.
2
+
3
+ It only adds things, never overwrites a file it didn't write, and says what it did and what it skipped.
4
+ """
5
+ import os, shutil, sys
6
+
7
+ from . import guard
8
+
9
+ WORKFLOW = """name: leakkill
10
+ on: [push, pull_request]
11
+ permissions:
12
+ contents: read
13
+ jobs:
14
+ secrets:
15
+ runs-on: ubuntu-latest
16
+ steps:
17
+ - uses: actions/checkout@v7
18
+ with: { fetch-depth: 0 }
19
+ - uses: ayushanand27/leakkill@v0
20
+ with: { history: true } # also fails on secrets that were committed and later deleted
21
+ """
22
+ # agent -> (config folder in the home directory, commands that mean it is installed)
23
+ AGENT_HINTS = {"claude": (".claude", ("claude",)), "cursor": (".cursor", ("cursor", "cursor-agent")),
24
+ "copilot": (".copilot", ("copilot",)), "codex": (".codex", ("codex",))}
25
+
26
+
27
+ def agents_in_use(home=None, project="."):
28
+ """Agents that appear to be installed or used here: a config folder, or the program on the PATH."""
29
+ home = home or os.path.expanduser("~")
30
+ found = []
31
+ for agent, (folder, programs) in AGENT_HINTS.items():
32
+ if os.path.isdir(os.path.join(home, folder)) or os.path.isdir(os.path.join(project, folder)) \
33
+ or any(shutil.which(p) for p in programs):
34
+ found.append(agent)
35
+ return found
36
+
37
+
38
+ def _git_hook():
39
+ if not os.path.isdir(".git"):
40
+ return "skipped the git hook (run this from the top folder of a git repository)"
41
+ hook = os.path.join(".git", "hooks", "pre-commit")
42
+ if os.path.exists(hook) and "leakkill" not in open(hook, encoding="utf-8", errors="replace").read():
43
+ return f"skipped the git hook ({hook} already exists and isn't leakkill's)"
44
+ guard.install_git_hook()
45
+ return None
46
+
47
+
48
+ def _workflow():
49
+ path = os.path.join(".github", "workflows", "leakkill.yml")
50
+ if os.path.exists(path):
51
+ return f"kept your existing {path}"
52
+ if not (os.path.isdir(".github") or os.path.isdir(".git")):
53
+ return "skipped the CI workflow (not a git project)"
54
+ os.makedirs(os.path.dirname(path), exist_ok=True)
55
+ with open(path, "w", encoding="utf-8") as f:
56
+ f.write(WORKFLOW)
57
+ print(f"Wrote {path}")
58
+ return None
59
+
60
+
61
+ def run(home=None):
62
+ notes = [_git_hook()]
63
+ chosen = agents_in_use(home)
64
+ if chosen:
65
+ guard.install_agent_hooks(chosen)
66
+ else:
67
+ notes.append("no AI coding agent found (add one later with `leakkill install-agent-hooks`)")
68
+ notes.append(_workflow())
69
+ for n in filter(None, notes):
70
+ print(f" note: {n}")
71
+ print("\nDone. Next: `leakkill` scans this folder now; `leakkill scan --agents` checks what your AI tools stored.")
72
+ return 0
@@ -0,0 +1,52 @@
1
+ """`leakkill scan https://github.com/owner/repo`: clone read-only into a temp folder, scan it, delete it.
2
+
3
+ For checking a repository before you trust it. Cloning untrusted code is the risky part, so:
4
+ - only https:// and ssh-style URLs are accepted (git's `ext::` and `file:` transports can run commands or read
5
+ local files), and the URL goes after `--` so it can never be taken for an option;
6
+ - git never asks for a password (GIT_TERMINAL_PROMPT=0), never fetches submodules, and runs with the same
7
+ hardening as every other leakkill git call (no repository-configured programs);
8
+ - the clone is deleted afterwards, even when the scan fails.
9
+ """
10
+ import contextlib, os, re, shutil, stat, subprocess, tempfile
11
+
12
+ URL = re.compile(r"^(?:https://[^\s/]+/\S+|ssh://\S+|[\w.-]+@[\w.-]+:\S+)$")
13
+ SHORT = re.compile(r"^(github\.com|gitlab\.com|bitbucket\.org|codeberg\.org)/[\w.-]+/[\w.-]+$")
14
+
15
+
16
+ def parse(arg):
17
+ """A clone URL for `arg` if it is one (or looks like github.com/owner/repo), else None (a local path)."""
18
+ if not isinstance(arg, str) or arg.startswith("-") or any(c.isspace() for c in arg) or os.path.exists(arg):
19
+ return None
20
+ if SHORT.match(arg):
21
+ return "https://" + arg
22
+ return arg if URL.match(arg) and not arg.lower().startswith(("ext::", "file:")) else None
23
+
24
+
25
+ def safe_url(url):
26
+ """The URL with any `user:password@` removed, for messages."""
27
+ return re.sub(r"//[^/@\s]*@", "//", url)
28
+
29
+
30
+ def _clone(url, dest, full_history):
31
+ from .scanner import run_git
32
+ depth = [] if full_history else ["--depth", "1"]
33
+ r = run_git("-c", "protocol.allow=never", "-c", "protocol.https.allow=always", "-c", "protocol.ssh.allow=always",
34
+ "clone", "--quiet", "--no-tags", "--no-recurse-submodules", *depth, "--", url, dest,
35
+ text=True, timeout=600, env_extra={"GIT_TERMINAL_PROMPT": "0"})
36
+ if r.returncode:
37
+ raise RuntimeError((r.stderr or "git clone failed").strip().splitlines()[-1][:300])
38
+
39
+
40
+ def _writable(func, path, _exc): # Windows keeps .git objects read-only
41
+ os.chmod(path, stat.S_IWRITE)
42
+ func(path)
43
+
44
+
45
+ @contextlib.contextmanager
46
+ def checkout(url, full_history=False, clone=_clone):
47
+ work = tempfile.mkdtemp(prefix="leakkill-")
48
+ try:
49
+ clone(url, os.path.join(work, "repo"), full_history)
50
+ yield os.path.join(work, "repo")
51
+ finally:
52
+ shutil.rmtree(work, onerror=_writable)
@@ -3,11 +3,12 @@ import os, subprocess
3
3
  from datetime import datetime, timezone
4
4
 
5
5
  from .providers import LIVE, DEAD, provider
6
+ from .scanner import run_git
6
7
 
7
8
 
8
9
  def tracked_files():
9
10
  try:
10
- out = subprocess.run(["git", "ls-files", "-z"], capture_output=True, text=True, check=True).stdout
11
+ out = run_git("ls-files", "-z", text=True, check=True).stdout
11
12
  return {os.path.normpath(p) for p in out.split("\0") if p}
12
13
  except (OSError, subprocess.CalledProcessError):
13
14
  return None # not a git repo
@@ -308,7 +308,7 @@ def _scan(text, path=None):
308
308
  out = {}
309
309
  for ln in sorted(raw):
310
310
  end = starts[ln] if ln < len(starts) else len(text)
311
- if "leakkill:ignore" in text[starts[ln - 1]:end]:
311
+ if INLINE_IGNORE and "leakkill:ignore" in text[starts[ln - 1]:end]:
312
312
  continue
313
313
  hits = []
314
314
  for kind, val in raw[ln]: # rule order first, then position: a specific rule beats a generic one
@@ -352,6 +352,7 @@ def iter_files(paths):
352
352
  yield os.path.join(root, f)
353
353
 
354
354
 
355
+ INLINE_IGNORE = True # honor `leakkill:ignore` comments; switched off when scanning a repository you don't trust
355
356
  MAX_SCAN_BYTES = 2_000_000
356
357
 
357
358
 
@@ -417,14 +418,22 @@ def _parallel(fn, items, jobs=None):
417
418
  return [f for item in items for f in fn(item)]
418
419
 
419
420
 
421
+ def run_git(*args, cwd=None, env_extra=None, **kw):
422
+ """Run git in a repository that may be untrusted. A repository's own config can name programs for git to run
423
+ (core.fsmonitor, diff drivers and text converters), so those are switched off: scanning a repo must never
424
+ run code from it. `cwd` keeps the folder out of the command line, where a name like `--foo` could be an option."""
425
+ return subprocess.run(["git", "-c", "core.fsmonitor=false", *args], cwd=cwd, capture_output=True,
426
+ env={**os.environ, "GIT_OPTIONAL_LOCKS": "0", **(env_extra or {})}, **kw)
427
+
428
+
420
429
  def _git_ignored(path):
421
430
  """(files, directories) under `path` that git ignores and does not track; empty outside a git repository,
422
431
  and empty when `path` itself is ignored (you named a folder like `data/`: you want it scanned)."""
423
432
  try:
424
- if subprocess.run(["git", "-C", path, "check-ignore", "-q", "."], capture_output=True, timeout=30).returncode == 0:
433
+ if run_git("check-ignore", "-q", ".", cwd=path, timeout=30).returncode == 0:
425
434
  return set(), []
426
- r = subprocess.run(["git", "-C", path, "ls-files", "--others", "--ignored", "--exclude-standard",
427
- "--directory", "-z"], capture_output=True, timeout=30)
435
+ r = run_git("ls-files", "--others", "--ignored", "--exclude-standard", "--directory", "-z", cwd=path,
436
+ timeout=30)
428
437
  except (OSError, subprocess.SubprocessError):
429
438
  return set(), []
430
439
  if r.returncode:
@@ -467,8 +476,7 @@ def scan_paths(paths, jobs=None, include_ignored=False):
467
476
 
468
477
 
469
478
  def _git(*args):
470
- return subprocess.run(["git", *args], capture_output=True, text=True,
471
- encoding="utf-8", errors="replace").stdout
479
+ return run_git(*args, text=True, encoding="utf-8", errors="replace").stdout
472
480
 
473
481
 
474
482
  def _scan_batch(batch):
@@ -507,12 +515,13 @@ def _scan_diff(diff, commit_of_header=None, jobs=None):
507
515
 
508
516
 
509
517
  def scan_staged():
510
- return _scan_diff(_git("diff", "--cached", "-U0", "--no-color"))
518
+ return _scan_diff(_git("diff", "--cached", "-U0", "--no-color", "--no-ext-diff", "--no-textconv"))
511
519
 
512
520
 
513
521
  def scan_history():
514
522
  """Every line ever added in any commit on any branch (catches secrets that were 'deleted')."""
515
- return _scan_diff(_git("log", "-p", "--all", "-U0", "--no-color", "--format=commit %h"), commit_of_header=True)
523
+ return _scan_diff(_git("log", "-p", "--all", "-U0", "--no-color", "--no-ext-diff", "--no-textconv",
524
+ "--format=commit %h"), commit_of_header=True)
516
525
 
517
526
 
518
527
  def is_test_path(path):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: leakkill
3
- Version: 0.7.3
3
+ Version: 0.8.0
4
4
  Summary: Find leaked secrets, check if they're live, revoke them in one command, and keep them out of AI coding agents
5
5
  Author-email: Ayush <andymylove24@gmail.com>
6
6
  License-Expression: MIT
@@ -42,6 +42,10 @@ working, whose account is it, how do I revoke it right now, and how do I clean i
42
42
  with a plain `pip install` (no dependencies), runs locally, and can stop AI coding agents from reading or writing
43
43
  secrets in the first place.
44
44
 
45
+ ![A real terminal: leakkill finds a live GitHub token, revokes it, and confirms it is dead](https://raw.githubusercontent.com/ayushanand27/leakkill/main/docs/demo.png)
46
+
47
+ *A real run on a throwaway GitHub token: found **LIVE**, **REVOKED**, then **DEAD**.*
48
+
45
49
  ```console
46
50
  $ leakkill verify
47
51
  #1 LIVE GitHub token ghp_************ config.py:3
@@ -62,6 +66,8 @@ $ leakkill revoke --only 1 --yes
62
66
  pip install leakkill
63
67
  ```
64
68
 
69
+ Try it without installing: `uvx leakkill scan` or `pipx run leakkill scan` (scans the current folder).
70
+
65
71
  Python 3.9+, no dependencies. Latest development version:
66
72
  `pip install git+https://github.com/ayushanand27/leakkill`
67
73
 
@@ -76,7 +82,9 @@ docker run --rm -v "$PWD:/scan" ghcr.io/ayushanand27/leakkill --history # every
76
82
 
77
83
  | Command | What it does | Network? |
78
84
  |---|---|---|
85
+ | `leakkill init` | Set a project up in one step: the git hook, the guards for the AI agents you use, and a CI workflow. Adds only, never overwrites. | **Never** |
79
86
  | `leakkill [scan] [PATH ...]` | Find secrets. Exit code 1 if any. | **Never** |
87
+ | `leakkill scan <github-url>` | Check a repository **before you trust it**: clones read-only to a temp folder, scans, deletes it (`--history` for every commit). Only scans; `verify`/`revoke` are refused, because they would test keys that belong to someone else. | Only the clone |
80
88
  | `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 |
81
89
  | `leakkill revoke` | Show what can be revoked. With `--yes`, revoke the live ones (`--only 1,3` to pick) | Only with `--yes` |
82
90
  | `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) |
@@ -186,7 +194,7 @@ leakkill somewhat; false alarms on four clean repositories (requests, flask, dja
186
194
 
187
195
  ### How it's tested
188
196
 
189
- - 163 tests on Linux, macOS and Windows with Python 3.9 and 3.13; CI fails below 88% branch coverage (currently 93%).
197
+ - 191 tests on Linux, macOS and Windows with Python 3.9 and 3.13; CI fails below 88% branch coverage (currently 93%).
190
198
  - Property-based fuzz tests: the scanner never crashes on random input, never prints a raw secret, finds a
191
199
  planted token in any surrounding text, and gives the same answer scanning a whole file or line by line.
192
200
  (Fuzzing found two real bugs before release: a guard crash and a slow-input case, both fixed.)
@@ -338,7 +346,7 @@ baseline doesn't make it safe: revoke real keys first.
338
346
  # .pre-commit-config.yaml
339
347
  repos:
340
348
  - repo: https://github.com/ayushanand27/leakkill
341
- rev: v0.7.3
349
+ rev: v0.8.0
342
350
  hooks:
343
351
  - id: leakkill
344
352
  ```
@@ -10,7 +10,9 @@ src/leakkill/baseline.py
10
10
  src/leakkill/cli.py
11
11
  src/leakkill/gitleaks_rules.py
12
12
  src/leakkill/guard.py
13
+ src/leakkill/onboard.py
13
14
  src/leakkill/providers.py
15
+ src/leakkill/remote.py
14
16
  src/leakkill/report.py
15
17
  src/leakkill/sarif.py
16
18
  src/leakkill/scanner.py
@@ -26,6 +28,7 @@ tests/test_fuzz.py
26
28
  tests/test_guard.py
27
29
  tests/test_guard_agents.py
28
30
  tests/test_import_gitleaks.py
31
+ tests/test_onboard_remote.py
29
32
  tests/test_providers.py
30
33
  tests/test_real_world.py
31
34
  tests/test_redos.py
@@ -0,0 +1,145 @@
1
+ import json, os, subprocess, sys, tempfile
2
+
3
+ import pytest
4
+
5
+ from leakkill import cli, onboard, remote, scanner
6
+
7
+ GH = "ghp_" + "a1B2c3D4e5F6g7H8i9J0k1L2m3N4o5P6q7R8"
8
+
9
+
10
+ def git(cwd, *args):
11
+ subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True)
12
+
13
+
14
+ # ---------------------------------------------------------------- scan <url>
15
+ @pytest.mark.parametrize("arg,expected", [
16
+ ("https://github.com/owner/repo", "https://github.com/owner/repo"),
17
+ ("https://github.com/owner/repo.git", "https://github.com/owner/repo.git"),
18
+ ("github.com/owner/repo", "https://github.com/owner/repo"),
19
+ ("git@github.com:owner/repo.git", "git@github.com:owner/repo.git"),
20
+ ("ssh://git@host/owner/repo", "ssh://git@host/owner/repo"),
21
+ ])
22
+ def test_parse_accepts_clone_urls(arg, expected, tmp_path, monkeypatch):
23
+ monkeypatch.chdir(tmp_path)
24
+ assert remote.parse(arg) == expected
25
+
26
+
27
+ @pytest.mark.parametrize("arg", ["ext::sh -c 'touch /tmp/x'", "file:///etc", "--upload-pack=evil", "-h", "src", ".",
28
+ "http://github.com/o/r", "ftp://x/y", "https://x/y z", "github.com/owner", ""])
29
+ def test_parse_rejects_everything_else(arg, tmp_path, monkeypatch):
30
+ monkeypatch.chdir(tmp_path)
31
+ assert remote.parse(arg) is None
32
+
33
+
34
+ def test_an_existing_local_path_is_never_a_url(tmp_path, monkeypatch):
35
+ monkeypatch.chdir(tmp_path)
36
+ (tmp_path / "github.com" / "o").mkdir(parents=True)
37
+ (tmp_path / "github.com" / "o" / "r").mkdir()
38
+ assert remote.parse("github.com/o/r") is None
39
+
40
+
41
+ def test_credentials_never_printed():
42
+ assert remote.safe_url("https://user:pw@host/o/r") == "https://host/o/r"
43
+
44
+
45
+ @pytest.fixture
46
+ def fake_remote(tmp_path, monkeypatch):
47
+ """A local repository standing in for the remote one: a secret that was committed and later deleted."""
48
+ src = tmp_path / "src_repo"
49
+ src.mkdir()
50
+ git(src, "init", "-q")
51
+ git(src, "config", "user.email", "t@example.com")
52
+ git(src, "config", "user.name", "t")
53
+ (src / "old.py").write_text(f'T = "{GH}"\n')
54
+ (src / ".leakkillignore").write_text("*\n") # the repo tries to hide everything
55
+ git(src, "add", "-A"); git(src, "commit", "-qm", "leak")
56
+ (src / "old.py").write_text("T = 1\n")
57
+ (src / "new.py").write_text(f'T = "{GH}" # leakkill:ignore\n')
58
+ git(src, "add", "-A"); git(src, "commit", "-qm", "remove")
59
+ def clone(url, dest, full_history):
60
+ args = ["git", "clone", "--quiet", str(src), dest] if full_history else ["git", "clone", "--quiet", "--depth", "1", "file://" + str(src), dest]
61
+ subprocess.run(args, check=True, capture_output=True)
62
+ cleaned = []
63
+ real = remote.checkout
64
+ monkeypatch.setattr(remote, "checkout", lambda url, full_history=False: real(url, full_history, clone=clone))
65
+ work = tmp_path / "work"
66
+ work.mkdir()
67
+ monkeypatch.chdir(work)
68
+ return work
69
+
70
+
71
+ def test_remote_scan_ignores_the_repos_own_hiding_and_cleans_up(fake_remote, capsys, monkeypatch, tmp_path):
72
+ scratch = tmp_path / "scratch"
73
+ scratch.mkdir()
74
+ monkeypatch.setattr(tempfile, "tempdir", str(scratch))
75
+ assert cli.main(["scan", "https://example.com/o/r"]) == 1 # new.py: its leakkill:ignore and .leakkillignore are not honored
76
+ out = capsys.readouterr().out
77
+ assert "new.py:1" in out and GH not in out
78
+ assert scanner.INLINE_IGNORE is True and os.getcwd() == str(fake_remote) # state restored
79
+ assert os.listdir(scratch) == [] # the clone is gone
80
+
81
+
82
+ def test_remote_history_finds_the_deleted_secret(fake_remote, capsys):
83
+ assert cli.main(["scan", "--history", "--json", "https://example.com/o/r"]) == 1
84
+ assert any("old.py" in loc for i in json.loads(capsys.readouterr().out) for loc in i["locations"])
85
+
86
+
87
+ def test_remote_never_verifies_or_revokes_someone_elses_keys(fake_remote, capsys, monkeypatch):
88
+ called = []
89
+ monkeypatch.setattr(cli.providers, "verify", lambda *a, **k: called.append(a))
90
+ for cmd in ("verify", "revoke"):
91
+ assert cli.main([cmd, "https://example.com/o/r"]) == 2
92
+ assert "belong to someone else" in capsys.readouterr().err and not called
93
+
94
+
95
+ def test_remote_report_writes_next_to_you_not_in_the_temp_clone(fake_remote):
96
+ assert cli.main(["report", "-o", "r.md", "https://example.com/o/r"]) == 1
97
+ text = (fake_remote / "r.md").read_text()
98
+ assert "not verified" in text and GH not in text # never contacted a provider about keys that aren't yours
99
+
100
+
101
+ def test_clone_failure_is_a_clean_error(tmp_path, monkeypatch, capsys):
102
+ monkeypatch.chdir(tmp_path)
103
+ def boom(url, dest, full_history):
104
+ raise RuntimeError("repository not found")
105
+ real = remote.checkout
106
+ monkeypatch.setattr(remote, "checkout", lambda url, full_history=False: real(url, full_history, clone=boom))
107
+ assert cli.main(["scan", "https://example.com/o/missing"]) == 2
108
+ assert "could not clone https://example.com/o/missing: repository not found" in capsys.readouterr().err
109
+
110
+
111
+ # ---------------------------------------------------------------- init
112
+ def test_init_sets_up_what_exists_and_is_repeatable(tmp_path, monkeypatch, capsys):
113
+ home = tmp_path / "home"
114
+ (home / ".cursor").mkdir(parents=True)
115
+ work = tmp_path / "proj"
116
+ work.mkdir()
117
+ git(work, "init", "-q")
118
+ monkeypatch.chdir(work)
119
+ monkeypatch.setattr(onboard.shutil, "which", lambda p: None)
120
+ monkeypatch.setenv("HOME", str(home)); monkeypatch.setenv("USERPROFILE", str(home))
121
+ assert cli.main(["init"]) == 0
122
+ assert (work / ".git" / "hooks" / "pre-commit").exists()
123
+ assert (work / ".cursor" / "hooks.json").exists() and not (work / ".claude").exists() # only the agent in use
124
+ assert "uses: ayushanand27/leakkill@v0" in (work / ".github" / "workflows" / "leakkill.yml").read_text()
125
+ first = (work / ".cursor" / "hooks.json").read_text()
126
+ assert cli.main(["init"]) == 0 # again: nothing breaks, nothing duplicates
127
+ assert (work / ".cursor" / "hooks.json").read_text() == first
128
+ assert "kept your existing" in capsys.readouterr().out
129
+
130
+
131
+ def test_init_never_overwrites_foreign_files(tmp_path, monkeypatch, capsys):
132
+ work = tmp_path / "proj"
133
+ (work / ".git" / "hooks").mkdir(parents=True)
134
+ (work / ".git" / "hooks" / "pre-commit").write_text("#!/bin/sh\necho mine\n")
135
+ (work / ".github" / "workflows").mkdir(parents=True)
136
+ (work / ".github" / "workflows" / "leakkill.yml").write_text("mine: true\n")
137
+ monkeypatch.chdir(work)
138
+ monkeypatch.setattr(onboard.shutil, "which", lambda p: None)
139
+ monkeypatch.setenv("HOME", str(tmp_path / "nohome")); monkeypatch.setenv("USERPROFILE", str(tmp_path / "nohome"))
140
+ assert cli.main(["init"]) == 0
141
+ assert "echo mine" in (work / ".git" / "hooks" / "pre-commit").read_text()
142
+ assert (work / ".github" / "workflows" / "leakkill.yml").read_text() == "mine: true\n"
143
+ out = capsys.readouterr().out
144
+ assert "isn't leakkill's" in out and "no AI coding agent found" in out
145
+ assert cli.main(["install-hook"]) == 1 # the standalone command refuses too
@@ -97,3 +97,58 @@ def test_naming_an_ignored_folder_scans_it(tmp_path):
97
97
  assert {os.path.basename(f.path) for f in scanner.scan_paths([str(tmp_path / "data")])} == {"dump.txt"}
98
98
  assert scanner.IGNORED == []
99
99
  assert found(tmp_path) == set() and len(scanner.IGNORED) == 1 # but scanning the repo root leaves it out
100
+
101
+
102
+ # ---- a scanned repository must never be able to run code through its own git config ----
103
+ posix = pytest.mark.skipif(sys.platform == "win32", reason="uses shell scripts")
104
+
105
+
106
+ def evil_script(tmp_path, name, body=""):
107
+ marker = tmp_path / "PWNED"
108
+ script = tmp_path / name
109
+ script.write_text(f"#!/bin/sh\ntouch {marker}\n{body}")
110
+ script.chmod(0o755)
111
+ return marker, script
112
+
113
+
114
+ def repo_with(tmp_path):
115
+ work = tmp_path / "repo"
116
+ work.mkdir()
117
+ git(work, "init", "-q")
118
+ git(work, "config", "user.email", "t@example.com")
119
+ git(work, "config", "user.name", "t")
120
+ return work
121
+
122
+
123
+ @posix
124
+ def test_scanning_a_repo_never_runs_its_fsmonitor(tmp_path):
125
+ marker, script = evil_script(tmp_path, "hook.sh")
126
+ work = repo_with(tmp_path)
127
+ git(work, "config", "core.fsmonitor", str(script))
128
+ (work / "a.py").write_text("x = 1\n")
129
+ scanner.scan_paths([str(work)])
130
+ assert not marker.exists()
131
+
132
+
133
+ @posix
134
+ def test_staged_and_history_scans_never_run_diff_drivers(tmp_path, monkeypatch):
135
+ marker, script = evil_script(tmp_path, "conv.sh", 'cat "$1"\n')
136
+ work = repo_with(tmp_path)
137
+ (work / ".gitattributes").write_text("*.py diff=evil\n")
138
+ git(work, "config", "diff.evil.textconv", str(script))
139
+ git(work, "config", "diff.external", str(script))
140
+ (work / "app.py").write_text(LINE)
141
+ git(work, "add", ".")
142
+ monkeypatch.chdir(work)
143
+ assert [f.kind for f in scanner.scan_staged()] == ["GitHub token"]
144
+ git(work, "commit", "-qm", "x")
145
+ assert [f.kind for f in scanner.scan_history()] == ["GitHub token"]
146
+ assert not marker.exists()
147
+
148
+
149
+ def test_folder_names_that_look_like_options_are_just_folders(tmp_path, monkeypatch):
150
+ monkeypatch.chdir(tmp_path)
151
+ odd = tmp_path / "--upload-pack=evil"
152
+ odd.mkdir()
153
+ (odd / "a.py").write_text(LINE)
154
+ assert [f.kind for f in scanner.scan_paths(["--upload-pack=evil"])] == ["GitHub token"]
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