kneepad 0.3.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.
kneepad/audit.py ADDED
@@ -0,0 +1,303 @@
1
+ """Tamper-evident audit log.
2
+
3
+ Each line is one JSON object. Every entry contains the SHA-256 of the previous
4
+ entry, so editing, deleting or reordering any line breaks the chain from that
5
+ point on. Each entry is also signed with HMAC-SHA256 using a key stored next to
6
+ the log, so someone who can edit the file but cannot read the key cannot forge a
7
+ valid replacement chain.
8
+
9
+ What this does NOT protect against, stated plainly:
10
+
11
+ * Deleting entries from the END of the log leaves a valid chain. Record an
12
+ anchor (``kneepad anchor``) somewhere the agent cannot write to, and verify
13
+ against it with ``kneepad verify --anchor SEQ:HASH``.
14
+ * Anyone who can read the key AND write the log can forge a new chain.
15
+ * It is local. It proves integrity of a file on this machine, not that the
16
+ machine itself was not compromised.
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import hashlib
22
+ import hmac
23
+ import json
24
+ import os
25
+ import secrets
26
+ import time
27
+ from dataclasses import dataclass, field
28
+ from typing import Any, Dict, List, Optional
29
+
30
+ from .util import ensure_private_dir, now_iso, kneepad_home
31
+
32
+ GENESIS = "0" * 64
33
+ _BIN = getattr(os, "O_BINARY", 0) # Windows translates newlines unless the descriptor is binary
34
+ VERSION = 1
35
+
36
+ try: # POSIX
37
+ import fcntl
38
+
39
+ def _lock(fd: int) -> None:
40
+ fcntl.flock(fd, fcntl.LOCK_EX)
41
+
42
+ def _unlock(fd: int) -> None:
43
+ fcntl.flock(fd, fcntl.LOCK_UN)
44
+ except ImportError: # Windows
45
+ import msvcrt
46
+
47
+ def _lock(fd: int) -> None:
48
+ # LK_LOCK gives up after about 10 seconds with OSError; keep trying for up to a minute.
49
+ deadline = time.monotonic() + 60
50
+ while True:
51
+ os.lseek(fd, 0, os.SEEK_SET)
52
+ try:
53
+ msvcrt.locking(fd, msvcrt.LK_LOCK, 1)
54
+ return
55
+ except OSError:
56
+ if time.monotonic() > deadline:
57
+ raise
58
+
59
+ def _unlock(fd: int) -> None:
60
+ os.lseek(fd, 0, os.SEEK_SET)
61
+ msvcrt.locking(fd, msvcrt.LK_UNLCK, 1)
62
+
63
+
64
+ def canonical(obj: Dict[str, Any]) -> str:
65
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=True)
66
+
67
+
68
+ def entry_hash(entry_without_hashes: Dict[str, Any]) -> str:
69
+ return hashlib.sha256(canonical(entry_without_hashes).encode("ascii")).hexdigest()
70
+
71
+
72
+ @dataclass
73
+ class VerifyResult:
74
+ ok: bool
75
+ count: int = 0
76
+ head_seq: int = 0
77
+ head_hash: str = GENESIS
78
+ error: str = ""
79
+ hmac_verified: bool = False
80
+ warnings: List[str] = field(default_factory=list)
81
+
82
+
83
+ class _Rotated(Exception):
84
+ pass
85
+
86
+
87
+ class AuditLog:
88
+ def __init__(self, home: Optional[str] = None) -> None:
89
+ self.home = home or kneepad_home()
90
+ self.path = os.path.join(self.home, "audit.jsonl")
91
+ self.key_path = os.path.join(self.home, "key")
92
+ self.anchor_path = os.path.join(self.home, "anchors.txt")
93
+
94
+ # ---- key -----------------------------------------------------------
95
+ def ensure_key(self) -> bytes:
96
+ ensure_private_dir(self.home)
97
+ key = self._read_key()
98
+ if key is None:
99
+ # Write the key to a private temp file, then publish it atomically with link(), which
100
+ # fails if another process got there first. Readers never see a half-written key.
101
+ tmp = os.path.join(self.home, f".key.{os.getpid()}.{secrets.token_hex(4)}")
102
+ fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_EXCL | _BIN, 0o600)
103
+ try:
104
+ with os.fdopen(fd, "w") as fh:
105
+ fh.write(secrets.token_hex(32))
106
+ fh.flush()
107
+ os.fsync(fh.fileno())
108
+ try:
109
+ os.link(tmp, self.key_path)
110
+ except FileExistsError:
111
+ pass
112
+ finally:
113
+ try:
114
+ os.unlink(tmp)
115
+ except OSError:
116
+ pass
117
+ key = self._read_key()
118
+ if key is None:
119
+ raise OSError("could not read the audit key")
120
+ return key
121
+
122
+ def _read_key(self) -> Optional[bytes]:
123
+ try:
124
+ with open(self.key_path, "r", encoding="ascii") as fh:
125
+ hexkey = fh.read().strip()
126
+ return bytes.fromhex(hexkey) if hexkey else None
127
+ except (OSError, ValueError):
128
+ return None
129
+
130
+ # ---- append --------------------------------------------------------
131
+ def _last_line(self, fd: int) -> Optional[bytes]:
132
+ size = os.fstat(fd).st_size
133
+ if size == 0:
134
+ return None
135
+ chunk = 65536
136
+ data = b""
137
+ pos = size
138
+ while pos > 0:
139
+ read = min(chunk, pos)
140
+ pos -= read
141
+ data = os.pread(fd, read, pos) + data
142
+ body = data.rstrip(b"\n")
143
+ if b"\n" in body or pos == 0:
144
+ break
145
+ body = data.rstrip(b"\n")
146
+ return body.rsplit(b"\n", 1)[-1] if body else None
147
+
148
+ def append(self, event: str, data: Dict[str, Any]) -> Dict[str, Any]:
149
+ try:
150
+ return self._append(event, data)
151
+ except _Rotated:
152
+ return self._append(event, {**data, "note": "previous log was corrupt and was set aside"})
153
+
154
+ def _append(self, event: str, data: Dict[str, Any]) -> Dict[str, Any]:
155
+ key = self.ensure_key()
156
+ fd = os.open(self.path, os.O_RDWR | os.O_CREAT | os.O_APPEND | _BIN, 0o600)
157
+ try:
158
+ _lock(fd)
159
+ try:
160
+ last_raw = self._last_line(fd)
161
+ last: Optional[Dict[str, Any]] = None
162
+ if last_raw is not None:
163
+ try:
164
+ last = json.loads(last_raw)
165
+ if not isinstance(last, dict) or "hash" not in last or "seq" not in last:
166
+ raise ValueError("not an entry")
167
+ except ValueError:
168
+ # Corrupt tail (for example a crash mid-write): keep the evidence
169
+ # and start a fresh chain.
170
+ # Rotate while still holding the lock, then retry on a fresh file.
171
+ dest = f"{self.path}.corrupt-{int(time.time())}"
172
+ n = 0
173
+ while os.path.exists(dest):
174
+ n += 1
175
+ dest = f"{self.path}.corrupt-{int(time.time())}-{n}"
176
+ os.replace(self.path, dest)
177
+ raise _Rotated()
178
+ seq = (last["seq"] + 1) if last else 1
179
+ prev = last["hash"] if last else GENESIS
180
+ body = {"v": VERSION, "seq": seq, "ts": now_iso(), "event": event, "data": data, "prev": prev}
181
+ h = entry_hash(body)
182
+ entry = dict(body)
183
+ entry["hash"] = h
184
+ entry["hmac"] = hmac.new(key, h.encode("ascii"), hashlib.sha256).hexdigest()
185
+ os.write(fd, (canonical(entry) + "\n").encode("ascii"))
186
+ os.fsync(fd)
187
+ return entry
188
+ finally:
189
+ _unlock(fd)
190
+ finally:
191
+ try:
192
+ os.close(fd)
193
+ except OSError:
194
+ pass
195
+
196
+ # ---- read / verify -------------------------------------------------
197
+ def read_all(self) -> List[Dict[str, Any]]:
198
+ out: List[Dict[str, Any]] = []
199
+ try:
200
+ with open(self.path, "rb") as fh:
201
+ for raw in fh:
202
+ raw = raw.rstrip(b"\n")
203
+ if raw:
204
+ try:
205
+ out.append(json.loads(raw))
206
+ except ValueError:
207
+ continue
208
+ except FileNotFoundError:
209
+ pass
210
+ return out
211
+
212
+ def tail(self, n: int = 20) -> List[Dict[str, Any]]:
213
+ return self.read_all()[-n:]
214
+
215
+ def verify(self, anchor: Optional[str] = None) -> VerifyResult:
216
+ res = VerifyResult(ok=True)
217
+ key = self._read_key()
218
+ saw_hmac = False
219
+ expected_prev = GENESIS
220
+ expected_seq = 1
221
+ anchor_seq: Optional[int] = None
222
+ anchor_hash: Optional[str] = None
223
+ if anchor:
224
+ try:
225
+ s, h = anchor.split(":", 1)
226
+ anchor_seq, anchor_hash = int(s), h.strip().lower()
227
+ except ValueError:
228
+ return VerifyResult(ok=False, error="anchor must look like SEQ:HASH")
229
+ anchor_found = False
230
+ try:
231
+ fh = open(self.path, "rb")
232
+ except FileNotFoundError:
233
+ if anchor:
234
+ return VerifyResult(ok=False, error="no audit log exists but an anchor was supplied")
235
+ return res
236
+ with fh:
237
+ for lineno, raw in enumerate(fh, 1):
238
+ raw = raw.rstrip(b"\n")
239
+ if not raw:
240
+ return self._fail(res, f"line {lineno}: blank line inside the log")
241
+ try:
242
+ text = raw.decode("ascii")
243
+ except UnicodeDecodeError:
244
+ return self._fail(res, f"line {lineno}: non-ASCII bytes (entries are ASCII-only)")
245
+ try:
246
+ e = json.loads(text)
247
+ except ValueError:
248
+ return self._fail(res, f"line {lineno}: not valid JSON")
249
+ if not isinstance(e, dict):
250
+ return self._fail(res, f"line {lineno}: not an object")
251
+ for k in ("v", "seq", "ts", "event", "data", "prev", "hash"):
252
+ if k not in e:
253
+ return self._fail(res, f"line {lineno}: missing field {k!r}")
254
+ if canonical(e) != text:
255
+ return self._fail(res, f"line {lineno}: not in canonical form (edited or re-serialised)")
256
+ if e["seq"] != expected_seq:
257
+ return self._fail(res, f"line {lineno}: sequence is {e['seq']}, expected {expected_seq} (entry removed, inserted or reordered)")
258
+ if e["prev"] != expected_prev:
259
+ return self._fail(res, f"line {lineno}: previous-hash does not match the entry before it (chain broken)")
260
+ body = {k: v for k, v in e.items() if k not in ("hash", "hmac")}
261
+ if entry_hash(body) != e["hash"]:
262
+ return self._fail(res, f"line {lineno}: contents do not match their hash (entry was modified)")
263
+ if "hmac" in e:
264
+ saw_hmac = True
265
+ if key is not None:
266
+ want = hmac.new(key, e["hash"].encode("ascii"), hashlib.sha256).hexdigest()
267
+ if not hmac.compare_digest(want, str(e["hmac"])):
268
+ return self._fail(res, f"line {lineno}: signature does not verify (forged or key changed)")
269
+ elif key is not None:
270
+ return self._fail(res, f"line {lineno}: entry is unsigned although a key exists")
271
+ if anchor_seq is not None and e["seq"] == anchor_seq:
272
+ if e["hash"] != anchor_hash:
273
+ return self._fail(res, f"anchor mismatch at seq {anchor_seq}: the log was rewritten")
274
+ anchor_found = True
275
+ expected_prev = e["hash"]
276
+ expected_seq += 1
277
+ res.count += 1
278
+ res.head_seq = e["seq"]
279
+ res.head_hash = e["hash"]
280
+ if anchor and not anchor_found:
281
+ return self._fail(res, f"anchor seq {anchor_seq} not found: the log was truncated")
282
+ if saw_hmac and key is None:
283
+ res.warnings.append("entries are signed but the key file is missing, so signatures were not verified")
284
+ res.hmac_verified = bool(saw_hmac and key is not None)
285
+ return res
286
+
287
+ @staticmethod
288
+ def _fail(res: VerifyResult, msg: str) -> VerifyResult:
289
+ res.ok = False
290
+ res.error = msg
291
+ return res
292
+
293
+ # ---- anchors -------------------------------------------------------
294
+ def anchor(self) -> Optional[str]:
295
+ """Record the current head as SEQ:HASH, to be stored somewhere the agent cannot write."""
296
+ res = self.verify()
297
+ if not res.ok or res.head_seq == 0:
298
+ return None
299
+ line = f"{res.head_seq}:{res.head_hash}"
300
+ ensure_private_dir(self.home)
301
+ with open(self.anchor_path, "a", encoding="ascii") as fh:
302
+ fh.write(f"{now_iso()} {line}\n")
303
+ return line
kneepad/badge.py ADDED
@@ -0,0 +1,30 @@
1
+ """Static 'protected by kneepad' SVG badge, generated locally with no network access."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from xml.sax.saxutils import escape
6
+
7
+
8
+ def _text_width(s: str) -> int:
9
+ # Verdana 11px is about 6.6px per character on average; add padding.
10
+ return int(len(s) * 6.6) + 12
11
+
12
+
13
+ def make_badge(label: str = "protected by", message: str = "kneepad", color: str = "#2da44e") -> str:
14
+ lw, rw = _text_width(label), _text_width(message)
15
+ w = lw + rw
16
+ lx, rx = lw / 2, lw + rw / 2
17
+ lab, msg = escape(label), escape(message)
18
+ return (
19
+ f'<svg xmlns="http://www.w3.org/2000/svg" width="{w}" height="20" role="img" aria-label="{lab}: {msg}">'
20
+ f"<title>{lab}: {msg}</title>"
21
+ '<linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/>'
22
+ '<stop offset="1" stop-opacity=".1"/></linearGradient>'
23
+ f'<clipPath id="r"><rect width="{w}" height="20" rx="3" fill="#fff"/></clipPath>'
24
+ f'<g clip-path="url(#r)"><rect width="{lw}" height="20" fill="#555"/>'
25
+ f'<rect x="{lw}" width="{rw}" height="20" fill="{color}"/><rect width="{w}" height="20" fill="url(#s)"/></g>'
26
+ '<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">'
27
+ f'<text x="{lx}" y="15" fill="#010101" fill-opacity=".3">{lab}</text><text x="{lx}" y="14">{lab}</text>'
28
+ f'<text x="{rx}" y="15" fill="#010101" fill-opacity=".3">{msg}</text><text x="{rx}" y="14">{msg}</text>'
29
+ "</g></svg>\n"
30
+ )