push-guard 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,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,97 @@
1
+ # Push Guard
2
+
3
+ Push Guard is a local Git `pre-push` guard for likely secret leaks.
4
+
5
+ It scans the content being pushed, reports likely secret patterns, redacts all
6
+ matched values, and exits nonzero so Git blocks the push.
7
+
8
+ > Built and maintained by Dragon Lady - [github.com/Dragon-Lady](https://github.com/Dragon-Lady) - X: [@answerislove2](https://x.com/answerislove2)
9
+
10
+ ## Posture
11
+
12
+ - Local only.
13
+ - No network calls.
14
+ - No package installs.
15
+ - No target file mutation.
16
+ - No secret values printed.
17
+ - No tokens, keys, secrets, credentials, file contents, repository contents, or
18
+ user data are saved by Push Guard.
19
+ - Findings store only rule IDs, file paths, line numbers, reasons, and the
20
+ literal placeholder `<redacted>`.
21
+ - Uses the `git` subprocess only to read commit diffs.
22
+ - No mutation through Git and no other subprocess execution.
23
+ - No claim that a repository is clean.
24
+
25
+ Blocking a push is Git's response to the advisory. Push Guard remains read-only
26
+ and does not mutate files. Override is available with `git push --no-verify`
27
+ when the matched value is known not to be a secret.
28
+
29
+ Push Guard does not send data to any service. It does not phone home, collect
30
+ telemetry, upload reports, write scan results by default, or retain copies of
31
+ matched values.
32
+
33
+ ## Current Signals
34
+
35
+ - GitHub classic token prefixes: `ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`
36
+ - GitHub fine-grained token prefix: `github_pat_`
37
+ - OpenAI-style `sk-...` tokens
38
+ - AWS access key IDs: `AKIA...` / `ASIA...`
39
+ - private key block markers
40
+ - generic long `api_key`, `token`, `secret`, or `password` assignments,
41
+ including underscore/dash-delimited names such as `AWS_SECRET_ACCESS_KEY`
42
+
43
+ All evidence is redacted as `<redacted>`.
44
+
45
+ ## Install
46
+
47
+ ```sh
48
+ pip install push-guard
49
+ ```
50
+
51
+ ## Install A Repo Hook
52
+
53
+ Install per repository. Do not install globally.
54
+
55
+ From the repository you want to protect:
56
+
57
+ ```sh
58
+ push-guard install
59
+ ```
60
+
61
+ If a `pre-push` hook already exists, Push Guard refuses to overwrite it. Preserve
62
+ and chain existing hooks intentionally, or rerun with `--force` only when you are
63
+ refreshing a Push Guard-managed hook.
64
+
65
+ Manual hook body, for teams that prefer to wire hooks themselves:
66
+
67
+ ```sh
68
+ #!/bin/sh
69
+ exec python -m push_guard --repo "$(git rev-parse --show-toplevel)"
70
+ ```
71
+
72
+ ## Run Manually
73
+
74
+ The CLI expects Git `pre-push` input on stdin. Manual dry runs are best done from
75
+ an actual hook or a test fixture.
76
+
77
+ ```sh
78
+ python -m push_guard --repo /path/to/repo
79
+ ```
80
+
81
+ ## Known Limits
82
+
83
+ - Pattern-based detection can miss secrets or flag non-secrets.
84
+ - Long non-secret identifiers in assignments such as
85
+ `secret = mySuperLongFunctionCallHereWithNoSpaces` can match the generic
86
+ assignment rule.
87
+ - If a hook is installed from a Git subdirectory, Git may resolve `--repo` to a
88
+ parent repository root. This is acceptable for current diff-only scanning, but
89
+ future path-relative features such as allowlists or report output must resolve
90
+ and document the canonical Git root first.
91
+ - It blocks likely matches; it does not rotate exposed credentials.
92
+ - If a real secret was committed, rotate from a clean context after removing it.
93
+ - It should be treated as a seatbelt, not a guarantee.
94
+
95
+ ## License
96
+
97
+ Apache-2.0.
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=68"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "push-guard"
7
+ version = "0.1.0"
8
+ description = "Local pre-push guard for likely secret leaks."
9
+ readme = "README.md"
10
+ requires-python = ">=3.11"
11
+ license = "Apache-2.0"
12
+ authors = [{ name = "Dragon Lady" }]
13
+ keywords = ["git", "pre-push", "secrets", "security", "credentials", "developer-tools"]
14
+ classifiers = [
15
+ "Development Status :: 3 - Alpha",
16
+ "Environment :: Console",
17
+ "Intended Audience :: Developers",
18
+ "Programming Language :: Python :: 3",
19
+ "Topic :: Security",
20
+ "Topic :: Software Development :: Version Control :: Git",
21
+ ]
22
+
23
+ [project.urls]
24
+ Homepage = "https://github.com/Dragon-Lady/push-guard"
25
+ Repository = "https://github.com/Dragon-Lady/push-guard"
26
+ Issues = "https://github.com/Dragon-Lady/push-guard/issues"
27
+
28
+ [project.scripts]
29
+ push-guard = "push_guard.guard:main"
30
+
31
+ [tool.setuptools.packages.find]
32
+ where = ["src"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,5 @@
1
+ """Push Guard public API."""
2
+
3
+ from .guard import SecretFinding, scan_git_push, scan_text_for_secrets
4
+
5
+ __all__ = ["SecretFinding", "scan_git_push", "scan_text_for_secrets"]
@@ -0,0 +1,5 @@
1
+ from .guard import main
2
+
3
+
4
+ if __name__ == "__main__":
5
+ raise SystemExit(main())
@@ -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,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/push_guard/__init__.py
5
+ src/push_guard/__main__.py
6
+ src/push_guard/guard.py
7
+ src/push_guard.egg-info/PKG-INFO
8
+ src/push_guard.egg-info/SOURCES.txt
9
+ src/push_guard.egg-info/dependency_links.txt
10
+ src/push_guard.egg-info/entry_points.txt
11
+ src/push_guard.egg-info/top_level.txt
12
+ tests/test_guard.py
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ push-guard = push_guard.guard:main
@@ -0,0 +1 @@
1
+ push_guard
@@ -0,0 +1,289 @@
1
+ import unittest
2
+ from io import StringIO
3
+ from pathlib import Path
4
+ from subprocess import CalledProcessError, CompletedProcess
5
+ from tempfile import TemporaryDirectory
6
+ from unittest.mock import patch
7
+
8
+ from push_guard.guard import (
9
+ _resolve_git_root,
10
+ _scan_diff,
11
+ install_pre_push_hook,
12
+ main,
13
+ scan_text_for_secrets,
14
+ )
15
+
16
+
17
+ class PushGuardTests(unittest.TestCase):
18
+ def test_detects_github_tokens_without_returning_secret_value(self):
19
+ secret = "ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJ"
20
+ findings = scan_text_for_secrets(f"token={secret}", path="example.env")
21
+
22
+ self.assertEqual(1, len(findings))
23
+ self.assertEqual("secret.github_token", findings[0].rule_id)
24
+ self.assertEqual("example.env", findings[0].path)
25
+ self.assertNotIn(secret, findings[0].evidence)
26
+ self.assertIn("redacted", findings[0].evidence.lower())
27
+
28
+ def test_detects_github_fine_grained_token_without_returning_secret_value(self):
29
+ secret = "github_pat_11AAAAAAA0abcdefghijklmnopqrstuvwxyzABCDEFGHI"
30
+ findings = scan_text_for_secrets(secret, path="notes.txt")
31
+
32
+ self.assertEqual(1, len(findings))
33
+ self.assertEqual("secret.github_fine_grained_token", findings[0].rule_id)
34
+ self.assertNotIn(secret, findings[0].evidence)
35
+
36
+ def test_detects_private_key_block_without_returning_body(self):
37
+ text = (
38
+ "-----BEGIN OPENSSH PRIVATE KEY-----\n"
39
+ "abc123abc123abc123abc123\n"
40
+ "-----END OPENSSH PRIVATE KEY-----\n"
41
+ )
42
+ findings = scan_text_for_secrets(text, path="id_key")
43
+
44
+ self.assertEqual(1, len(findings))
45
+ self.assertEqual("secret.private_key", findings[0].rule_id)
46
+ self.assertNotIn("abc123abc123abc123abc123", findings[0].evidence)
47
+
48
+ def test_detects_openai_style_token_without_returning_secret_value(self):
49
+ secret = "sk-abcdefghijklmnopqrstuvwxyzABCDEF"
50
+ findings = scan_text_for_secrets(f"OPENAI_API_KEY={secret}", path=".env")
51
+
52
+ self.assertEqual(1, len(findings))
53
+ self.assertEqual("secret.openai_token", findings[0].rule_id)
54
+ self.assertNotIn(secret, findings[0].evidence)
55
+
56
+ def test_detects_aws_access_key_without_returning_secret_value(self):
57
+ secret = "AKIAABCDEFGHIJKLMNOP"
58
+ findings = scan_text_for_secrets(f"AWS_ACCESS_KEY_ID={secret}", path=".env")
59
+
60
+ self.assertEqual(1, len(findings))
61
+ self.assertEqual("secret.aws_access_key", findings[0].rule_id)
62
+ self.assertNotIn(secret, findings[0].evidence)
63
+
64
+ def test_detects_generic_secret_assignment_without_returning_secret_value(self):
65
+ secret = "superlongsecretvalue1234567890"
66
+ findings = scan_text_for_secrets(f"api_key = '{secret}'", path="config.py")
67
+
68
+ self.assertEqual(1, len(findings))
69
+ self.assertEqual("secret.generic_assignment", findings[0].rule_id)
70
+ self.assertNotIn(secret, findings[0].evidence)
71
+
72
+ def test_ignores_obvious_placeholders(self):
73
+ text = "\n".join(
74
+ [
75
+ "api_key=YOUR_API_KEY_HERE",
76
+ "token=example-token-placeholder",
77
+ "password=changeme",
78
+ ]
79
+ )
80
+ findings = scan_text_for_secrets(text, path="README.md")
81
+
82
+ self.assertEqual([], findings)
83
+
84
+ def test_specific_token_is_not_hidden_by_placeholder_comment(self):
85
+ secret = "ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJ"
86
+ findings = scan_text_for_secrets(
87
+ f'token = "{secret}" # test this config',
88
+ path="config.py",
89
+ )
90
+
91
+ self.assertEqual(1, len(findings))
92
+ self.assertEqual("secret.github_token", findings[0].rule_id)
93
+ self.assertNotIn(secret, findings[0].evidence)
94
+
95
+ def test_token_shape_with_embedded_placeholder_word_is_detected(self):
96
+ # A real ghp_ token whose own characters contain "test" must NOT be
97
+ # suppressed by the placeholder filter (the original false-negative).
98
+ secret = "ghp_test" + "a" * 30
99
+ findings = scan_text_for_secrets(secret, path="config.py")
100
+
101
+ self.assertEqual(1, len(findings))
102
+ self.assertEqual("secret.github_token", findings[0].rule_id)
103
+ self.assertNotIn(secret, findings[0].evidence)
104
+
105
+ def test_detects_underscored_secret_assignment(self):
106
+ # AWS_SECRET_ACCESS_KEY holds a 40-ish char secret with no provider
107
+ # prefix; only the generic rule can see it, and the underscores must not
108
+ # hide the `secret` keyword.
109
+ secret = "abcdEFGH1234ijklMNOP5678qrstUVWX"
110
+ findings = scan_text_for_secrets(
111
+ f"AWS_SECRET_ACCESS_KEY={secret}", path=".env"
112
+ )
113
+
114
+ self.assertEqual(1, len(findings))
115
+ self.assertEqual("secret.generic_assignment", findings[0].rule_id)
116
+ self.assertNotIn(secret, findings[0].evidence)
117
+
118
+ def test_generic_secret_with_embedded_common_word_is_not_skipped(self):
119
+ secret = "mytestpasswordABCDEF1234567890"
120
+ findings = scan_text_for_secrets(
121
+ f"password = '{secret}'", path="config.py"
122
+ )
123
+
124
+ self.assertEqual(1, len(findings))
125
+ self.assertEqual("secret.generic_assignment", findings[0].rule_id)
126
+ self.assertNotIn(secret, findings[0].evidence)
127
+
128
+ def test_verbose_dummy_placeholder_value_is_still_ignored(self):
129
+ findings = scan_text_for_secrets(
130
+ "api_key = 'your-api-key-here-please-replace'", path="README.md"
131
+ )
132
+
133
+ self.assertEqual([], findings)
134
+
135
+ def test_scan_diff_reports_added_secret_path_and_line(self):
136
+ secret = "ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJ"
137
+ diff_text = "\n".join(
138
+ [
139
+ "diff --git a/config.py b/config.py",
140
+ "index 1111111..2222222 100644",
141
+ "--- a/config.py",
142
+ "+++ b/config.py",
143
+ "@@ -10,3 +10,4 @@",
144
+ " context line one",
145
+ " context line two",
146
+ f"+token = '{secret}'",
147
+ ]
148
+ )
149
+
150
+ findings = _scan_diff(diff_text)
151
+
152
+ self.assertEqual(1, len(findings))
153
+ self.assertEqual("config.py", findings[0].path)
154
+ self.assertEqual(12, findings[0].line)
155
+
156
+ def test_resolve_git_root_canonicalizes_nested_repo_path(self):
157
+ nested = Path("C:/Users/tanya/dragoneye")
158
+ root = "C:/Users/tanya"
159
+
160
+ with patch(
161
+ "push_guard.guard.subprocess.run",
162
+ return_value=CompletedProcess(
163
+ args=["git"],
164
+ returncode=0,
165
+ stdout=f"{root}\n",
166
+ stderr="",
167
+ ),
168
+ ) as run:
169
+ resolved = _resolve_git_root(nested)
170
+
171
+ self.assertEqual(Path(root), resolved)
172
+ run.assert_called_once_with(
173
+ [
174
+ "git",
175
+ "-c",
176
+ f"safe.directory={nested}",
177
+ "-C",
178
+ str(nested),
179
+ "rev-parse",
180
+ "--show-toplevel",
181
+ ],
182
+ check=True,
183
+ text=True,
184
+ encoding="utf-8",
185
+ errors="replace",
186
+ stdout=-1,
187
+ stderr=-1,
188
+ )
189
+
190
+ def test_resolve_git_root_retries_dubious_ownership_root(self):
191
+ nested = Path("C:/Users/tanya/dragoneye")
192
+ root = Path("C:/Users/tanya")
193
+ dubious = CalledProcessError(
194
+ returncode=128,
195
+ cmd=["git"],
196
+ stderr=(
197
+ "fatal: detected dubious ownership in repository at "
198
+ "'C:/Users/tanya'\n"
199
+ ),
200
+ )
201
+
202
+ with patch(
203
+ "push_guard.guard.subprocess.run",
204
+ side_effect=[
205
+ dubious,
206
+ CompletedProcess(
207
+ args=["git"],
208
+ returncode=0,
209
+ stdout=f"{root}\n",
210
+ stderr="",
211
+ ),
212
+ ],
213
+ ) as run:
214
+ resolved = _resolve_git_root(nested)
215
+
216
+ self.assertEqual(root, resolved)
217
+ self.assertEqual(2, run.call_count)
218
+ self.assertIn(f"safe.directory={root}", run.call_args_list[1].args[0])
219
+
220
+ def test_main_blocks_and_reports_redacted_findings(self):
221
+ secret = "ghp_abcdefghijklmnopqrstuvwxyzABCDEFGHIJ"
222
+ finding_diff = "\n".join(
223
+ [
224
+ "diff --git a/config.py b/config.py",
225
+ "--- a/config.py",
226
+ "+++ b/config.py",
227
+ "@@ -1,0 +1,1 @@",
228
+ f"+token = '{secret}'",
229
+ ]
230
+ )
231
+
232
+ with (
233
+ patch("push_guard.guard._diffs_for_push_ref", return_value=[finding_diff]),
234
+ patch("sys.stdin", StringIO("refs/heads/main abc refs/heads/main def\n")),
235
+ patch("sys.stderr", new_callable=StringIO) as stderr,
236
+ ):
237
+ exit_code = main(["--repo", "."])
238
+
239
+ self.assertEqual(1, exit_code)
240
+ output = stderr.getvalue()
241
+ self.assertIn("blocked this push", output)
242
+ self.assertIn("<redacted>", output)
243
+ self.assertNotIn(secret, output)
244
+
245
+ def test_main_reports_clean_git_inspection_error_without_traceback(self):
246
+ with (
247
+ patch(
248
+ "push_guard.guard._diffs_for_push_ref",
249
+ side_effect=RuntimeError("git diff failed"),
250
+ ),
251
+ patch("sys.stdin", StringIO("refs/heads/main abc refs/heads/main def\n")),
252
+ patch("sys.stderr", new_callable=StringIO) as stderr,
253
+ ):
254
+ exit_code = main(["--repo", "."])
255
+
256
+ self.assertEqual(1, exit_code)
257
+ output = stderr.getvalue()
258
+ self.assertIn("could not inspect this push", output)
259
+ self.assertIn("Blocking push because inspection failed", output)
260
+ self.assertNotIn("Traceback", output)
261
+
262
+ def test_install_pre_push_hook_writes_local_hook(self):
263
+ with TemporaryDirectory() as tmpdir:
264
+ repo = Path(tmpdir)
265
+ (repo / ".git" / "hooks").mkdir(parents=True)
266
+
267
+ with patch("push_guard.guard._resolve_git_root", return_value=repo):
268
+ hook = install_pre_push_hook(repo)
269
+
270
+ self.assertEqual(repo / ".git" / "hooks" / "pre-push", hook)
271
+ body = hook.read_text(encoding="utf-8")
272
+ self.assertIn("python -m push_guard", body)
273
+ self.assertIn("--repo", body)
274
+
275
+ def test_install_pre_push_hook_refuses_unmanaged_existing_hook(self):
276
+ with TemporaryDirectory() as tmpdir:
277
+ repo = Path(tmpdir)
278
+ hook_dir = repo / ".git" / "hooks"
279
+ hook_dir.mkdir(parents=True)
280
+ hook = hook_dir / "pre-push"
281
+ hook.write_text("#!/bin/sh\necho existing\n", encoding="utf-8")
282
+
283
+ with (
284
+ patch("push_guard.guard._resolve_git_root", return_value=repo),
285
+ self.assertRaises(RuntimeError),
286
+ ):
287
+ install_pre_push_hook(repo)
288
+
289
+ self.assertEqual("#!/bin/sh\necho existing\n", hook.read_text())