kneepad 0.3.0__tar.gz → 0.3.2__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.
- {kneepad-0.3.0/src/kneepad.egg-info → kneepad-0.3.2}/PKG-INFO +5 -5
- {kneepad-0.3.0 → kneepad-0.3.2}/README.md +4 -4
- {kneepad-0.3.0 → kneepad-0.3.2}/pyproject.toml +1 -1
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/__init__.py +1 -1
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/api.py +3 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/argvtools.py +2 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/audit.py +79 -8
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/cli.py +167 -49
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/engine.py +61 -12
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/installer.py +27 -6
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/integrations.py +2 -2
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/util.py +19 -1
- kneepad-0.3.2/src/kneepad/winacl.py +181 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/winshell.py +44 -4
- {kneepad-0.3.0 → kneepad-0.3.2/src/kneepad.egg-info}/PKG-INFO +5 -5
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad.egg-info/SOURCES.txt +11 -1
- kneepad-0.3.2/tests/test_allow_deny_matrix.py +284 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/tests/test_audit_snapshots_hook.py +2 -0
- kneepad-0.3.2/tests/test_branches.py +745 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/tests/test_engine.py +5 -3
- {kneepad-0.3.0 → kneepad-0.3.2}/tests/test_integrations.py +15 -7
- {kneepad-0.3.0 → kneepad-0.3.2}/tests/test_platforms.py +1 -1
- kneepad-0.3.2/tests/test_qa_corpus.py +64 -0
- kneepad-0.3.2/tests/test_qa_regressions.py +210 -0
- kneepad-0.3.2/tests/test_races.py +204 -0
- kneepad-0.3.2/tests/test_symlink_alias.py +49 -0
- kneepad-0.3.2/tests/test_verify_rules_fuzz.py +282 -0
- kneepad-0.3.2/tests/test_winacl.py +258 -0
- kneepad-0.3.2/tests/test_windows_parity.py +207 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/LICENSE +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/setup.cfg +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/__main__.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/adapters.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/badge.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/config.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/data/footguns.toml +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/data/footguns_ext.toml +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/data/footguns_macos.toml +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/data/footguns_windows.toml +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/hook.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/rules.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/shellparse.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/snapshots.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad/sqlscan.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad.egg-info/dependency_links.txt +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad.egg-info/entry_points.txt +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/src/kneepad.egg-info/top_level.txt +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/tests/test_corpus.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/tests/test_hardening.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/tests/test_robustness.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/tests/test_rules_db.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/tests/test_shellparse.py +0 -0
- {kneepad-0.3.0 → kneepad-0.3.2}/tests/test_sqlscan.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: kneepad
|
|
3
|
-
Version: 0.3.
|
|
3
|
+
Version: 0.3.2
|
|
4
4
|
Summary: Local safety layer for AI coding agents on Linux, macOS and Windows: blocks or snapshots destructive commands, with a footgun database and a tamper-evident audit log.
|
|
5
5
|
License: MIT
|
|
6
6
|
Classifier: Programming Language :: Python :: 3
|
|
@@ -26,7 +26,7 @@ Zero dependencies. Python 3.11+. Linux, macOS and Windows. Runs entirely on your
|
|
|
26
26
|
- **Footgun database.** 249 rules (216 pattern rules plus 33 emitted by engine code) for the commands that ruin days: `rm -rf` on the wrong path, `git push --force` to main, `terraform destroy`, `DROP TABLE`, `kubectl delete ns`, `aws s3 rb --force`, `prisma migrate reset`, `curl | sh`, writes to `~/.ssh` and `.bashrc`, and more. Rules are pattern families (one rule covers every `delete`/`destroy`/`terminate` subcommand of a cloud CLI, for example), across about 560 named tools, including Windows and macOS tools. Count of rules is not coverage: more rules also means more false positives, so every rule must pass the benign corpus. Every rule ships with examples that the test suite executes.
|
|
27
27
|
- **Understands shell, not just text.** Quotes, `$(...)`, backticks, heredocs, pipes, `bash -c`, `eval`, `ssh host '...'`, `docker exec`, `kubectl exec --`, `sudo`/`env`/`nice` wrappers, `npx`/`poetry run`/`bundle exec`, and shell scripts the agent is about to run. `echo "rm -rf /"` is not flagged. `DIR=; rm -rf $DIR/` is.
|
|
28
28
|
- **Snapshots before risky-but-allowed actions.** Deleting untracked files, `git reset --hard`, `git clean`, `git branch -D` each take a copy first. Restore with `kneepad snapshots restore <id>`.
|
|
29
|
-
- **Hash-chained audit log.** Every decision is appended to a JSONL log where each entry commits to the previous one and is signed with a local key. Editing, deleting, reordering or inserting entries is detected by `kneepad verify`.
|
|
29
|
+
- **Hash-chained audit log.** Every decision that has a finding (anything other than a plain allow), and every `kneepad run` decision, is appended to a JSONL log where each entry commits to the previous one and is signed with a local key. Editing, deleting, reordering or inserting entries is detected by `kneepad verify`.
|
|
30
30
|
- **"Protected by Kneepad" badge.** `kneepad badge` writes an SVG, and refuses to if the hook is not installed or the log does not verify.
|
|
31
31
|
|
|
32
32
|
Decision model: Kneepad never says "allow". Safe commands pass through silently and keep your normal permission flow. Risky ones get `ask`. Catastrophic ones get `deny`. If Kneepad itself errors, it answers `ask`.
|
|
@@ -41,9 +41,9 @@ Claude Code, OpenAI Codex CLI, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, an
|
|
|
41
41
|
|---|---|---|---|
|
|
42
42
|
| Command analysis | yes | yes: `diskutil`, `tmutil`, `csrutil`, `launchctl`, `security`, `dscl`, `osascript do shell script`, `/private` paths, case-insensitive volumes | yes: cmd.exe and PowerShell syntax, drive and UNC paths, `Remove-Item`/`del`/`rd`, registry, `-EncodedCommand` is decoded, `wsl`/`cmd /c`/`powershell -c` are unwrapped |
|
|
43
43
|
| Agent hook installers | all | all | all except Cline (its docs say macOS and Linux only) |
|
|
44
|
-
| Continuous integration | full suite | full suite | rule examples and platform tests
|
|
44
|
+
| Continuous integration | full suite and end-to-end QA | full suite and end-to-end QA | rule examples and platform tests gate the build; the full suite and the end-to-end QA run as informational steps and passed on real Windows runners for 0.3.1 |
|
|
45
45
|
|
|
46
|
-
Be clear about what this means. The Windows and macOS logic was written and unit-tested on Linux by simulating those platforms' paths and syntax, plus a mutation pass over the new code. The
|
|
46
|
+
Be clear about what this means. The Windows and macOS logic was written and unit-tested on Linux by simulating those platforms' paths and syntax, plus a mutation pass over the new code. The full suite passes on real macOS runners, and the Windows-specific tests pass on real Windows runners (Windows does not run the whole suite). Neither has been used by a person on a real machine with a real agent, so treat both as lightly proven. No agent integration has been run inside its real vendor app on any operating system. Known gaps are listed in [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
|
|
47
47
|
|
|
48
48
|
## Install
|
|
49
49
|
|
|
@@ -99,6 +99,6 @@ Read [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) before relying on it. In short
|
|
|
99
99
|
python3 -m unittest discover -s tests
|
|
100
100
|
```
|
|
101
101
|
|
|
102
|
-
|
|
102
|
+
441 tests: parser, SQL scanner, every rule example, about 280 everyday commands that must pass silently, about 120 destructive commands that must be stopped, audit tamper fuzzing (every single byte flip is detected), concurrent writers, hostile-repo handling, random-input robustness, and Windows and macOS path and syntax simulation. `python tools/smoke_hook.py` installs the hooks into a throwaway home and runs the written hook command through your real OS shell.
|
|
103
103
|
|
|
104
104
|
Adding a rule: see [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md). The rule list is in [docs/FOOTGUNS.md](docs/FOOTGUNS.md).
|
|
@@ -9,7 +9,7 @@ Zero dependencies. Python 3.11+. Linux, macOS and Windows. Runs entirely on your
|
|
|
9
9
|
- **Footgun database.** 249 rules (216 pattern rules plus 33 emitted by engine code) for the commands that ruin days: `rm -rf` on the wrong path, `git push --force` to main, `terraform destroy`, `DROP TABLE`, `kubectl delete ns`, `aws s3 rb --force`, `prisma migrate reset`, `curl | sh`, writes to `~/.ssh` and `.bashrc`, and more. Rules are pattern families (one rule covers every `delete`/`destroy`/`terminate` subcommand of a cloud CLI, for example), across about 560 named tools, including Windows and macOS tools. Count of rules is not coverage: more rules also means more false positives, so every rule must pass the benign corpus. Every rule ships with examples that the test suite executes.
|
|
10
10
|
- **Understands shell, not just text.** Quotes, `$(...)`, backticks, heredocs, pipes, `bash -c`, `eval`, `ssh host '...'`, `docker exec`, `kubectl exec --`, `sudo`/`env`/`nice` wrappers, `npx`/`poetry run`/`bundle exec`, and shell scripts the agent is about to run. `echo "rm -rf /"` is not flagged. `DIR=; rm -rf $DIR/` is.
|
|
11
11
|
- **Snapshots before risky-but-allowed actions.** Deleting untracked files, `git reset --hard`, `git clean`, `git branch -D` each take a copy first. Restore with `kneepad snapshots restore <id>`.
|
|
12
|
-
- **Hash-chained audit log.** Every decision is appended to a JSONL log where each entry commits to the previous one and is signed with a local key. Editing, deleting, reordering or inserting entries is detected by `kneepad verify`.
|
|
12
|
+
- **Hash-chained audit log.** Every decision that has a finding (anything other than a plain allow), and every `kneepad run` decision, is appended to a JSONL log where each entry commits to the previous one and is signed with a local key. Editing, deleting, reordering or inserting entries is detected by `kneepad verify`.
|
|
13
13
|
- **"Protected by Kneepad" badge.** `kneepad badge` writes an SVG, and refuses to if the hook is not installed or the log does not verify.
|
|
14
14
|
|
|
15
15
|
Decision model: Kneepad never says "allow". Safe commands pass through silently and keep your normal permission flow. Risky ones get `ask`. Catastrophic ones get `deny`. If Kneepad itself errors, it answers `ask`.
|
|
@@ -24,9 +24,9 @@ Claude Code, OpenAI Codex CLI, Cursor, Gemini CLI, GitHub Copilot CLI, Cline, an
|
|
|
24
24
|
|---|---|---|---|
|
|
25
25
|
| Command analysis | yes | yes: `diskutil`, `tmutil`, `csrutil`, `launchctl`, `security`, `dscl`, `osascript do shell script`, `/private` paths, case-insensitive volumes | yes: cmd.exe and PowerShell syntax, drive and UNC paths, `Remove-Item`/`del`/`rd`, registry, `-EncodedCommand` is decoded, `wsl`/`cmd /c`/`powershell -c` are unwrapped |
|
|
26
26
|
| Agent hook installers | all | all | all except Cline (its docs say macOS and Linux only) |
|
|
27
|
-
| Continuous integration | full suite | full suite | rule examples and platform tests
|
|
27
|
+
| Continuous integration | full suite and end-to-end QA | full suite and end-to-end QA | rule examples and platform tests gate the build; the full suite and the end-to-end QA run as informational steps and passed on real Windows runners for 0.3.1 |
|
|
28
28
|
|
|
29
|
-
Be clear about what this means. The Windows and macOS logic was written and unit-tested on Linux by simulating those platforms' paths and syntax, plus a mutation pass over the new code. The
|
|
29
|
+
Be clear about what this means. The Windows and macOS logic was written and unit-tested on Linux by simulating those platforms' paths and syntax, plus a mutation pass over the new code. The full suite passes on real macOS runners, and the Windows-specific tests pass on real Windows runners (Windows does not run the whole suite). Neither has been used by a person on a real machine with a real agent, so treat both as lightly proven. No agent integration has been run inside its real vendor app on any operating system. Known gaps are listed in [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md).
|
|
30
30
|
|
|
31
31
|
## Install
|
|
32
32
|
|
|
@@ -82,6 +82,6 @@ Read [docs/THREAT_MODEL.md](docs/THREAT_MODEL.md) before relying on it. In short
|
|
|
82
82
|
python3 -m unittest discover -s tests
|
|
83
83
|
```
|
|
84
84
|
|
|
85
|
-
|
|
85
|
+
441 tests: parser, SQL scanner, every rule example, about 280 everyday commands that must pass silently, about 120 destructive commands that must be stopped, audit tamper fuzzing (every single byte flip is detected), concurrent writers, hostile-repo handling, random-input robustness, and Windows and macOS path and syntax simulation. `python tools/smoke_hook.py` installs the hooks into a throwaway home and runs the written hook command through your real OS shell.
|
|
86
86
|
|
|
87
87
|
Adding a rule: see [docs/CONTRIBUTING.md](docs/CONTRIBUTING.md). The rule list is in [docs/FOOTGUNS.md](docs/FOOTGUNS.md).
|
|
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
|
|
4
4
|
|
|
5
5
|
[project]
|
|
6
6
|
name = "kneepad"
|
|
7
|
-
version = "0.3.
|
|
7
|
+
version = "0.3.2"
|
|
8
8
|
description = "Local safety layer for AI coding agents on Linux, macOS and Windows: blocks or snapshots destructive commands, with a footgun database and a tamper-evident audit log."
|
|
9
9
|
readme = "README.md"
|
|
10
10
|
requires-python = ">=3.11"
|
|
@@ -59,4 +59,7 @@ def guard(func: Optional[Callable] = None, *, arg: str = "command", allow_ask: b
|
|
|
59
59
|
|
|
60
60
|
return inner
|
|
61
61
|
|
|
62
|
+
if func is not None and not callable(func):
|
|
63
|
+
raise TypeError("guard decorates a function: use @guard or @guard(allow_ask=True), not guard('command'). "
|
|
64
|
+
"To check a command string use check_command().")
|
|
62
65
|
return wrap(func) if func is not None else wrap
|
|
@@ -40,6 +40,8 @@ _WRAPPERS: Dict[str, Tuple[Set[str], int]] = {
|
|
|
40
40
|
"npx": ({"-p", "--package", "-c", "--call"}, 0),
|
|
41
41
|
"pnpx": (set(), 0),
|
|
42
42
|
"bunx": (set(), 0),
|
|
43
|
+
"busybox": (set(), 0),
|
|
44
|
+
"toybox": (set(), 0),
|
|
43
45
|
}
|
|
44
46
|
|
|
45
47
|
# Options that consume the next token, per command. Keeps values out of positionals.
|
|
@@ -32,6 +32,7 @@ from .util import ensure_private_dir, now_iso, kneepad_home
|
|
|
32
32
|
GENESIS = "0" * 64
|
|
33
33
|
_BIN = getattr(os, "O_BINARY", 0) # Windows translates newlines unless the descriptor is binary
|
|
34
34
|
VERSION = 1
|
|
35
|
+
_COPY_ROTATION = os.name == "nt" # Windows cannot rename a file that is open; see AuditLog._set_aside
|
|
35
36
|
|
|
36
37
|
try: # POSIX
|
|
37
38
|
import fcntl
|
|
@@ -41,6 +42,9 @@ try: # POSIX
|
|
|
41
42
|
|
|
42
43
|
def _unlock(fd: int) -> None:
|
|
43
44
|
fcntl.flock(fd, fcntl.LOCK_UN)
|
|
45
|
+
|
|
46
|
+
def _lock_shared(fd: int) -> None:
|
|
47
|
+
fcntl.flock(fd, fcntl.LOCK_SH)
|
|
44
48
|
except ImportError: # Windows
|
|
45
49
|
import msvcrt
|
|
46
50
|
|
|
@@ -60,6 +64,8 @@ except ImportError: # Windows
|
|
|
60
64
|
os.lseek(fd, 0, os.SEEK_SET)
|
|
61
65
|
msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
|
|
62
66
|
|
|
67
|
+
_lock_shared = _lock # Windows has no shared byte-range lock here; an exclusive one is brief
|
|
68
|
+
|
|
63
69
|
|
|
64
70
|
def canonical(obj: Dict[str, Any]) -> str:
|
|
65
71
|
return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
|
|
@@ -84,6 +90,10 @@ class _Rotated(Exception):
|
|
|
84
90
|
pass
|
|
85
91
|
|
|
86
92
|
|
|
93
|
+
class _Stale(Exception):
|
|
94
|
+
"""The file we locked is no longer the live log (another writer rotated it while we waited)."""
|
|
95
|
+
|
|
96
|
+
|
|
87
97
|
class AuditLog:
|
|
88
98
|
def __init__(self, home: Optional[str] = None) -> None:
|
|
89
99
|
self.home = home or kneepad_home()
|
|
@@ -115,6 +125,9 @@ class AuditLog:
|
|
|
115
125
|
except OSError:
|
|
116
126
|
pass
|
|
117
127
|
key = self._read_key()
|
|
128
|
+
if os.name == "nt": # 0o600 is ignored on NTFS; make sure inherited access is not wider than the owner
|
|
129
|
+
from . import winacl
|
|
130
|
+
winacl.tighten_if_exposed(self.key_path, False)
|
|
118
131
|
if key is None:
|
|
119
132
|
raise OSError("could not read the audit key")
|
|
120
133
|
return key
|
|
@@ -138,26 +151,78 @@ class AuditLog:
|
|
|
138
151
|
while pos > 0:
|
|
139
152
|
read = min(chunk, pos)
|
|
140
153
|
pos -= read
|
|
141
|
-
|
|
154
|
+
os.lseek(fd, pos, os.SEEK_SET) # portable: os.pread does not exist on Windows
|
|
155
|
+
data = os.read(fd, read) + data
|
|
142
156
|
body = data.rstrip(b"\n")
|
|
143
157
|
if b"\n" in body or pos == 0:
|
|
144
158
|
break
|
|
145
159
|
body = data.rstrip(b"\n")
|
|
146
160
|
return body.rsplit(b"\n", 1)[-1] if body else None
|
|
147
161
|
|
|
148
|
-
def
|
|
162
|
+
def append_if_empty(self, event: str, data: Dict[str, Any]) -> Optional[Dict[str, Any]]:
|
|
163
|
+
"""Append only when the log has no entries yet, atomically (parallel `init` calls write one init event)."""
|
|
164
|
+
return self.append(event, data, only_if_empty=True)
|
|
165
|
+
|
|
166
|
+
def append(self, event: str, data: Dict[str, Any], only_if_empty: bool = False) -> Optional[Dict[str, Any]]:
|
|
167
|
+
note = False
|
|
168
|
+
for _attempt in range(50):
|
|
169
|
+
try:
|
|
170
|
+
return self._append(event, {**data, "note": "previous log was corrupt and was set aside"} if note else data,
|
|
171
|
+
only_if_empty)
|
|
172
|
+
except _Rotated:
|
|
173
|
+
note = True
|
|
174
|
+
except _Stale:
|
|
175
|
+
continue
|
|
176
|
+
raise OSError("audit log kept changing underneath this writer; giving up")
|
|
177
|
+
|
|
178
|
+
def _is_live(self, fd: int) -> bool:
|
|
179
|
+
"""True when ``fd`` still refers to the file currently at self.path (not one a peer rotated away)."""
|
|
149
180
|
try:
|
|
150
|
-
|
|
151
|
-
except
|
|
152
|
-
return
|
|
181
|
+
a, b = os.stat(self.path), os.fstat(fd)
|
|
182
|
+
except OSError:
|
|
183
|
+
return False
|
|
184
|
+
if not a.st_ino or not b.st_ino: # some Windows filesystems report no inode: assume live
|
|
185
|
+
return True
|
|
186
|
+
return (a.st_ino, a.st_dev) == (b.st_ino, b.st_dev)
|
|
187
|
+
|
|
188
|
+
def _set_aside(self, fd: int, dest: str) -> None:
|
|
189
|
+
"""Move the corrupt log out of the way while this writer still holds it open and locked.
|
|
190
|
+
|
|
191
|
+
POSIX renames the file. Windows refuses to rename a file that any handle has open (WinError 32), including ours, so
|
|
192
|
+
there the evidence is copied to ``dest`` and the live file is emptied in place; peers waiting on the lock then see
|
|
193
|
+
an empty log and start a fresh chain, exactly as they do after a rename."""
|
|
194
|
+
if not _COPY_ROTATION:
|
|
195
|
+
os.replace(self.path, dest)
|
|
196
|
+
return
|
|
197
|
+
size = os.fstat(fd).st_size
|
|
198
|
+
out = os.open(dest, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _BIN, 0o600)
|
|
199
|
+
try:
|
|
200
|
+
os.lseek(fd, 0, os.SEEK_SET)
|
|
201
|
+
left = size
|
|
202
|
+
while left > 0:
|
|
203
|
+
chunk = os.read(fd, min(left, 1 << 20))
|
|
204
|
+
if not chunk:
|
|
205
|
+
break
|
|
206
|
+
view = memoryview(chunk)
|
|
207
|
+
while view:
|
|
208
|
+
view = view[os.write(out, view):]
|
|
209
|
+
left -= len(chunk)
|
|
210
|
+
os.fsync(out)
|
|
211
|
+
finally:
|
|
212
|
+
os.close(out)
|
|
213
|
+
os.ftruncate(fd, 0)
|
|
153
214
|
|
|
154
|
-
def _append(self, event: str, data: Dict[str, Any]) -> Dict[str, Any]:
|
|
215
|
+
def _append(self, event: str, data: Dict[str, Any], only_if_empty: bool = False) -> Optional[Dict[str, Any]]:
|
|
155
216
|
key = self.ensure_key()
|
|
156
217
|
fd = os.open(self.path, os.O_RDWR | os.O_CREAT | os.O_APPEND | _BIN, 0o600)
|
|
157
218
|
try:
|
|
158
219
|
_lock(fd)
|
|
159
220
|
try:
|
|
221
|
+
if not self._is_live(fd):
|
|
222
|
+
raise _Stale()
|
|
160
223
|
last_raw = self._last_line(fd)
|
|
224
|
+
if only_if_empty and last_raw is not None:
|
|
225
|
+
return None
|
|
161
226
|
last: Optional[Dict[str, Any]] = None
|
|
162
227
|
if last_raw is not None:
|
|
163
228
|
try:
|
|
@@ -173,7 +238,7 @@ class AuditLog:
|
|
|
173
238
|
while os.path.exists(dest):
|
|
174
239
|
n += 1
|
|
175
240
|
dest = f"{self.path}.corrupt-{int(time.time())}-{n}"
|
|
176
|
-
|
|
241
|
+
self._set_aside(fd, dest)
|
|
177
242
|
raise _Rotated()
|
|
178
243
|
seq = (last["seq"] + 1) if last else 1
|
|
179
244
|
prev = last["hash"] if last else GENESIS
|
|
@@ -210,7 +275,7 @@ class AuditLog:
|
|
|
210
275
|
return out
|
|
211
276
|
|
|
212
277
|
def tail(self, n: int = 20) -> List[Dict[str, Any]]:
|
|
213
|
-
return self.read_all()[-n:]
|
|
278
|
+
return self.read_all()[-n:] if n > 0 else []
|
|
214
279
|
|
|
215
280
|
def verify(self, anchor: Optional[str] = None) -> VerifyResult:
|
|
216
281
|
res = VerifyResult(ok=True)
|
|
@@ -234,6 +299,12 @@ class AuditLog:
|
|
|
234
299
|
return VerifyResult(ok=False, error="no audit log exists but an anchor was supplied")
|
|
235
300
|
return res
|
|
236
301
|
with fh:
|
|
302
|
+
try:
|
|
303
|
+
# Wait for any append in progress, so a half-written last line is never mistaken for tampering.
|
|
304
|
+
# Closing the file at the end of this block releases the lock.
|
|
305
|
+
_lock_shared(fh.fileno())
|
|
306
|
+
except (OSError, ValueError):
|
|
307
|
+
pass
|
|
237
308
|
for lineno, raw in enumerate(fh, 1):
|
|
238
309
|
raw = raw.rstrip(b"\n")
|
|
239
310
|
if not raw:
|
|
@@ -5,6 +5,7 @@ from __future__ import annotations
|
|
|
5
5
|
import argparse
|
|
6
6
|
import json
|
|
7
7
|
import os
|
|
8
|
+
import re
|
|
8
9
|
import shlex
|
|
9
10
|
import shutil
|
|
10
11
|
import stat
|
|
@@ -24,7 +25,7 @@ from .integrations import TARGETS, install_target, uninstall_target
|
|
|
24
25
|
from .installer import InstallError, hook_command, install, is_installed, settings_path, uninstall
|
|
25
26
|
from .rules import load_default_rules, load_rules_text
|
|
26
27
|
from .snapshots import SnapshotError, SnapshotStore
|
|
27
|
-
from .util import kneepad_home
|
|
28
|
+
from .util import kneepad_home, redact
|
|
28
29
|
|
|
29
30
|
EXIT_ALLOW, EXIT_ASK, EXIT_DENY = 0, 10, 20
|
|
30
31
|
|
|
@@ -86,9 +87,16 @@ def cmd_init(args) -> int:
|
|
|
86
87
|
home = kneepad_home()
|
|
87
88
|
log = AuditLog(home)
|
|
88
89
|
log.ensure_key()
|
|
89
|
-
|
|
90
|
-
log.append("init", {"version": __version__})
|
|
90
|
+
log.append_if_empty("init", {"version": __version__})
|
|
91
91
|
print(f"Kneepad state directory: {home}")
|
|
92
|
+
if sys.platform == "win32":
|
|
93
|
+
from . import winacl
|
|
94
|
+
for p, is_dir in ((home, True), (log.key_path, False)):
|
|
95
|
+
fixed = winacl.tighten_if_exposed(p, is_dir)
|
|
96
|
+
if fixed is True:
|
|
97
|
+
print(f"Tightened access to {p}: now only you, SYSTEM and Administrators")
|
|
98
|
+
elif fixed is False:
|
|
99
|
+
print(f"warning: {p} is also accessible to other accounts and could not be tightened; fix it with icacls", file=sys.stderr)
|
|
92
100
|
targets = list(getattr(args, "target", None) or [])
|
|
93
101
|
if "all" in targets:
|
|
94
102
|
targets = list(TARGETS)
|
|
@@ -139,6 +147,9 @@ def cmd_uninstall(args) -> int:
|
|
|
139
147
|
|
|
140
148
|
|
|
141
149
|
def cmd_log(args) -> int:
|
|
150
|
+
if args.n < 0:
|
|
151
|
+
print("kneepad log: -n must be 0 or greater", file=sys.stderr)
|
|
152
|
+
return 2
|
|
142
153
|
entries = AuditLog().tail(args.n)
|
|
143
154
|
if args.json:
|
|
144
155
|
print(json.dumps(entries, indent=2))
|
|
@@ -184,7 +195,7 @@ def cmd_rules(args) -> int:
|
|
|
184
195
|
except (OSError, ValueError) as exc:
|
|
185
196
|
print(f"INVALID: {exc}")
|
|
186
197
|
return 1
|
|
187
|
-
print(f"OK: {len(rules)} rules")
|
|
198
|
+
print(f"OK: {len(rules)} rules (structure and regexes only; the test suite runs each rule's examples)")
|
|
188
199
|
return 0
|
|
189
200
|
rules = load_default_rules()
|
|
190
201
|
if args.rules_cmd == "list":
|
|
@@ -253,7 +264,10 @@ def run_doctor(cwd: str) -> List[tuple]:
|
|
|
253
264
|
items.append((False, "footgun database", str(exc)[:200]))
|
|
254
265
|
win = sys.platform == "win32"
|
|
255
266
|
if os.path.isdir(home) and win:
|
|
256
|
-
|
|
267
|
+
from . import winacl
|
|
268
|
+
rep = winacl.check(home)
|
|
269
|
+
items.append((True if rep.status == "private" else False if rep.status == "exposed" else None,
|
|
270
|
+
"state directory is private", f"{home} ({rep.detail or 'only you, SYSTEM and Administrators'})"))
|
|
257
271
|
elif os.path.isdir(home):
|
|
258
272
|
mode = stat.S_IMODE(os.stat(home).st_mode)
|
|
259
273
|
items.append((mode & 0o077 == 0 or None, "state directory is private", f"{home} mode {oct(mode)}"))
|
|
@@ -261,7 +275,10 @@ def run_doctor(cwd: str) -> List[tuple]:
|
|
|
261
275
|
items.append((None, "state directory exists", f"{home} not created yet; run kneepad init"))
|
|
262
276
|
log = AuditLog(home)
|
|
263
277
|
if os.path.exists(log.key_path) and win:
|
|
264
|
-
|
|
278
|
+
from . import winacl
|
|
279
|
+
rep = winacl.check(log.key_path)
|
|
280
|
+
items.append((True if rep.status == "private" else False if rep.status == "exposed" else None,
|
|
281
|
+
"audit key is private", rep.detail or "only you, SYSTEM and Administrators"))
|
|
265
282
|
elif os.path.exists(log.key_path):
|
|
266
283
|
mode = stat.S_IMODE(os.stat(log.key_path).st_mode)
|
|
267
284
|
items.append((mode & 0o077 == 0, "audit key is private", oct(mode)))
|
|
@@ -312,8 +329,12 @@ def cmd_badge(args) -> int:
|
|
|
312
329
|
"does not verify. Run `kneepad doctor`. (Use --force to override.)", file=sys.stderr)
|
|
313
330
|
return 1
|
|
314
331
|
out = args.out
|
|
315
|
-
|
|
316
|
-
|
|
332
|
+
try:
|
|
333
|
+
with open(out, "w", encoding="utf-8") as fh:
|
|
334
|
+
fh.write(make_badge())
|
|
335
|
+
except OSError as exc:
|
|
336
|
+
print(f"kneepad badge: cannot write {out}: {exc}", file=sys.stderr)
|
|
337
|
+
return 1
|
|
317
338
|
print(f"wrote {out}")
|
|
318
339
|
print(f"Markdown: })")
|
|
319
340
|
return 0
|
|
@@ -328,6 +349,74 @@ def _default_real_shell() -> str:
|
|
|
328
349
|
return "/bin/sh"
|
|
329
350
|
|
|
330
351
|
|
|
352
|
+
def _shell_command_arg(argv: List[str]) -> Optional[str]:
|
|
353
|
+
"""Return the command string of a `sh -c STRING` style invocation, or None when there is none.
|
|
354
|
+
|
|
355
|
+
Handles clustered short options (-ec, -xc, -lc, -euc), separate options before -c (-l -c, -o pipefail -c),
|
|
356
|
+
and long options (--norc). Stops at the first non-option word, which a shell treats as a script path.
|
|
357
|
+
"""
|
|
358
|
+
i = 0
|
|
359
|
+
while i < len(argv):
|
|
360
|
+
a = argv[i]
|
|
361
|
+
if a == "--":
|
|
362
|
+
return None
|
|
363
|
+
if a in ("-o", "+o", "-O", "+O", "--rcfile", "--init-file"):
|
|
364
|
+
i += 2
|
|
365
|
+
continue
|
|
366
|
+
if a.startswith("--"):
|
|
367
|
+
i += 1
|
|
368
|
+
continue
|
|
369
|
+
if re.fullmatch(r"[-+][A-Za-z]+", a):
|
|
370
|
+
if a[0] == "-" and "c" in a:
|
|
371
|
+
return argv[i + 1] if i + 1 < len(argv) else None
|
|
372
|
+
i += 1
|
|
373
|
+
continue
|
|
374
|
+
return None
|
|
375
|
+
return None
|
|
376
|
+
|
|
377
|
+
|
|
378
|
+
def _vet_command(text: str, tool: str, interactive_ask: bool) -> int:
|
|
379
|
+
"""Shared by `run` and `shell`: analyse, snapshot, log, and return 0 to proceed or 126 to refuse.
|
|
380
|
+
|
|
381
|
+
Every outcome is written to the audit log, including refusals. A failure to write the log is reported on
|
|
382
|
+
stderr instead of being swallowed.
|
|
383
|
+
"""
|
|
384
|
+
cfg = load_config(os.getcwd())
|
|
385
|
+
d = Analyzer(config=cfg, cwd=os.getcwd()).analyze_shell(text)
|
|
386
|
+
refused = False
|
|
387
|
+
if d.action in ("deny", "ask") and cfg.mode != "monitor":
|
|
388
|
+
print(d.reason(), file=sys.stderr)
|
|
389
|
+
if d.action == "deny":
|
|
390
|
+
refused = True
|
|
391
|
+
elif interactive_ask and sys.stdin.isatty():
|
|
392
|
+
refused = input("Run it anyway? [y/N] ").strip().lower() != "y"
|
|
393
|
+
else:
|
|
394
|
+
print("Not a terminal, so Kneepad cannot ask. Refusing." if interactive_ask else "Kneepad blocked this command.",
|
|
395
|
+
file=sys.stderr)
|
|
396
|
+
refused = True
|
|
397
|
+
snaps: List[str] = []
|
|
398
|
+
if not refused and d.plans:
|
|
399
|
+
try:
|
|
400
|
+
store = SnapshotStore()
|
|
401
|
+
for p in d.plans:
|
|
402
|
+
sid = store.create(p)["id"]
|
|
403
|
+
snaps.append(sid)
|
|
404
|
+
print(f"kneepad: snapshot {sid}", file=sys.stderr)
|
|
405
|
+
except SnapshotError as exc:
|
|
406
|
+
print(f"kneepad: snapshot failed ({exc}); refusing to run.", file=sys.stderr)
|
|
407
|
+
refused = True
|
|
408
|
+
try:
|
|
409
|
+
AuditLog().append("decision", {
|
|
410
|
+
"tool": tool, "action": d.action, "mode": cfg.mode, "refused": refused, "cwd": os.getcwd(),
|
|
411
|
+
"command": redact(text, 2000), "snapshots": snaps,
|
|
412
|
+
"findings": [{"rule": f.rule_id, "severity": f.severity, "action": f.action, "detail": redact(f.detail, 300)}
|
|
413
|
+
for f in d.findings]})
|
|
414
|
+
except Exception as exc:
|
|
415
|
+
print(f"kneepad: warning: could not write the audit log ({type(exc).__name__}: {exc}). "
|
|
416
|
+
"Continuing, but this decision is not recorded.", file=sys.stderr)
|
|
417
|
+
return 126 if refused else 0
|
|
418
|
+
|
|
419
|
+
|
|
331
420
|
def cmd_shell(args) -> int:
|
|
332
421
|
"""Drop-in for $SHELL: `kneepad shell -c "cmd"` checks the command, then runs it with the real shell.
|
|
333
422
|
|
|
@@ -337,14 +426,10 @@ def cmd_shell(args) -> int:
|
|
|
337
426
|
argv = list(args.argv)
|
|
338
427
|
if argv and argv[0] == "--":
|
|
339
428
|
argv = argv[1:]
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
print(d.reason(), file=sys.stderr)
|
|
345
|
-
print("Kneepad blocked this command.", file=sys.stderr)
|
|
346
|
-
return 126
|
|
347
|
-
if sys.platform == "win32": # os.execv on Windows detaches and loses the exit code
|
|
429
|
+
cmd_text = _shell_command_arg(argv)
|
|
430
|
+
if cmd_text is not None and _vet_command(cmd_text, "shell", interactive_ask=False) != 0:
|
|
431
|
+
return 126
|
|
432
|
+
if _is_windows(): # os.execv on Windows detaches and loses the exit code
|
|
348
433
|
try:
|
|
349
434
|
return subprocess.call([real] + argv)
|
|
350
435
|
except OSError as exc:
|
|
@@ -356,39 +441,28 @@ def cmd_shell(args) -> int:
|
|
|
356
441
|
|
|
357
442
|
def cmd_run(args) -> int:
|
|
358
443
|
argv = args.argv
|
|
444
|
+
if argv and argv[0] in ("-h", "--help"):
|
|
445
|
+
print("usage: kneepad run [--] COMMAND [ARGS...]\n\nAnalyse COMMAND with Kneepad and run it only if it is allowed.\n"
|
|
446
|
+
"Exit codes: the command's own exit code; 126 when Kneepad refuses; 127 when the program is not found.")
|
|
447
|
+
return 0
|
|
359
448
|
if argv and argv[0] == "--":
|
|
360
449
|
argv = argv[1:]
|
|
361
450
|
if not argv:
|
|
362
|
-
print("usage: kneepad run -- COMMAND [ARGS...]", file=sys.stderr)
|
|
451
|
+
print("usage: kneepad run [--] COMMAND [ARGS...]", file=sys.stderr)
|
|
363
452
|
return 2
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
print(d.reason(), file=sys.stderr)
|
|
370
|
-
if d.action == "deny":
|
|
371
|
-
return 126
|
|
372
|
-
if not sys.stdin.isatty():
|
|
373
|
-
print("Not a terminal, so Kneepad cannot ask. Refusing.", file=sys.stderr)
|
|
374
|
-
return 126
|
|
375
|
-
if input("Run it anyway? [y/N] ").strip().lower() != "y":
|
|
376
|
-
return 126
|
|
377
|
-
if d.plans:
|
|
378
|
-
store = SnapshotStore()
|
|
379
|
-
try:
|
|
380
|
-
for p in d.plans:
|
|
381
|
-
sid = store.create(p)["id"]
|
|
382
|
-
print(f"kneepad: snapshot {sid}", file=sys.stderr)
|
|
383
|
-
except SnapshotError as exc:
|
|
384
|
-
print(f"kneepad: snapshot failed ({exc}); refusing to run.", file=sys.stderr)
|
|
385
|
-
return 126
|
|
453
|
+
# POSIX quoting on every platform: the analyser parses shell syntax, and list2cmdline leaves backslash paths unquoted, which
|
|
454
|
+
# the parser reads as escapes (C:\Users\me\proj became a harmless-looking relative name and `rm -rf` of it was allowed).
|
|
455
|
+
text = shlex.join(argv)
|
|
456
|
+
if _vet_command(text, "run", interactive_ask=True) != 0:
|
|
457
|
+
return 126
|
|
386
458
|
try:
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
459
|
+
return subprocess.call(argv)
|
|
460
|
+
except FileNotFoundError:
|
|
461
|
+
print(f"kneepad run: command not found: {argv[0]}", file=sys.stderr)
|
|
462
|
+
return 127
|
|
463
|
+
except OSError as exc:
|
|
464
|
+
print(f"kneepad run: cannot execute {argv[0]}: {exc}", file=sys.stderr)
|
|
465
|
+
return 126
|
|
392
466
|
|
|
393
467
|
|
|
394
468
|
def build_parser() -> argparse.ArgumentParser:
|
|
@@ -397,15 +471,15 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
397
471
|
sub = p.add_subparsers(dest="cmd", required=True)
|
|
398
472
|
|
|
399
473
|
s = sub.add_parser("init", help="create state, key and optionally install the Claude Code hook")
|
|
400
|
-
s.add_argument("--claude-code", action="store_true")
|
|
474
|
+
s.add_argument("--claude-code", action="store_true", help="install the Claude Code PreToolUse hook")
|
|
401
475
|
s.add_argument("--target", action="append", choices=list(TARGETS) + ["all"], help="also install for another agent (repeatable)")
|
|
402
|
-
s.add_argument("--scope", choices=["user", "project"], default="user")
|
|
476
|
+
s.add_argument("--scope", choices=["user", "project"], default="user", help="user: your home directory (default); project: this repository only")
|
|
403
477
|
s.set_defaults(func=cmd_init)
|
|
404
478
|
|
|
405
479
|
s = sub.add_parser("uninstall", help="remove the Claude Code hook (or --target another agent)")
|
|
406
480
|
s.add_argument("--claude-code", action="store_true", help="also remove the Claude Code hook when --target is given")
|
|
407
|
-
s.add_argument("--target", action="append", choices=list(TARGETS) + ["all"])
|
|
408
|
-
s.add_argument("--scope", choices=["user", "project"], default="user")
|
|
481
|
+
s.add_argument("--target", action="append", choices=list(TARGETS) + ["all"], help="agent to remove the hook from (repeatable)")
|
|
482
|
+
s.add_argument("--scope", choices=["user", "project"], default="user", help="user: your home directory (default); project: this repository only")
|
|
409
483
|
s.set_defaults(func=cmd_uninstall)
|
|
410
484
|
|
|
411
485
|
s = sub.add_parser("hook", help="run as a hook (reads JSON on stdin)")
|
|
@@ -419,7 +493,7 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
419
493
|
s.add_argument("--json", action="store_true")
|
|
420
494
|
s.set_defaults(func=cmd_check)
|
|
421
495
|
|
|
422
|
-
s = sub.add_parser("shell", help="shell wrapper for agents that run commands through $SHELL -c")
|
|
496
|
+
s = sub.add_parser("shell", help="shell wrapper for agents that run commands through $SHELL -c (all arguments go to the real shell, so --help shows the shell's help)")
|
|
423
497
|
s.add_argument("argv", nargs=argparse.REMAINDER)
|
|
424
498
|
s.set_defaults(func=cmd_shell)
|
|
425
499
|
|
|
@@ -474,12 +548,51 @@ def build_parser() -> argparse.ArgumentParser:
|
|
|
474
548
|
return p
|
|
475
549
|
|
|
476
550
|
|
|
551
|
+
def _is_windows() -> bool:
|
|
552
|
+
return sys.platform == "win32"
|
|
553
|
+
|
|
554
|
+
|
|
477
555
|
def shell_main() -> int:
|
|
478
556
|
"""Entry point for `kneepad-shell`: a drop-in value for $SHELL."""
|
|
479
557
|
return main(["shell"] + sys.argv[1:])
|
|
480
558
|
|
|
481
559
|
|
|
560
|
+
def _closed_pipe_error(exc: BaseException) -> bool:
|
|
561
|
+
"""A reader that went away: EPIPE everywhere, and EINVAL on Windows (writing to a closed pipe fails with errno 22 there)."""
|
|
562
|
+
import errno
|
|
563
|
+
if isinstance(exc, BrokenPipeError):
|
|
564
|
+
return True
|
|
565
|
+
no = getattr(exc, "errno", None)
|
|
566
|
+
return no == errno.EPIPE or (no == errno.EINVAL and os.name == "nt")
|
|
567
|
+
|
|
568
|
+
|
|
569
|
+
def _flush_std(rc: int) -> int:
|
|
570
|
+
"""Flush stdout and stderr inside main() so a reader that went away (`kneepad rules list | head -1`) is handled here.
|
|
571
|
+
|
|
572
|
+
A broken pipe caught earlier still leaves the final partial buffer pending; the interpreter would then fail to flush it
|
|
573
|
+
at exit and print "Exception ignored ... BrokenPipeError" with exit status 120. Pointing the descriptor at /dev/null
|
|
574
|
+
(the recipe from the Python documentation) makes that exit-time flush harmless."""
|
|
575
|
+
for stream in (sys.stdout, sys.stderr):
|
|
576
|
+
if stream is None:
|
|
577
|
+
continue
|
|
578
|
+
try:
|
|
579
|
+
stream.flush()
|
|
580
|
+
except (BrokenPipeError, OSError) as exc:
|
|
581
|
+
if isinstance(exc, BrokenPipeError) or _closed_pipe_error(exc):
|
|
582
|
+
try:
|
|
583
|
+
os.dup2(os.open(os.devnull, os.O_WRONLY), stream.fileno())
|
|
584
|
+
except (OSError, ValueError, AttributeError):
|
|
585
|
+
pass
|
|
586
|
+
except ValueError:
|
|
587
|
+
pass
|
|
588
|
+
return rc
|
|
589
|
+
|
|
590
|
+
|
|
482
591
|
def main(argv: Optional[List[str]] = None) -> int:
|
|
592
|
+
return _flush_std(_main(argv))
|
|
593
|
+
|
|
594
|
+
|
|
595
|
+
def _main(argv: Optional[List[str]] = None) -> int:
|
|
483
596
|
raw = list(sys.argv[1:] if argv is None else argv)
|
|
484
597
|
# `shell` and `run` forward arbitrary arguments (including -c and other dash options) to another
|
|
485
598
|
# program, which argparse cannot express with REMAINDER when the first token starts with a dash.
|
|
@@ -496,3 +609,8 @@ def main(argv: Optional[List[str]] = None) -> int:
|
|
|
496
609
|
return 130
|
|
497
610
|
except BrokenPipeError:
|
|
498
611
|
return 0
|
|
612
|
+
except OSError as exc:
|
|
613
|
+
if _closed_pipe_error(exc):
|
|
614
|
+
return 0
|
|
615
|
+
print(f"kneepad: error: {exc}", file=sys.stderr)
|
|
616
|
+
return 1
|