awgov 0.1.8__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.
awgov/__init__.py ADDED
@@ -0,0 +1,25 @@
1
+ """awgov — the platform's Policy Decision Point for every tool call.
2
+
3
+ from awgov import evaluate, hook_response
4
+
5
+ verdict = evaluate(payload, principal="agent:atlas")
6
+ print(verdict.decision, verdict.rule_id, verdict.lane)
7
+ print(hook_response(verdict, "shadow")) # {} — P1 never blocks
8
+
9
+ One YAML sanction file decides; awbac's segment-aware matcher answers the grant
10
+ question; a deny can always name the lane that should have been used instead.
11
+ """
12
+
13
+ from .engine import Verdict, evaluate, principal_kind
14
+ from .hook import hook_response
15
+ from .policy import Policy, load_policy
16
+
17
+ __version__ = "0.1.8"
18
+ __all__ = [
19
+ "Verdict",
20
+ "Policy",
21
+ "evaluate",
22
+ "hook_response",
23
+ "load_policy",
24
+ "principal_kind",
25
+ ]
awgov/__main__.py ADDED
@@ -0,0 +1,6 @@
1
+ """``python -m awgov`` — the same CLI as the console script."""
2
+
3
+ from .cli import main
4
+
5
+ if __name__ == "__main__":
6
+ raise SystemExit(main())
awgov/admit.py ADDED
@@ -0,0 +1,374 @@
1
+ """A needs-owner call the owner APPROVED with a signed answer runs once.
2
+
3
+ The card awgov raises for a B2 verdict promises "Approve = this exact call runs
4
+ once for this session; the agent re-runs it". Until 0.1.3 nothing kept that
5
+ promise. ``evaluate()`` never read the card store, so the re-run met the same
6
+ needs-owner verdict, the answered card was no longer open, and a NEW card was
7
+ raised. Measured 2026-11-24 on a capped cloud render: approving it would have
8
+ admitted nothing, and the owner would have been asked again.
9
+
10
+ Admission is bound four ways, and every check fails closed:
11
+
12
+ * the card SHOWS the call. Its facts carry the whole command, or the whole tool
13
+ input, unclipped and unmasked. A call that carries a secret-looking value is
14
+ shown masked and can never be admitted;
15
+ * the card's facts carry ``call sha256:<digest>`` of (principal, session, tool,
16
+ everything in the input but the agent's own description and timeout, cwd). The
17
+ owner's receipt signs the facts, so an approval never admits a different call;
18
+ * the answer is ``approve`` with a receipt ``awstorage.attest.verify_receipt``
19
+ accepts: the platform's Ed25519 key, a fresh passkey/TOTP owner sign-in, this
20
+ card, this choice, these facts. A surface LABEL is never proof
21
+ (``answered_via`` is whatever the answering client wrote);
22
+ * one admission per card, recorded in awgov's own ledger before the call runs.
23
+
24
+ Every ledger read waits at most ``BUSY_S``. The PEP is an HTTP hook with a short
25
+ timeout, and a slow decision is no decision at all.
26
+
27
+ Threat model: the one awstorage.attest documents. This is a governance gate with
28
+ an audit trail for agents that use the tools, not a boundary against a hostile
29
+ local agent, which could edit the ledger under its home directory. The signed
30
+ digest is what stops one approval from admitting another call.
31
+ """
32
+
33
+ from __future__ import annotations
34
+
35
+ import hashlib
36
+ import json
37
+ import os
38
+ import sqlite3
39
+ import time
40
+ from dataclasses import dataclass
41
+ from pathlib import Path
42
+ from typing import Any, Callable, Iterable, Optional
43
+
44
+ #: The fact that binds a card to one call. The receipt signs the card's facts.
45
+ CALL_FACT_PREFIX = "call sha256:"
46
+ #: Said on every card, because an unsigned answer is recorded and admits nothing.
47
+ PASSKEY_FACT = ("Approve with your passkey (awdesk or app.aitherium.com/decide); "
48
+ "an unsigned answer runs nothing.")
49
+ #: ``AWGOV_ADMIT=0`` turns admission off (every needs-owner call stays denied).
50
+ ADMIT_ENV = "AWGOV_ADMIT"
51
+ #: The owner principals a signed answer must name (same list the platform's
52
+ #: other signed-card consumers read).
53
+ OWNERS_ENV = "AWSTORAGE_MANAGE_OWNERS"
54
+ #: Tools whose call IS their command text.
55
+ SHELL_TOOLS = ("Bash", "PowerShell")
56
+ #: Input fields that never change what runs: the agent's own label and its timeout.
57
+ _UNBOUND_FIELDS = ("description", "timeout")
58
+ #: The longest any ledger read or write may wait on a lock, in seconds.
59
+ BUSY_S = 0.3
60
+
61
+ _DDL = """
62
+ CREATE TABLE IF NOT EXISTS cards_v2 (
63
+ card_id TEXT PRIMARY KEY,
64
+ digest TEXT NOT NULL,
65
+ family TEXT NOT NULL DEFAULT '',
66
+ session TEXT NOT NULL DEFAULT '',
67
+ admissible INTEGER NOT NULL DEFAULT 1,
68
+ raised_at REAL NOT NULL
69
+ );
70
+ CREATE INDEX IF NOT EXISTS cards_v2_digest ON cards_v2(digest, raised_at);
71
+ CREATE INDEX IF NOT EXISTS cards_v2_family ON cards_v2(family, raised_at);
72
+ CREATE INDEX IF NOT EXISTS cards_v2_session ON cards_v2(session, raised_at);
73
+ CREATE TABLE IF NOT EXISTS admissions_v2 (
74
+ card_id TEXT PRIMARY KEY,
75
+ digest TEXT NOT NULL,
76
+ admitted_at REAL NOT NULL
77
+ );
78
+ """
79
+
80
+
81
+ class LedgerError(RuntimeError):
82
+ """The ledger exists but could not be read or written in time."""
83
+
84
+
85
+ #: What a card may show the owner: printable ASCII plus newline and tab. A carriage
86
+ #: return can overwrite a line in a terminal, a bidi control reorders it, and a
87
+ #: look-alike letter hides another host (second review, 2026-11-24).
88
+ def showable(text: str) -> bool:
89
+ return all(ch in "\n\t" or 32 <= ord(ch) < 127 for ch in str(text or ""))
90
+
91
+
92
+ @dataclass(frozen=True)
93
+ class Admission:
94
+ """The outcome of one admission attempt. ``why`` is always set."""
95
+
96
+ admitted: bool
97
+ card_id: str = ""
98
+ why: str = ""
99
+
100
+
101
+ def enabled(environ: Optional[dict] = None) -> bool:
102
+ env = os.environ if environ is None else environ
103
+ return str(env.get(ADMIT_ENV, "")).strip().lower() not in ("0", "false", "no", "off")
104
+
105
+
106
+ def wanted(payload: Any) -> bool:
107
+ """Only a real PreToolUse from a session is admitted.
108
+
109
+ An ``awgov check`` preview or a test payload carries no hook event, and it
110
+ must never spend the one admission an approval buys.
111
+ """
112
+ return (isinstance(payload, dict)
113
+ and str(payload.get("hook_event_name") or "") == "PreToolUse"
114
+ and bool(str(payload.get("session_id") or "").strip()))
115
+
116
+
117
+ def _canonical(obj: Any) -> str:
118
+ return json.dumps(obj, sort_keys=True, separators=(",", ":"), ensure_ascii=False,
119
+ default=str)
120
+
121
+
122
+ def bound_input(payload: dict) -> dict:
123
+ """The part of the tool input that decides what runs."""
124
+ tool_input = payload.get("tool_input") or {}
125
+ if not isinstance(tool_input, dict):
126
+ return {"value": tool_input}
127
+ return {k: v for k, v in tool_input.items() if k not in _UNBOUND_FIELDS}
128
+
129
+
130
+ def call_digest(payload: dict, principal: str) -> str:
131
+ """sha256 of exactly what would run: who, which session, which tool, the input
132
+ it runs with and the directory it runs in."""
133
+ body = {"v": 2, "principal": str(principal or ""),
134
+ "session": str(payload.get("session_id") or ""),
135
+ "tool": str(payload.get("tool_name") or ""), "input": bound_input(payload),
136
+ "cwd": os.path.normcase(str(payload.get("cwd") or ""))}
137
+ return hashlib.sha256(_canonical(body).encode("utf-8")).hexdigest()
138
+
139
+
140
+ def call_fact(digest: str) -> str:
141
+ return CALL_FACT_PREFIX + digest
142
+
143
+
144
+ def shown_call(payload: dict) -> str:
145
+ """The fact that shows the owner the whole call: the command of a shell tool,
146
+ otherwise every bound input field. Unclipped and unmasked by construction."""
147
+ tool = str(payload.get("tool_name") or "")
148
+ if tool in SHELL_TOOLS:
149
+ return "command: %s" % str((payload.get("tool_input") or {}).get("command") or "")
150
+ return "input: %s %s" % (tool, _canonical(bound_input(payload)))
151
+
152
+
153
+ def _home() -> Path:
154
+ home = os.environ.get("AWGOV_HOME", "").strip()
155
+ return Path(home) if home else Path.home() / ".aither" / "awgov"
156
+
157
+
158
+ def ledger_path(path: str = "") -> Path:
159
+ return Path(path) if path else _home() / "admit.sqlite"
160
+
161
+
162
+ def _connect(path: Path) -> sqlite3.Connection:
163
+ path.parent.mkdir(parents=True, exist_ok=True)
164
+ db = sqlite3.connect(str(path), timeout=BUSY_S, isolation_level=None)
165
+ db.executescript(_DDL)
166
+ return db
167
+
168
+
169
+ def ledger_ok(path: str = "") -> bool:
170
+ """True when the ledger can be opened and written within ``BUSY_S``."""
171
+ try:
172
+ db = _connect(ledger_path(path))
173
+ db.close()
174
+ return True
175
+ except (OSError, sqlite3.Error):
176
+ return False
177
+
178
+
179
+ def remember_card(digest: str, card_id: str, path: str = "", *, family: str = "",
180
+ session: str = "", admissible: bool = True) -> bool:
181
+ """Index the card raised for this exact call. Best effort: False on failure,
182
+ which only means the call cannot be admitted later (fail closed)."""
183
+ if not digest or not card_id:
184
+ return False
185
+ try:
186
+ db = _connect(ledger_path(path))
187
+ try:
188
+ db.execute("INSERT OR IGNORE INTO cards_v2(card_id, digest, family, session,"
189
+ " admissible, raised_at) VALUES (?,?,?,?,?,?)",
190
+ (card_id, digest, family, session, int(bool(admissible)),
191
+ time.time()))
192
+ finally:
193
+ db.close()
194
+ return True
195
+ except (OSError, sqlite3.Error):
196
+ return False
197
+
198
+
199
+ def recent_cards(path: str = "", *, digest: str = "", family: str = "",
200
+ session: str = "", limit: int = 1, admissible_only: bool = False) -> list:
201
+ """Card ids raised for this call, family or session, newest first. [] when nothing
202
+ was ever raised (the ledger is never created just to look); raises LedgerError
203
+ when the ledger exists and cannot answer, so a caller never mistakes a lock for
204
+ "no card yet" and raises another."""
205
+ column, value = (("digest", digest) if digest else ("family", family) if family
206
+ else ("session", session))
207
+ target = ledger_path(path)
208
+ if not value or not target.is_file():
209
+ return []
210
+ where = "%s = ?%s" % (column, " AND admissible = 1" if admissible_only else "")
211
+ try:
212
+ db = _connect(target)
213
+ try:
214
+ rows = db.execute("SELECT card_id FROM cards_v2 WHERE %s ORDER BY raised_at"
215
+ " DESC LIMIT ?" % where, (value, int(limit))).fetchall()
216
+ finally:
217
+ db.close()
218
+ except (OSError, sqlite3.Error) as exc:
219
+ raise LedgerError(str(exc)) from exc
220
+ return [str(r[0]) for r in rows]
221
+
222
+
223
+ def previous_card(digest: str, path: str = "") -> str:
224
+ """The card last raised for this exact call, or "" (also when the ledger cannot
225
+ answer: admission then refuses, which is the closed side)."""
226
+ try:
227
+ found = recent_cards(path, digest=digest)
228
+ except LedgerError:
229
+ return ""
230
+ return found[0] if found else ""
231
+
232
+
233
+ def spent(card_id: str, path: str = "") -> bool:
234
+ """True when this card already admitted its call (or the ledger cannot say)."""
235
+ target = ledger_path(path)
236
+ if not target.is_file():
237
+ return False
238
+ try:
239
+ db = _connect(target)
240
+ try:
241
+ return db.execute("SELECT 1 FROM admissions_v2 WHERE card_id = ?",
242
+ (card_id,)).fetchone() is not None
243
+ finally:
244
+ db.close()
245
+ except (OSError, sqlite3.Error):
246
+ return True
247
+
248
+
249
+ def _consume(card_id: str, digest: str, path: Path) -> bool:
250
+ """Record the one admission. False when it is already spent or cannot be written."""
251
+ try:
252
+ db = _connect(path)
253
+ try:
254
+ db.execute("INSERT INTO admissions_v2(card_id, digest, admitted_at)"
255
+ " VALUES (?,?,?)", (card_id, digest, time.time()))
256
+ return True
257
+ finally:
258
+ db.close()
259
+ except sqlite3.IntegrityError:
260
+ return False
261
+ except (OSError, sqlite3.Error):
262
+ return False
263
+
264
+
265
+ def _owners() -> list:
266
+ raw = os.environ.get(OWNERS_ENV, "")
267
+ return [o.strip() for o in raw.split(",") if o.strip()]
268
+
269
+
270
+ def _norm(fact: Any) -> str:
271
+ return " ".join(str(fact).split())
272
+
273
+
274
+ def _facts(card: Any) -> set:
275
+ raw = card.get("facts") if isinstance(card, dict) else getattr(card, "facts", None)
276
+ return {_norm(f) for f in (raw or [])}
277
+
278
+
279
+ def _field(card: Any, name: str) -> Any:
280
+ return card.get(name) if isinstance(card, dict) else getattr(card, name, None)
281
+
282
+
283
+ def _default_store():
284
+ from .ask_lane import _store # late: awask is optional
285
+ return _store()
286
+
287
+
288
+ def _default_verify() -> Callable[..., Any]:
289
+ from awstorage.attest import verify_receipt # late: the signed-answer verifier
290
+
291
+ def verify(card: Any, owners: Iterable[str]) -> Any:
292
+ # No nonce store: the receipt is bound to this card and these facts, and
293
+ # the one admission it buys is this module's own primary key.
294
+ return verify_receipt(card, owners=owners, record=False)
295
+
296
+ return verify
297
+
298
+
299
+ def admit(verdict: Any, payload: dict, principal: str, *, store: Any = None,
300
+ verify: Optional[Callable[..., Any]] = None, owners: Optional[list] = None,
301
+ ledger: str = "", consume: bool = True) -> Admission:
302
+ """Admit this needs-owner call once if the owner approved it with a signed
303
+ answer on the card that showed it. Never raises; every failure is a refusal.
304
+
305
+ ``consume=False`` answers "would it be admitted?" without spending the one
306
+ admission; the caller checks the call's other grants first, then consumes.
307
+ """
308
+ try:
309
+ if getattr(verdict, "decision", "") != "needs_owner":
310
+ return Admission(False, "", "not a needs-owner verdict")
311
+ if not enabled():
312
+ return Admission(False, "", "admission is off (%s=0)" % ADMIT_ENV)
313
+ digest = call_digest(payload, principal)
314
+ card_id = previous_card(digest, ledger)
315
+ if not card_id:
316
+ return Admission(False, "", "no card was raised for this exact call")
317
+ st = store if store is not None else _default_store()
318
+ card = st.get(card_id)
319
+ if card is None:
320
+ return Admission(False, card_id, "card %s is gone" % card_id)
321
+ status = str(_field(card, "status") or "")
322
+ if status != "answered":
323
+ return Admission(False, card_id, "card %s is %s" % (card_id, status or "unknown"))
324
+ if str(_field(card, "answer") or "") != "approve":
325
+ return Admission(False, card_id, "card %s was answered %r"
326
+ % (card_id, _field(card, "answer")))
327
+ facts = _facts(card)
328
+ if _norm(call_fact(digest)) not in facts:
329
+ return Admission(False, card_id, "card %s does not name this call" % card_id)
330
+ shown = shown_call(payload)
331
+ if not showable(shown) or _norm(shown) not in facts:
332
+ return Admission(False, card_id, "card %s did not show this call in full"
333
+ % card_id)
334
+ if _norm("rule %s" % getattr(verdict, "rule_id", "")) not in facts:
335
+ return Admission(False, card_id, "card %s was raised for another rule" % card_id)
336
+ who = owners if owners is not None else _owners()
337
+ if not who:
338
+ return Admission(False, card_id, "%s is empty: no owner to verify against"
339
+ % OWNERS_ENV)
340
+ check = verify if verify is not None else _default_verify()
341
+ try:
342
+ check(card, owners=who)
343
+ except Exception as exc: # noqa: BLE001 -- any verifier failure is a refusal
344
+ return Admission(False, card_id, "card %s: the answer is not signed by the "
345
+ "owner (%s)" % (card_id, exc))
346
+ path = ledger_path(ledger)
347
+ if spent(card_id, ledger) or (consume and not _consume(card_id, digest, path)):
348
+ return Admission(False, card_id, "card %s already admitted its call once"
349
+ % card_id)
350
+ return Admission(True, card_id, "approved once by the owner on card %s "
351
+ "(signed answer)" % card_id)
352
+ except Exception as exc: # noqa: BLE001 -- admission must never crash the PDP
353
+ return Admission(False, "", "admission failed: %s: %s" % (type(exc).__name__, exc))
354
+
355
+
356
+ __all__ = [
357
+ "ADMIT_ENV",
358
+ "Admission",
359
+ "BUSY_S",
360
+ "CALL_FACT_PREFIX",
361
+ "PASSKEY_FACT",
362
+ "admit",
363
+ "bound_input",
364
+ "call_digest",
365
+ "call_fact",
366
+ "enabled",
367
+ "ledger_path",
368
+ "previous_card",
369
+ "recent_cards",
370
+ "remember_card",
371
+ "shown_call",
372
+ "spent",
373
+ "wanted",
374
+ ]