argvgate 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.
argvgate/__init__.py ADDED
@@ -0,0 +1,8 @@
1
+ """argvgate: a policy gate for coding-agent tool calls, built on a real shell parser."""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from .engine import Decision, Engine, Finding # noqa: E402
6
+ from .policy import Policy, PolicyError, from_dict, load # noqa: E402
7
+
8
+ __all__ = ["Decision", "Engine", "Finding", "Policy", "PolicyError", "from_dict", "load", "__version__"]
argvgate/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ import sys
2
+
3
+ from .cli import main
4
+
5
+ sys.exit(main())
argvgate/cli.py ADDED
@@ -0,0 +1,230 @@
1
+ """Command line interface."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import json
7
+ import os
8
+ import sys
9
+ from typing import List, Optional
10
+
11
+ from . import __version__, hook, probe
12
+ from .engine import Decision, Engine
13
+ from .policy import PolicyError, find_policy, load
14
+
15
+ EXIT = {"allow": 0, "deny": 2, "ask": 3}
16
+ USAGE_ERROR = 64
17
+
18
+ STARTER = '''# argvgate policy. Docs: https://github.com/anishpentyala/argvgate
19
+ version = 1
20
+
21
+ [paths]
22
+ # Gitignore-style patterns. A name with no slash matches anywhere.
23
+ # Matching a directory also covers everything under it.
24
+ deny_read = [".env", ".env.*", "~/.ssh/**", "~/.aws/**", "~/.gnupg/**", "**/*.pem", "**/id_rsa*"]
25
+ deny_write = [".env", ".env.*", ".git/hooks/**", ".github/workflows/**", "~/.ssh/**", "~/.bashrc", "~/.zshrc"]
26
+ # If set, writes anywhere else are refused. Relative entries are relative to the project root.
27
+ write_roots = [".", "/tmp"]
28
+
29
+ [commands]
30
+ default = "allow"
31
+ # Tokens that start with "-" are flags that must be present (a|b means either).
32
+ deny = [
33
+ "rm -r|-R|--recursive /",
34
+ "rm -r|-R|--recursive ~",
35
+ "git push --force|-f",
36
+ "git reset --hard",
37
+ "chmod -R|--recursive 777",
38
+ ]
39
+ ask = ["git push", "npm publish", "pip install", "docker run"]
40
+
41
+ [network]
42
+ # Uncomment to restrict where curl, wget, ssh, git clone and friends may connect.
43
+ # allow_hosts = ["github.com", "*.githubusercontent.com", "pypi.org", "files.pythonhosted.org"]
44
+ on_violation = "deny"
45
+
46
+ [opaque]
47
+ # What to do when a command cannot be analyzed (eval of a variable, python -c, curl | sh ...).
48
+ default = "ask"
49
+ pipe_to_shell = "deny"
50
+ '''
51
+
52
+ CLAUDE_SNIPPET = {
53
+ "hooks": {
54
+ "PreToolUse": [
55
+ {
56
+ "matcher": "Bash|Read|Write|Edit|MultiEdit|NotebookEdit|Grep|Glob|WebFetch",
57
+ "hooks": [{"type": "command", "command": "argvgate hook claude"}],
58
+ }
59
+ ]
60
+ }
61
+ }
62
+
63
+
64
+ def _load_policy(args) -> "object":
65
+ path = args.policy or os.environ.get("ARGVGATE_POLICY") or find_policy(args.cwd or os.getcwd())
66
+ if not path:
67
+ raise PolicyError("no policy found; pass --policy or run `argvgate init`")
68
+ return load(path), path
69
+
70
+
71
+ def _print_decision(dec: Decision, as_json: bool, explain: bool) -> None:
72
+ if as_json:
73
+ print(json.dumps({
74
+ "action": dec.action,
75
+ "reason": dec.reason(),
76
+ "findings": [{"action": f.action, "kind": f.kind, "detail": f.detail, "rule": f.rule} for f in dec.findings],
77
+ "trace": dec.trace if explain else [],
78
+ }, indent=2))
79
+ return
80
+ print(dec.action.upper())
81
+ for f in dec.findings:
82
+ print(" " + f.line())
83
+ if explain:
84
+ print("trace:")
85
+ for line in dec.trace:
86
+ print(" " + line)
87
+
88
+
89
+ def cmd_check(args) -> int:
90
+ policy, _ = _load_policy(args)
91
+ eng = Engine(policy, cwd=args.cwd)
92
+ if args.command is not None:
93
+ dec = eng.check_bash(args.command)
94
+ elif args.read is not None:
95
+ dec = eng.check_path("read", args.read)
96
+ elif args.write is not None:
97
+ dec = eng.check_path("write", args.write)
98
+ elif args.url is not None:
99
+ dec = eng.check_url(args.url)
100
+ else:
101
+ print("argvgate: give one of --command, --read, --write, --url", file=sys.stderr)
102
+ return USAGE_ERROR
103
+ _print_decision(dec, args.json, args.explain or args.prog == "explain")
104
+ return EXIT[dec.action]
105
+
106
+
107
+ def cmd_hook(args) -> int:
108
+ if args.agent != "claude":
109
+ print("argvgate: only 'claude' is supported", file=sys.stderr)
110
+ return USAGE_ERROR
111
+ return hook.run(sys.stdin, sys.stdout, args.policy, args.on_missing_policy)
112
+
113
+
114
+ def cmd_probe(args) -> int:
115
+ policy, path = _load_policy(args)
116
+ results, missed = probe.run(policy)
117
+ print("argvgate probe: %s" % path)
118
+ groups = {}
119
+ for r in results:
120
+ g = groups.setdefault(r.group, [0, 0])
121
+ g[0] += 1
122
+ g[1] += 1 if r.action == "allow" else 0
123
+ for g, (n, m) in groups.items():
124
+ print(" %-60s %3d variants, %d allowed" % (g[:60], n, m))
125
+ print("%d variants checked, %d blocked or flagged, %d allowed" % (len(results), len(results) - len(missed), len(missed)))
126
+ if missed:
127
+ print("\nAllowed variants (each one is a gap in this policy or in argvgate):")
128
+ for r in missed:
129
+ print(" [%s] %s" % (r.group, r.command))
130
+ return 1
131
+ return 0
132
+
133
+
134
+ def cmd_test(args) -> int:
135
+ policy, _ = _load_policy(args)
136
+ with open(args.cases, "r", encoding="utf-8") as fh:
137
+ cases = json.load(fh)
138
+ if isinstance(cases, dict):
139
+ cases = cases.get("cases", [])
140
+ bad = 0
141
+ for i, c in enumerate(cases):
142
+ eng = Engine(policy, cwd=c.get("cwd") or args.cwd)
143
+ tool = c.get("tool", "Bash")
144
+ ti = c.get("input") or ({"command": c["command"]} if "command" in c else {})
145
+ dec = eng.check_tool(tool, ti)
146
+ want = c["expect"]
147
+ ok = dec.action == want
148
+ bad += 0 if ok else 1
149
+ label = c.get("command") or json.dumps(ti)
150
+ print("%s %-5s (want %-5s) %s" % ("ok " if ok else "FAIL", dec.action, want, label))
151
+ print("%d cases, %d failed" % (len(cases), bad))
152
+ return 1 if bad else 0
153
+
154
+
155
+ def cmd_init(args) -> int:
156
+ path = args.path
157
+ if os.path.exists(path):
158
+ print("argvgate: %s already exists; not overwriting" % path, file=sys.stderr)
159
+ return 1
160
+ with open(path, "w", encoding="utf-8") as fh:
161
+ fh.write(STARTER)
162
+ print("wrote %s" % path)
163
+ print("next: argvgate probe --policy %s (tries bypass variants against it)" % path)
164
+ return 0
165
+
166
+
167
+ def cmd_snippet(args) -> int:
168
+ print(json.dumps(CLAUDE_SNIPPET, indent=2))
169
+ return 0
170
+
171
+
172
+ def build_parser() -> argparse.ArgumentParser:
173
+ p = argparse.ArgumentParser(prog="argvgate", description="Policy gate for coding-agent tool calls.")
174
+ p.add_argument("--version", action="version", version="argvgate " + __version__)
175
+ sub = p.add_subparsers(dest="prog")
176
+
177
+ def common(sp):
178
+ sp.add_argument("--policy", help="policy file (default: nearest argvgate.toml/json, or $ARGVGATE_POLICY)")
179
+ sp.add_argument("--cwd", help="working directory to evaluate relative paths from (default: current)")
180
+
181
+ for name in ("check", "explain"):
182
+ sp = sub.add_parser(name, help="evaluate one command, path or URL (exit 0 allow, 2 deny, 3 ask)")
183
+ common(sp)
184
+ sp.add_argument("--command")
185
+ sp.add_argument("--read")
186
+ sp.add_argument("--write")
187
+ sp.add_argument("--url")
188
+ sp.add_argument("--json", action="store_true")
189
+ sp.add_argument("--explain", action="store_true", help="show what was parsed")
190
+ sp.set_defaults(func=cmd_check)
191
+
192
+ sp = sub.add_parser("hook", help="run as a PreToolUse hook (reads the tool call from stdin)")
193
+ sp.add_argument("agent", choices=["claude"])
194
+ sp.add_argument("--policy")
195
+ sp.add_argument("--on-missing-policy", choices=["deny", "ask", "allow"], default="deny")
196
+ sp.set_defaults(func=cmd_hook)
197
+
198
+ sp = sub.add_parser("probe", help="try bypass variants against your policy; exit 1 if any is allowed")
199
+ common(sp)
200
+ sp.set_defaults(func=cmd_probe)
201
+
202
+ sp = sub.add_parser("test", help="run a JSON file of {command, expect} cases against the policy")
203
+ common(sp)
204
+ sp.add_argument("cases")
205
+ sp.set_defaults(func=cmd_test)
206
+
207
+ sp = sub.add_parser("init", help="write a starter policy")
208
+ sp.add_argument("--path", default="argvgate.toml")
209
+ sp.set_defaults(func=cmd_init)
210
+
211
+ sp = sub.add_parser("snippet", help="print the Claude Code settings.json hook entry")
212
+ sp.add_argument("agent", choices=["claude"])
213
+ sp.set_defaults(func=cmd_snippet)
214
+ return p
215
+
216
+
217
+ def main(argv: Optional[List[str]] = None) -> int:
218
+ parser = build_parser()
219
+ args = parser.parse_args(argv)
220
+ if not getattr(args, "func", None):
221
+ parser.print_help()
222
+ return USAGE_ERROR
223
+ try:
224
+ return args.func(args)
225
+ except PolicyError as exc:
226
+ print("argvgate: %s" % exc, file=sys.stderr)
227
+ return USAGE_ERROR
228
+ except OSError as exc:
229
+ print("argvgate: %s" % exc, file=sys.stderr)
230
+ return USAGE_ERROR