push-guard 0.1.0__py3-none-any.whl
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.
- push_guard/__init__.py +5 -0
- push_guard/__main__.py +5 -0
- push_guard/guard.py +464 -0
- push_guard-0.1.0.dist-info/METADATA +118 -0
- push_guard-0.1.0.dist-info/RECORD +9 -0
- push_guard-0.1.0.dist-info/WHEEL +5 -0
- push_guard-0.1.0.dist-info/entry_points.txt +2 -0
- push_guard-0.1.0.dist-info/licenses/LICENSE +158 -0
- push_guard-0.1.0.dist-info/top_level.txt +1 -0
push_guard/__init__.py
ADDED
push_guard/__main__.py
ADDED
push_guard/guard.py
ADDED
|
@@ -0,0 +1,464 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import os
|
|
5
|
+
import re
|
|
6
|
+
import subprocess
|
|
7
|
+
import sys
|
|
8
|
+
from dataclasses import dataclass
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
ZERO_SHA = "0" * 40
|
|
13
|
+
|
|
14
|
+
PLACEHOLDER_WORDS = {
|
|
15
|
+
"changeme",
|
|
16
|
+
"example",
|
|
17
|
+
"placeholder",
|
|
18
|
+
"replace",
|
|
19
|
+
"sample",
|
|
20
|
+
"test",
|
|
21
|
+
"your",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
# Each entry: (rule_id, pattern, reason, high_confidence)
|
|
25
|
+
# high_confidence == True means the match is a provider-specific token *shape*
|
|
26
|
+
# (ghp_, github_pat_, sk-, AKIA/ASIA). A value matching one of these is a real
|
|
27
|
+
# secret even if it happens to contain a word like "test" or "your", so the
|
|
28
|
+
# placeholder filter MUST NOT suppress it. Only low-confidence/structural
|
|
29
|
+
# markers honor the placeholder filter.
|
|
30
|
+
SECRET_PATTERNS = [
|
|
31
|
+
(
|
|
32
|
+
"secret.github_fine_grained_token",
|
|
33
|
+
re.compile(r"github_pat_[A-Za-z0-9_]{20,}"),
|
|
34
|
+
"GitHub fine-grained token pattern",
|
|
35
|
+
True,
|
|
36
|
+
),
|
|
37
|
+
(
|
|
38
|
+
"secret.github_token",
|
|
39
|
+
re.compile(r"gh[pousr]_[A-Za-z0-9_]{20,}"),
|
|
40
|
+
"GitHub token pattern",
|
|
41
|
+
True,
|
|
42
|
+
),
|
|
43
|
+
(
|
|
44
|
+
"secret.openai_token",
|
|
45
|
+
re.compile(r"sk-[A-Za-z0-9]{20,}"),
|
|
46
|
+
"OpenAI-style token pattern",
|
|
47
|
+
True,
|
|
48
|
+
),
|
|
49
|
+
(
|
|
50
|
+
"secret.aws_access_key",
|
|
51
|
+
re.compile(r"\b(?:AKIA|ASIA)[A-Z0-9]{16}\b"),
|
|
52
|
+
"AWS access key pattern",
|
|
53
|
+
True,
|
|
54
|
+
),
|
|
55
|
+
(
|
|
56
|
+
"secret.private_key",
|
|
57
|
+
re.compile(r"-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----"),
|
|
58
|
+
"Private key block marker",
|
|
59
|
+
False,
|
|
60
|
+
),
|
|
61
|
+
]
|
|
62
|
+
|
|
63
|
+
# Keyword may be embedded in an underscore/dash-delimited identifier so that
|
|
64
|
+
# names like AWS_SECRET_ACCESS_KEY or CLIENT_SECRET_TOKEN are matched, not just
|
|
65
|
+
# bare `secret=`. The negative lookbehind keeps the keyword on a real boundary
|
|
66
|
+
# (start, space, `_`, `-`) instead of matching inside an unrelated word.
|
|
67
|
+
GENERIC_ASSIGNMENT = re.compile(
|
|
68
|
+
r"(?i)(?<![A-Za-z0-9])"
|
|
69
|
+
r"(?:api[_-]?key|access[_-]?token|auth[_-]?token|secret|password|passwd|pwd)"
|
|
70
|
+
r"(?:[_-][A-Za-z0-9]+)*"
|
|
71
|
+
r"\s*[:=]\s*['\"]?([^'\"\s]{20,})"
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
@dataclass(frozen=True)
|
|
76
|
+
class SecretFinding:
|
|
77
|
+
rule_id: str
|
|
78
|
+
path: str
|
|
79
|
+
line: int
|
|
80
|
+
reason: str
|
|
81
|
+
evidence: str
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class PushGuardInspectionError(RuntimeError):
|
|
85
|
+
"""Raised when Push Guard cannot inspect Git push content cleanly."""
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def scan_text_for_secrets(text: str, path: str = "<text>") -> list[SecretFinding]:
|
|
89
|
+
findings: list[SecretFinding] = []
|
|
90
|
+
for line_number, line in enumerate(text.splitlines(), start=1):
|
|
91
|
+
findings.extend(_scan_line(line, path, line_number))
|
|
92
|
+
return findings
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def scan_git_push(repo: str | Path, stdin_text: str) -> list[SecretFinding]:
|
|
96
|
+
repo_path = _resolve_git_root(Path(repo))
|
|
97
|
+
findings: list[SecretFinding] = []
|
|
98
|
+
for _local_ref, local_sha, _remote_ref, remote_sha in _parse_pre_push(stdin_text):
|
|
99
|
+
if local_sha == ZERO_SHA:
|
|
100
|
+
continue
|
|
101
|
+
diffs = _diffs_for_push_ref(repo_path, local_sha, remote_sha)
|
|
102
|
+
for diff_text in diffs:
|
|
103
|
+
findings.extend(_scan_diff(diff_text))
|
|
104
|
+
return findings
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def main(argv: list[str] | None = None) -> int:
|
|
108
|
+
argv = sys.argv[1:] if argv is None else argv
|
|
109
|
+
if argv and argv[0] == "install":
|
|
110
|
+
return _install_main(argv[1:])
|
|
111
|
+
if argv and argv[0] in {"-h", "--help"}:
|
|
112
|
+
_print_help()
|
|
113
|
+
return 0
|
|
114
|
+
|
|
115
|
+
# Backward-compatible pre-push mode. Existing hooks call:
|
|
116
|
+
# python -m push_guard --repo "$(git rev-parse --show-toplevel)"
|
|
117
|
+
return _pre_push_main(argv)
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _pre_push_main(argv: list[str]) -> int:
|
|
121
|
+
parser = argparse.ArgumentParser(
|
|
122
|
+
prog="push-guard",
|
|
123
|
+
description="Local pre-push secret guard. Blocks likely secret pushes.",
|
|
124
|
+
)
|
|
125
|
+
parser.add_argument(
|
|
126
|
+
"--repo",
|
|
127
|
+
default=".",
|
|
128
|
+
help="Repository path. Defaults to current directory.",
|
|
129
|
+
)
|
|
130
|
+
args = parser.parse_args(argv)
|
|
131
|
+
|
|
132
|
+
stdin_text = sys.stdin.read()
|
|
133
|
+
try:
|
|
134
|
+
findings = scan_git_push(args.repo, stdin_text)
|
|
135
|
+
except RuntimeError as exc:
|
|
136
|
+
print("Push Guard could not inspect this push.", file=sys.stderr)
|
|
137
|
+
print(str(exc), file=sys.stderr)
|
|
138
|
+
print("Blocking push because inspection failed.", file=sys.stderr)
|
|
139
|
+
return 1
|
|
140
|
+
|
|
141
|
+
if not findings:
|
|
142
|
+
return 0
|
|
143
|
+
|
|
144
|
+
print("Push Guard blocked this push.", file=sys.stderr)
|
|
145
|
+
print("Likely secret material matched. Values are redacted.", file=sys.stderr)
|
|
146
|
+
for finding in findings:
|
|
147
|
+
print(
|
|
148
|
+
f"- {finding.rule_id} at {finding.path}:{finding.line} "
|
|
149
|
+
f"({finding.reason}; {finding.evidence})",
|
|
150
|
+
file=sys.stderr,
|
|
151
|
+
)
|
|
152
|
+
print("Review locally, remove or rotate the secret, then retry.", file=sys.stderr)
|
|
153
|
+
return 1
|
|
154
|
+
|
|
155
|
+
|
|
156
|
+
def _install_main(argv: list[str]) -> int:
|
|
157
|
+
parser = argparse.ArgumentParser(
|
|
158
|
+
prog="push-guard install",
|
|
159
|
+
description="Install Push Guard as this repository's local pre-push hook.",
|
|
160
|
+
)
|
|
161
|
+
parser.add_argument(
|
|
162
|
+
"--repo",
|
|
163
|
+
default=".",
|
|
164
|
+
help="Repository path. Defaults to current directory.",
|
|
165
|
+
)
|
|
166
|
+
parser.add_argument(
|
|
167
|
+
"--force",
|
|
168
|
+
action="store_true",
|
|
169
|
+
help="Replace an existing Push Guard-managed pre-push hook.",
|
|
170
|
+
)
|
|
171
|
+
args = parser.parse_args(argv)
|
|
172
|
+
|
|
173
|
+
try:
|
|
174
|
+
hook_path = install_pre_push_hook(args.repo, force=args.force)
|
|
175
|
+
except RuntimeError as exc:
|
|
176
|
+
print(f"Push Guard install failed: {exc}", file=sys.stderr)
|
|
177
|
+
return 1
|
|
178
|
+
|
|
179
|
+
print(f"Push Guard installed: {hook_path}")
|
|
180
|
+
return 0
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def install_pre_push_hook(repo: str | Path = ".", *, force: bool = False) -> Path:
|
|
184
|
+
repo_path = _resolve_git_root(Path(repo))
|
|
185
|
+
hook_dir = repo_path / ".git" / "hooks"
|
|
186
|
+
hook_path = hook_dir / "pre-push"
|
|
187
|
+
hook_dir.mkdir(parents=True, exist_ok=True)
|
|
188
|
+
|
|
189
|
+
hook_body = _hook_body()
|
|
190
|
+
if hook_path.exists():
|
|
191
|
+
existing = hook_path.read_text(encoding="utf-8", errors="replace")
|
|
192
|
+
if existing == hook_body:
|
|
193
|
+
return hook_path
|
|
194
|
+
if "push_guard" not in existing and "push-guard" not in existing:
|
|
195
|
+
raise RuntimeError(
|
|
196
|
+
f"{hook_path} already exists. Chain it manually or rerun with --force."
|
|
197
|
+
)
|
|
198
|
+
if not force:
|
|
199
|
+
raise RuntimeError(
|
|
200
|
+
f"{hook_path} already exists. Rerun with --force to refresh it."
|
|
201
|
+
)
|
|
202
|
+
|
|
203
|
+
hook_path.write_text(hook_body, encoding="utf-8", newline="\n")
|
|
204
|
+
if os.name != "nt":
|
|
205
|
+
hook_path.chmod(0o755)
|
|
206
|
+
return hook_path
|
|
207
|
+
|
|
208
|
+
|
|
209
|
+
def _hook_body() -> str:
|
|
210
|
+
return (
|
|
211
|
+
"#!/bin/sh\n"
|
|
212
|
+
"# Installed by Push Guard. Local only; no network calls.\n"
|
|
213
|
+
'exec python -m push_guard --repo "$(git rev-parse --show-toplevel)"\n'
|
|
214
|
+
)
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
def _print_help() -> None:
|
|
218
|
+
print(
|
|
219
|
+
"usage: push-guard [--repo REPO]\n"
|
|
220
|
+
" push-guard install [--repo REPO] [--force]\n\n"
|
|
221
|
+
"Local pre-push secret guard. Run from a Git pre-push hook, or install\n"
|
|
222
|
+
"the hook with `push-guard install`."
|
|
223
|
+
)
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def _scan_line(line: str, path: str, line_number: int) -> list[SecretFinding]:
|
|
227
|
+
findings: list[SecretFinding] = []
|
|
228
|
+
|
|
229
|
+
for rule_id, pattern, reason, high_confidence in SECRET_PATTERNS:
|
|
230
|
+
for match in pattern.finditer(line):
|
|
231
|
+
# High-confidence provider token shapes are never suppressed by a
|
|
232
|
+
# placeholder word — a real ghp_/sk-/AKIA value that merely contains
|
|
233
|
+
# "test" or "your" is still a real secret and must be caught.
|
|
234
|
+
if not high_confidence and _looks_like_placeholder(match.group(0)):
|
|
235
|
+
continue
|
|
236
|
+
findings.append(
|
|
237
|
+
SecretFinding(
|
|
238
|
+
rule_id=rule_id,
|
|
239
|
+
path=path,
|
|
240
|
+
line=line_number,
|
|
241
|
+
reason=reason,
|
|
242
|
+
evidence="<redacted>",
|
|
243
|
+
)
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
# Only consider the lower-confidence generic-assignment rule when no
|
|
247
|
+
# specific token already matched this line. This avoids double-reporting a
|
|
248
|
+
# single leak (e.g. OPENAI_API_KEY=sk-...) while still catching secrets that
|
|
249
|
+
# only the generic rule can see (e.g. a 40-char AWS *secret* in
|
|
250
|
+
# AWS_SECRET_ACCESS_KEY=..., which has no provider prefix).
|
|
251
|
+
if not findings:
|
|
252
|
+
match = GENERIC_ASSIGNMENT.search(line)
|
|
253
|
+
if match and not _value_is_placeholder(match.group(1)):
|
|
254
|
+
findings.append(
|
|
255
|
+
SecretFinding(
|
|
256
|
+
rule_id="secret.generic_assignment",
|
|
257
|
+
path=path,
|
|
258
|
+
line=line_number,
|
|
259
|
+
reason="High-entropy-looking secret assignment",
|
|
260
|
+
evidence="<redacted>",
|
|
261
|
+
)
|
|
262
|
+
)
|
|
263
|
+
|
|
264
|
+
return findings
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
def _looks_like_placeholder(value: str) -> bool:
|
|
268
|
+
"""Substring check, used only for low-confidence/structural markers."""
|
|
269
|
+
lowered = value.lower()
|
|
270
|
+
return any(word in lowered for word in PLACEHOLDER_WORDS)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
def _value_is_placeholder(value: str) -> bool:
|
|
274
|
+
"""True only when an assigned value is *dominated* by placeholder text.
|
|
275
|
+
|
|
276
|
+
The earlier behaviour skipped any value that merely *contained* a
|
|
277
|
+
placeholder word (e.g. a real secret embedding "test"), which silently let
|
|
278
|
+
secrets through. Now a value counts as a placeholder only when it is an
|
|
279
|
+
obvious dummy shape, stacks two or more placeholder words, or is left with
|
|
280
|
+
almost nothing real after the placeholder words are removed. This biases a
|
|
281
|
+
pre-push seatbelt toward blocking — a verbose dummy may be flagged for
|
|
282
|
+
review, but a real secret with an embedded common word is no longer missed.
|
|
283
|
+
"""
|
|
284
|
+
lowered = value.lower()
|
|
285
|
+
# Bracketed dummies (<your-token>, [REDACTED]) or filler runs (xxxxxxxx).
|
|
286
|
+
if re.fullmatch(r"[<\[{(].*[>\]})]", value):
|
|
287
|
+
return True
|
|
288
|
+
if re.fullmatch(r"[x*._\-]{8,}", lowered):
|
|
289
|
+
return True
|
|
290
|
+
present = [word for word in PLACEHOLDER_WORDS if word in lowered]
|
|
291
|
+
if len(present) >= 2:
|
|
292
|
+
return True
|
|
293
|
+
residue = lowered
|
|
294
|
+
for word in present:
|
|
295
|
+
residue = residue.replace(word, "")
|
|
296
|
+
residue = re.sub(r"[^a-z0-9]", "", residue)
|
|
297
|
+
return len(residue) < 8
|
|
298
|
+
|
|
299
|
+
|
|
300
|
+
def _parse_pre_push(stdin_text: str) -> list[tuple[str, str, str, str]]:
|
|
301
|
+
refs: list[tuple[str, str, str, str]] = []
|
|
302
|
+
for line in stdin_text.splitlines():
|
|
303
|
+
parts = line.split()
|
|
304
|
+
if len(parts) != 4:
|
|
305
|
+
continue
|
|
306
|
+
refs.append((parts[0], parts[1], parts[2], parts[3]))
|
|
307
|
+
return refs
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
def _diffs_for_push_ref(repo: Path, local_sha: str, remote_sha: str) -> list[str]:
|
|
311
|
+
if remote_sha == ZERO_SHA:
|
|
312
|
+
commits = _run_git(
|
|
313
|
+
repo,
|
|
314
|
+
["rev-list", "--reverse", local_sha, "--not", "--remotes"],
|
|
315
|
+
).splitlines()
|
|
316
|
+
if not commits:
|
|
317
|
+
commits = [local_sha]
|
|
318
|
+
return [
|
|
319
|
+
_run_git(repo, ["show", "--format=", "--unified=0", "--no-ext-diff", commit])
|
|
320
|
+
for commit in commits
|
|
321
|
+
]
|
|
322
|
+
|
|
323
|
+
return [
|
|
324
|
+
_run_git(
|
|
325
|
+
repo,
|
|
326
|
+
[
|
|
327
|
+
"diff",
|
|
328
|
+
"--unified=0",
|
|
329
|
+
"--no-ext-diff",
|
|
330
|
+
"--diff-filter=ACMRT",
|
|
331
|
+
remote_sha,
|
|
332
|
+
local_sha,
|
|
333
|
+
],
|
|
334
|
+
)
|
|
335
|
+
]
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def _scan_diff(diff_text: str) -> list[SecretFinding]:
|
|
339
|
+
findings: list[SecretFinding] = []
|
|
340
|
+
current_path = "<diff>"
|
|
341
|
+
new_line = 0
|
|
342
|
+
in_hunk = False
|
|
343
|
+
for line in diff_text.splitlines():
|
|
344
|
+
if line.startswith("+++ b/"):
|
|
345
|
+
current_path = line[6:]
|
|
346
|
+
continue
|
|
347
|
+
if line.startswith("@@"):
|
|
348
|
+
new_line = _parse_hunk_new_line(line)
|
|
349
|
+
in_hunk = True
|
|
350
|
+
continue
|
|
351
|
+
if not in_hunk:
|
|
352
|
+
continue
|
|
353
|
+
if line.startswith("+") and not line.startswith("+++"):
|
|
354
|
+
findings.extend(_scan_line(line[1:], current_path, max(new_line, 1)))
|
|
355
|
+
new_line += 1
|
|
356
|
+
continue
|
|
357
|
+
if line.startswith("-") and not line.startswith("---"):
|
|
358
|
+
continue
|
|
359
|
+
if line.startswith("\\ No newline"):
|
|
360
|
+
continue
|
|
361
|
+
new_line += 1
|
|
362
|
+
return findings
|
|
363
|
+
|
|
364
|
+
|
|
365
|
+
def _parse_hunk_new_line(line: str) -> int:
|
|
366
|
+
match = re.search(r"\+(\d+)", line)
|
|
367
|
+
if not match:
|
|
368
|
+
return 0
|
|
369
|
+
return int(match.group(1))
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
def _resolve_git_root(repo: Path) -> Path:
|
|
373
|
+
try:
|
|
374
|
+
completed = _run_rev_parse_show_toplevel(repo, repo)
|
|
375
|
+
except subprocess.CalledProcessError as exc:
|
|
376
|
+
dubious_root = _parse_dubious_ownership_root(exc.stderr)
|
|
377
|
+
if dubious_root:
|
|
378
|
+
try:
|
|
379
|
+
completed = _run_rev_parse_show_toplevel(repo, dubious_root)
|
|
380
|
+
except subprocess.CalledProcessError as retry_exc:
|
|
381
|
+
raise _git_inspection_error(
|
|
382
|
+
"git rev-parse --show-toplevel", retry_exc
|
|
383
|
+
) from retry_exc
|
|
384
|
+
else:
|
|
385
|
+
raise _git_inspection_error("git rev-parse --show-toplevel", exc) from exc
|
|
386
|
+
|
|
387
|
+
root = completed.stdout.strip()
|
|
388
|
+
if not root:
|
|
389
|
+
raise PushGuardInspectionError("git rev-parse --show-toplevel returned no path")
|
|
390
|
+
return Path(root)
|
|
391
|
+
|
|
392
|
+
|
|
393
|
+
def _run_rev_parse_show_toplevel(
|
|
394
|
+
repo: Path, safe_directory: Path
|
|
395
|
+
) -> subprocess.CompletedProcess[str]:
|
|
396
|
+
return subprocess.run(
|
|
397
|
+
_git_command(repo, ["rev-parse", "--show-toplevel"], safe_directory),
|
|
398
|
+
check=True,
|
|
399
|
+
text=True,
|
|
400
|
+
encoding="utf-8",
|
|
401
|
+
errors="replace",
|
|
402
|
+
stdout=subprocess.PIPE,
|
|
403
|
+
stderr=subprocess.PIPE,
|
|
404
|
+
)
|
|
405
|
+
|
|
406
|
+
|
|
407
|
+
def _git_inspection_error(
|
|
408
|
+
command: str, exc: subprocess.CalledProcessError
|
|
409
|
+
) -> PushGuardInspectionError:
|
|
410
|
+
stderr = _first_stderr_line(exc.stderr)
|
|
411
|
+
detail = f": {stderr}" if stderr else ""
|
|
412
|
+
return PushGuardInspectionError(
|
|
413
|
+
f"{command} failed with exit {exc.returncode}{detail}"
|
|
414
|
+
)
|
|
415
|
+
|
|
416
|
+
|
|
417
|
+
def _parse_dubious_ownership_root(stderr: str | None) -> Path | None:
|
|
418
|
+
if not stderr or "dubious ownership" not in stderr:
|
|
419
|
+
return None
|
|
420
|
+
match = re.search(r"repository at '([^']+)'", stderr)
|
|
421
|
+
if not match:
|
|
422
|
+
return None
|
|
423
|
+
return Path(match.group(1))
|
|
424
|
+
|
|
425
|
+
|
|
426
|
+
def _run_git(repo: Path, args: list[str]) -> str:
|
|
427
|
+
try:
|
|
428
|
+
completed = subprocess.run(
|
|
429
|
+
_git_command(repo, args, repo),
|
|
430
|
+
check=True,
|
|
431
|
+
text=True,
|
|
432
|
+
encoding="utf-8",
|
|
433
|
+
errors="replace",
|
|
434
|
+
stdout=subprocess.PIPE,
|
|
435
|
+
stderr=subprocess.PIPE,
|
|
436
|
+
)
|
|
437
|
+
except subprocess.CalledProcessError as exc:
|
|
438
|
+
stderr = _first_stderr_line(exc.stderr)
|
|
439
|
+
detail = f": {stderr}" if stderr else ""
|
|
440
|
+
raise PushGuardInspectionError(
|
|
441
|
+
f"git {' '.join(args)} failed with exit {exc.returncode}{detail}"
|
|
442
|
+
) from exc
|
|
443
|
+
return completed.stdout
|
|
444
|
+
|
|
445
|
+
|
|
446
|
+
def _git_command(repo: Path, args: list[str], safe_directory: Path) -> list[str]:
|
|
447
|
+
return [
|
|
448
|
+
"git",
|
|
449
|
+
"-c",
|
|
450
|
+
f"safe.directory={safe_directory}",
|
|
451
|
+
"-C",
|
|
452
|
+
str(repo),
|
|
453
|
+
*args,
|
|
454
|
+
]
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def _first_stderr_line(stderr: str | None) -> str:
|
|
458
|
+
if not stderr:
|
|
459
|
+
return ""
|
|
460
|
+
for line in stderr.splitlines():
|
|
461
|
+
stripped = line.strip()
|
|
462
|
+
if stripped:
|
|
463
|
+
return stripped
|
|
464
|
+
return ""
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: push-guard
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Local pre-push guard for likely secret leaks.
|
|
5
|
+
Author: Dragon Lady
|
|
6
|
+
License-Expression: Apache-2.0
|
|
7
|
+
Project-URL: Homepage, https://github.com/Dragon-Lady/push-guard
|
|
8
|
+
Project-URL: Repository, https://github.com/Dragon-Lady/push-guard
|
|
9
|
+
Project-URL: Issues, https://github.com/Dragon-Lady/push-guard/issues
|
|
10
|
+
Keywords: git,pre-push,secrets,security,credentials,developer-tools
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Environment :: Console
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Security
|
|
16
|
+
Classifier: Topic :: Software Development :: Version Control :: Git
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Description-Content-Type: text/markdown
|
|
19
|
+
License-File: LICENSE
|
|
20
|
+
Dynamic: license-file
|
|
21
|
+
|
|
22
|
+
# Push Guard
|
|
23
|
+
|
|
24
|
+
Push Guard is a local Git `pre-push` guard for likely secret leaks.
|
|
25
|
+
|
|
26
|
+
It scans the content being pushed, reports likely secret patterns, redacts all
|
|
27
|
+
matched values, and exits nonzero so Git blocks the push.
|
|
28
|
+
|
|
29
|
+
> Built and maintained by Dragon Lady - [github.com/Dragon-Lady](https://github.com/Dragon-Lady) - X: [@answerislove2](https://x.com/answerislove2)
|
|
30
|
+
|
|
31
|
+
## Posture
|
|
32
|
+
|
|
33
|
+
- Local only.
|
|
34
|
+
- No network calls.
|
|
35
|
+
- No package installs.
|
|
36
|
+
- No target file mutation.
|
|
37
|
+
- No secret values printed.
|
|
38
|
+
- No tokens, keys, secrets, credentials, file contents, repository contents, or
|
|
39
|
+
user data are saved by Push Guard.
|
|
40
|
+
- Findings store only rule IDs, file paths, line numbers, reasons, and the
|
|
41
|
+
literal placeholder `<redacted>`.
|
|
42
|
+
- Uses the `git` subprocess only to read commit diffs.
|
|
43
|
+
- No mutation through Git and no other subprocess execution.
|
|
44
|
+
- No claim that a repository is clean.
|
|
45
|
+
|
|
46
|
+
Blocking a push is Git's response to the advisory. Push Guard remains read-only
|
|
47
|
+
and does not mutate files. Override is available with `git push --no-verify`
|
|
48
|
+
when the matched value is known not to be a secret.
|
|
49
|
+
|
|
50
|
+
Push Guard does not send data to any service. It does not phone home, collect
|
|
51
|
+
telemetry, upload reports, write scan results by default, or retain copies of
|
|
52
|
+
matched values.
|
|
53
|
+
|
|
54
|
+
## Current Signals
|
|
55
|
+
|
|
56
|
+
- GitHub classic token prefixes: `ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`
|
|
57
|
+
- GitHub fine-grained token prefix: `github_pat_`
|
|
58
|
+
- OpenAI-style `sk-...` tokens
|
|
59
|
+
- AWS access key IDs: `AKIA...` / `ASIA...`
|
|
60
|
+
- private key block markers
|
|
61
|
+
- generic long `api_key`, `token`, `secret`, or `password` assignments,
|
|
62
|
+
including underscore/dash-delimited names such as `AWS_SECRET_ACCESS_KEY`
|
|
63
|
+
|
|
64
|
+
All evidence is redacted as `<redacted>`.
|
|
65
|
+
|
|
66
|
+
## Install
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
pip install push-guard
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## Install A Repo Hook
|
|
73
|
+
|
|
74
|
+
Install per repository. Do not install globally.
|
|
75
|
+
|
|
76
|
+
From the repository you want to protect:
|
|
77
|
+
|
|
78
|
+
```sh
|
|
79
|
+
push-guard install
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
If a `pre-push` hook already exists, Push Guard refuses to overwrite it. Preserve
|
|
83
|
+
and chain existing hooks intentionally, or rerun with `--force` only when you are
|
|
84
|
+
refreshing a Push Guard-managed hook.
|
|
85
|
+
|
|
86
|
+
Manual hook body, for teams that prefer to wire hooks themselves:
|
|
87
|
+
|
|
88
|
+
```sh
|
|
89
|
+
#!/bin/sh
|
|
90
|
+
exec python -m push_guard --repo "$(git rev-parse --show-toplevel)"
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
## Run Manually
|
|
94
|
+
|
|
95
|
+
The CLI expects Git `pre-push` input on stdin. Manual dry runs are best done from
|
|
96
|
+
an actual hook or a test fixture.
|
|
97
|
+
|
|
98
|
+
```sh
|
|
99
|
+
python -m push_guard --repo /path/to/repo
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
## Known Limits
|
|
103
|
+
|
|
104
|
+
- Pattern-based detection can miss secrets or flag non-secrets.
|
|
105
|
+
- Long non-secret identifiers in assignments such as
|
|
106
|
+
`secret = mySuperLongFunctionCallHereWithNoSpaces` can match the generic
|
|
107
|
+
assignment rule.
|
|
108
|
+
- If a hook is installed from a Git subdirectory, Git may resolve `--repo` to a
|
|
109
|
+
parent repository root. This is acceptable for current diff-only scanning, but
|
|
110
|
+
future path-relative features such as allowlists or report output must resolve
|
|
111
|
+
and document the canonical Git root first.
|
|
112
|
+
- It blocks likely matches; it does not rotate exposed credentials.
|
|
113
|
+
- If a real secret was committed, rotate from a clean context after removing it.
|
|
114
|
+
- It should be treated as a seatbelt, not a guarantee.
|
|
115
|
+
|
|
116
|
+
## License
|
|
117
|
+
|
|
118
|
+
Apache-2.0.
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
push_guard/__init__.py,sha256=-LQ2GXnUOPFichM1xVvou_3aQNZ_BTGXDf8xDoqQllo,172
|
|
2
|
+
push_guard/__main__.py,sha256=Dk8SPCjS-zcBmY60AOrhqtUcfZvyAfOevLrEoZ2tUb8,82
|
|
3
|
+
push_guard/guard.py,sha256=4viywbQxhgXOcYoaym3z14xdAeVxKFecKuJy8P4leZw,15308
|
|
4
|
+
push_guard-0.1.0.dist-info/licenses/LICENSE,sha256=ESl-8MaqG02vRjWK7nPEq7XMCoy_efK_YSTPnC6TUcE,9074
|
|
5
|
+
push_guard-0.1.0.dist-info/METADATA,sha256=zz9FzQFz759BNJvW_Hr1Y7_SHwG_j1n0cy7VDgORbIo,4106
|
|
6
|
+
push_guard-0.1.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
|
|
7
|
+
push_guard-0.1.0.dist-info/entry_points.txt,sha256=jFqqHJ_iwnwmMI0MHvafEvz8C71DVx1lPKFtmMgzZbY,53
|
|
8
|
+
push_guard-0.1.0.dist-info/top_level.txt,sha256=ydUXPto8h_dB-rV76K00psvLo-6FBj-NaTQMDQG9VK8,11
|
|
9
|
+
push_guard-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,158 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and
|
|
10
|
+
distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright
|
|
13
|
+
owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities
|
|
16
|
+
that control, are controlled by, or are under common control with that entity.
|
|
17
|
+
For the purposes of this definition, "control" means (i) the power, direct or
|
|
18
|
+
indirect, to cause the direction or management of such entity, whether by
|
|
19
|
+
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
20
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
21
|
+
|
|
22
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
|
23
|
+
permissions granted by this License.
|
|
24
|
+
|
|
25
|
+
"Source" form shall mean the preferred form for making modifications, including
|
|
26
|
+
but not limited to software source code, documentation source, and configuration
|
|
27
|
+
files.
|
|
28
|
+
|
|
29
|
+
"Object" form shall mean any form resulting from mechanical transformation or
|
|
30
|
+
translation of a Source form, including but not limited to compiled object code,
|
|
31
|
+
generated documentation, and conversions to other media types.
|
|
32
|
+
|
|
33
|
+
"Work" shall mean the work of authorship, whether in Source or Object form,
|
|
34
|
+
made available under the License, as indicated by a copyright notice that is
|
|
35
|
+
included in or attached to the work.
|
|
36
|
+
|
|
37
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that
|
|
38
|
+
is based on (or derived from) the Work and for which the editorial revisions,
|
|
39
|
+
annotations, elaborations, or other modifications represent, as a whole, an
|
|
40
|
+
original work of authorship. For the purposes of this License, Derivative Works
|
|
41
|
+
shall not include works that remain separable from, or merely link (or bind by
|
|
42
|
+
name) to the interfaces of, the Work and Derivative Works thereof.
|
|
43
|
+
|
|
44
|
+
"Contribution" shall mean any work of authorship, including the original
|
|
45
|
+
version of the Work and any modifications or additions to that Work or
|
|
46
|
+
Derivative Works thereof, that is intentionally submitted to Licensor for
|
|
47
|
+
inclusion in the Work by the copyright owner or by an individual or Legal Entity
|
|
48
|
+
authorized to submit on behalf of the copyright owner. For the purposes of this
|
|
49
|
+
definition, "submitted" means any form of electronic, verbal, or written
|
|
50
|
+
communication sent to the Licensor or its representatives, including but not
|
|
51
|
+
limited to communication on electronic mailing lists, source code control
|
|
52
|
+
systems, and issue tracking systems that are managed by, or on behalf of, the
|
|
53
|
+
Licensor for the purpose of discussing and improving the Work, but excluding
|
|
54
|
+
communication that is conspicuously marked or otherwise designated in writing by
|
|
55
|
+
the copyright owner as "Not a Contribution."
|
|
56
|
+
|
|
57
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
|
|
58
|
+
of whom a Contribution has been received by Licensor and subsequently
|
|
59
|
+
incorporated within the Work.
|
|
60
|
+
|
|
61
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this
|
|
62
|
+
License, each Contributor hereby grants to You a perpetual, worldwide,
|
|
63
|
+
non-exclusive, no-charge, royalty-free, irrevocable copyright license to
|
|
64
|
+
reproduce, prepare Derivative Works of, publicly display, publicly perform,
|
|
65
|
+
sublicense, and distribute the Work and such Derivative Works in Source or
|
|
66
|
+
Object form.
|
|
67
|
+
|
|
68
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License,
|
|
69
|
+
each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
|
|
70
|
+
no-charge, royalty-free, irrevocable patent license to make, have made, use,
|
|
71
|
+
offer to sell, sell, import, and otherwise transfer the Work, where such license
|
|
72
|
+
applies only to those patent claims licensable by such Contributor that are
|
|
73
|
+
necessarily infringed by their Contribution(s) alone or by combination of their
|
|
74
|
+
Contribution(s) with the Work to which such Contribution(s) was submitted. If
|
|
75
|
+
You institute patent litigation against any entity (including a cross-claim or
|
|
76
|
+
counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated
|
|
77
|
+
within the Work constitutes direct or contributory patent infringement, then any
|
|
78
|
+
patent licenses granted to You under this License for that Work shall terminate
|
|
79
|
+
as of the date such litigation is filed.
|
|
80
|
+
|
|
81
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or
|
|
82
|
+
Derivative Works thereof in any medium, with or without modifications, and in
|
|
83
|
+
Source or Object form, provided that You meet the following conditions:
|
|
84
|
+
|
|
85
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of
|
|
86
|
+
this License; and
|
|
87
|
+
|
|
88
|
+
(b) You must cause any modified files to carry prominent notices stating that
|
|
89
|
+
You changed the files; and
|
|
90
|
+
|
|
91
|
+
(c) You must retain, in the Source form of any Derivative Works that You
|
|
92
|
+
distribute, all copyright, patent, trademark, and attribution notices from the
|
|
93
|
+
Source form of the Work, excluding those notices that do not pertain to any part
|
|
94
|
+
of the Derivative Works; and
|
|
95
|
+
|
|
96
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then
|
|
97
|
+
any Derivative Works that You distribute must include a readable copy of the
|
|
98
|
+
attribution notices contained within such NOTICE file, excluding those notices
|
|
99
|
+
that do not pertain to any part of the Derivative Works, in at least one of the
|
|
100
|
+
following places: within a NOTICE text file distributed as part of the
|
|
101
|
+
Derivative Works; within the Source form or documentation, if provided along
|
|
102
|
+
with the Derivative Works; or, within a display generated by the Derivative
|
|
103
|
+
Works, if and wherever such third-party notices normally appear. The contents of
|
|
104
|
+
the NOTICE file are for informational purposes only and do not modify the
|
|
105
|
+
License. You may add Your own attribution notices within Derivative Works that
|
|
106
|
+
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
|
107
|
+
provided that such additional attribution notices cannot be construed as
|
|
108
|
+
modifying the License.
|
|
109
|
+
|
|
110
|
+
You may add Your own copyright statement to Your modifications and may provide
|
|
111
|
+
additional or different license terms and conditions for use, reproduction, or
|
|
112
|
+
distribution of Your modifications, or for any such Derivative Works as a whole,
|
|
113
|
+
provided Your use, reproduction, and distribution of the Work otherwise complies
|
|
114
|
+
with the conditions stated in this License.
|
|
115
|
+
|
|
116
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any
|
|
117
|
+
Contribution intentionally submitted for inclusion in the Work by You to the
|
|
118
|
+
Licensor shall be under the terms and conditions of this License, without any
|
|
119
|
+
additional terms or conditions. Notwithstanding the above, nothing herein shall
|
|
120
|
+
supersede or modify the terms of any separate license agreement you may have
|
|
121
|
+
executed with Licensor regarding such Contributions.
|
|
122
|
+
|
|
123
|
+
6. Trademarks. This License does not grant permission to use the trade names,
|
|
124
|
+
trademarks, service marks, or product names of the Licensor, except as required
|
|
125
|
+
for reasonable and customary use in describing the origin of the Work and
|
|
126
|
+
reproducing the content of the NOTICE file.
|
|
127
|
+
|
|
128
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
|
|
129
|
+
writing, Licensor provides the Work (and each Contributor provides its
|
|
130
|
+
Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
|
|
131
|
+
KIND, either express or implied, including, without limitation, any warranties or
|
|
132
|
+
conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
133
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
134
|
+
appropriateness of using or redistributing the Work and assume any risks
|
|
135
|
+
associated with Your exercise of permissions under this License.
|
|
136
|
+
|
|
137
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in
|
|
138
|
+
tort (including negligence), contract, or otherwise, unless required by
|
|
139
|
+
applicable law (such as deliberate and grossly negligent acts) or agreed to in
|
|
140
|
+
writing, shall any Contributor be liable to You for damages, including any
|
|
141
|
+
direct, indirect, special, incidental, or consequential damages of any character
|
|
142
|
+
arising as a result of this License or out of the use or inability to use the
|
|
143
|
+
Work (including but not limited to damages for loss of goodwill, work stoppage,
|
|
144
|
+
computer failure or malfunction, or any and all other commercial damages or
|
|
145
|
+
losses), even if such Contributor has been advised of the possibility of such
|
|
146
|
+
damages.
|
|
147
|
+
|
|
148
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or
|
|
149
|
+
Derivative Works thereof, You may choose to offer, and charge a fee for,
|
|
150
|
+
acceptance of support, warranty, indemnity, or other liability obligations
|
|
151
|
+
and/or rights consistent with this License. However, in accepting such
|
|
152
|
+
obligations, You may act only on Your own behalf and on Your sole
|
|
153
|
+
responsibility, not on behalf of any other Contributor, and only if You agree to
|
|
154
|
+
indemnify, defend, and hold each Contributor harmless for any liability incurred
|
|
155
|
+
by, or claims asserted against, such Contributor by reason of your accepting any
|
|
156
|
+
such warranty or additional liability.
|
|
157
|
+
|
|
158
|
+
END OF TERMS AND CONDITIONS
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
push_guard
|