obstat 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.
- obstat/__init__.py +11 -0
- obstat/__main__.py +87 -0
- obstat/approval.py +139 -0
- obstat/guard.py +329 -0
- obstat/paths.py +34 -0
- obstat/policy.py +109 -0
- obstat/record.py +122 -0
- obstat-0.1.0.dist-info/METADATA +216 -0
- obstat-0.1.0.dist-info/RECORD +12 -0
- obstat-0.1.0.dist-info/WHEEL +4 -0
- obstat-0.1.0.dist-info/entry_points.txt +2 -0
- obstat-0.1.0.dist-info/licenses/LICENSE +202 -0
obstat/__init__.py
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
"""obstat — an auditable decision record for agent tool calls.
|
|
2
|
+
|
|
3
|
+
*nihil obstat*: nothing stands in the way. The clearance is written down before
|
|
4
|
+
the act, not reconstructed after it.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .guard import Denied, Subject, guard, set_subject_resolver
|
|
8
|
+
from .policy import PolicyError
|
|
9
|
+
|
|
10
|
+
__all__ = ["Denied", "PolicyError", "Subject", "guard", "set_subject_resolver"]
|
|
11
|
+
__version__ = "0.1.0"
|
obstat/__main__.py
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
"""`obstat` — the operator's side: what is waiting, and what happened.
|
|
2
|
+
|
|
3
|
+
obstat pending
|
|
4
|
+
obstat approve <id>
|
|
5
|
+
obstat deny <id>
|
|
6
|
+
obstat log [-n 20]
|
|
7
|
+
obstat stop | resume
|
|
8
|
+
"""
|
|
9
|
+
|
|
10
|
+
from __future__ import annotations
|
|
11
|
+
|
|
12
|
+
import argparse
|
|
13
|
+
import getpass
|
|
14
|
+
import json
|
|
15
|
+
import sys
|
|
16
|
+
import time
|
|
17
|
+
|
|
18
|
+
from . import approval, paths, record
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def _pending(_: argparse.Namespace) -> int:
|
|
22
|
+
rows = approval.pending()
|
|
23
|
+
if not rows:
|
|
24
|
+
print("nothing waiting")
|
|
25
|
+
return 0
|
|
26
|
+
for row in rows:
|
|
27
|
+
left = int(row.expires - time.time())
|
|
28
|
+
print(f"{row.id} {row.tool:24} {row.subject:20} {row.resource:30} {left}s left")
|
|
29
|
+
return 0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _decide(args: argparse.Namespace) -> int:
|
|
33
|
+
who = args.by or getpass.getuser()
|
|
34
|
+
if approval.resolve(args.id, approved=args.approved, by=who):
|
|
35
|
+
print(f"{args.id} {'approved' if args.approved else 'denied'} by {who}")
|
|
36
|
+
return 0
|
|
37
|
+
# Already decided, already used, or never existed — all the same to the operator.
|
|
38
|
+
print(f"{args.id}: no pending approval by that id", file=sys.stderr)
|
|
39
|
+
return 1
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _log(args: argparse.Namespace) -> int:
|
|
43
|
+
entries = record.read()
|
|
44
|
+
for entry in entries[-args.n :]:
|
|
45
|
+
print(json.dumps(entry))
|
|
46
|
+
return 0
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _stop(_: argparse.Namespace) -> int:
|
|
50
|
+
path = paths.halt()
|
|
51
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
52
|
+
path.write_text(f"stopped by {getpass.getuser()} at {time.time()}\n", encoding="utf-8")
|
|
53
|
+
print(f"stopped. Every guarded call is denied until `obstat resume`. ({path})")
|
|
54
|
+
return 0
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _resume(_: argparse.Namespace) -> int:
|
|
58
|
+
paths.halt().unlink(missing_ok=True)
|
|
59
|
+
print("resumed")
|
|
60
|
+
return 0
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def main(argv: list[str] | None = None) -> int:
|
|
64
|
+
parser = argparse.ArgumentParser(prog="obstat", description=__doc__)
|
|
65
|
+
sub = parser.add_subparsers(dest="command", required=True)
|
|
66
|
+
|
|
67
|
+
sub.add_parser("pending", help="approvals waiting on a human").set_defaults(run=_pending)
|
|
68
|
+
|
|
69
|
+
for verb, approved in (("approve", True), ("deny", False)):
|
|
70
|
+
cmd = sub.add_parser(verb, help=f"{verb} a pending approval")
|
|
71
|
+
cmd.add_argument("id")
|
|
72
|
+
cmd.add_argument("--by", help="who decided (default: the shell user)")
|
|
73
|
+
cmd.set_defaults(run=_decide, approved=approved)
|
|
74
|
+
|
|
75
|
+
log = sub.add_parser("log", help="the decision record, oldest first")
|
|
76
|
+
log.add_argument("-n", type=int, default=20, help="how many entries (default 20)")
|
|
77
|
+
log.set_defaults(run=_log)
|
|
78
|
+
|
|
79
|
+
sub.add_parser("stop", help="deny every guarded call").set_defaults(run=_stop)
|
|
80
|
+
sub.add_parser("resume", help="undo stop").set_defaults(run=_resume)
|
|
81
|
+
|
|
82
|
+
args = parser.parse_args(argv)
|
|
83
|
+
return int(args.run(args))
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
if __name__ == "__main__":
|
|
87
|
+
raise SystemExit(main())
|
obstat/approval.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"""Two-phase approval (§4).
|
|
2
|
+
|
|
3
|
+
Phase 1: the call arrives, policy says `approve`, and the tool returns an
|
|
4
|
+
approval id instead of doing anything. Phase 2: a human decides, the agent calls
|
|
5
|
+
again with the id, and the call proceeds.
|
|
6
|
+
|
|
7
|
+
The agent is never blocked waiting on a human, because most agents are not
|
|
8
|
+
sitting at a terminal. That is the only reason this is a state machine in SQLite
|
|
9
|
+
rather than an `input()` call.
|
|
10
|
+
|
|
11
|
+
An approval is bound to the exact call it was granted for — tool, subject,
|
|
12
|
+
resource and argument digest — and is single-use. Approving "send the email"
|
|
13
|
+
must not authorise sending a different one.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import sqlite3
|
|
19
|
+
import time
|
|
20
|
+
import uuid
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
|
|
23
|
+
from . import paths
|
|
24
|
+
|
|
25
|
+
TTL_SECONDS = 900 # 15 minutes: long enough to reach a human, short enough to expire
|
|
26
|
+
|
|
27
|
+
_SCHEMA = """
|
|
28
|
+
CREATE TABLE IF NOT EXISTS approvals (
|
|
29
|
+
id TEXT PRIMARY KEY,
|
|
30
|
+
created REAL NOT NULL,
|
|
31
|
+
expires REAL NOT NULL,
|
|
32
|
+
tool TEXT NOT NULL,
|
|
33
|
+
subject TEXT NOT NULL,
|
|
34
|
+
resource TEXT NOT NULL,
|
|
35
|
+
args_digest TEXT NOT NULL,
|
|
36
|
+
record_id TEXT NOT NULL,
|
|
37
|
+
state TEXT NOT NULL CHECK (state IN ('pending','approved','denied','consumed')),
|
|
38
|
+
decided_by TEXT,
|
|
39
|
+
decided_at REAL
|
|
40
|
+
);
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
@dataclass(frozen=True)
|
|
45
|
+
class Pending:
|
|
46
|
+
id: str
|
|
47
|
+
tool: str
|
|
48
|
+
subject: str
|
|
49
|
+
resource: str
|
|
50
|
+
created: float
|
|
51
|
+
expires: float
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _connect() -> sqlite3.Connection:
|
|
55
|
+
path = paths.db()
|
|
56
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
57
|
+
# isolation_level=None: explicit BEGIN IMMEDIATE where it matters, autocommit
|
|
58
|
+
# elsewhere. WAL so a human running the CLI cannot block a serving process.
|
|
59
|
+
conn = sqlite3.connect(path, isolation_level=None, timeout=5.0)
|
|
60
|
+
conn.row_factory = sqlite3.Row
|
|
61
|
+
conn.execute("PRAGMA journal_mode=WAL")
|
|
62
|
+
conn.execute(_SCHEMA)
|
|
63
|
+
return conn
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def request(
|
|
67
|
+
*, tool: str, subject: str, resource: str, args_digest: str, record_id: str
|
|
68
|
+
) -> tuple[str, int]:
|
|
69
|
+
"""Open a pending approval. Returns its id and how long it is valid for."""
|
|
70
|
+
approval_id = uuid.uuid4().hex[:12] # short enough to read out loud over a call
|
|
71
|
+
now = time.time()
|
|
72
|
+
with _connect() as conn:
|
|
73
|
+
conn.execute(
|
|
74
|
+
"INSERT INTO approvals (id, created, expires, tool, subject, resource,"
|
|
75
|
+
" args_digest, record_id, state) VALUES (?,?,?,?,?,?,?,?,'pending')",
|
|
76
|
+
(approval_id, now, now + TTL_SECONDS, tool, subject, resource, args_digest, record_id),
|
|
77
|
+
)
|
|
78
|
+
return approval_id, TTL_SECONDS
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
def resolve(approval_id: str, *, approved: bool, by: str) -> bool:
|
|
82
|
+
"""A human decides. Returns False if there was no pending approval by that id."""
|
|
83
|
+
state = "approved" if approved else "denied"
|
|
84
|
+
with _connect() as conn:
|
|
85
|
+
cursor = conn.execute(
|
|
86
|
+
"UPDATE approvals SET state=?, decided_by=?, decided_at=?"
|
|
87
|
+
" WHERE id=? AND state='pending'",
|
|
88
|
+
(state, by, time.time(), approval_id),
|
|
89
|
+
)
|
|
90
|
+
return cursor.rowcount == 1
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def consume(
|
|
94
|
+
approval_id: str, *, tool: str, subject: str, resource: str, args_digest: str
|
|
95
|
+
) -> tuple[bool, str]:
|
|
96
|
+
"""Spend an approval on exactly the call it was granted for.
|
|
97
|
+
|
|
98
|
+
Returns (ok, reason). The check and the state change happen inside one
|
|
99
|
+
IMMEDIATE transaction, so two concurrent retries cannot both win.
|
|
100
|
+
"""
|
|
101
|
+
with _connect() as conn:
|
|
102
|
+
conn.execute("BEGIN IMMEDIATE")
|
|
103
|
+
try:
|
|
104
|
+
row = conn.execute("SELECT * FROM approvals WHERE id=?", (approval_id,)).fetchone()
|
|
105
|
+
if row is None:
|
|
106
|
+
return False, "unknown approval"
|
|
107
|
+
if row["state"] == "consumed":
|
|
108
|
+
return False, "approval already used"
|
|
109
|
+
if row["state"] != "approved":
|
|
110
|
+
return False, f"approval is {row['state']}"
|
|
111
|
+
if row["expires"] < time.time():
|
|
112
|
+
return False, "approval expired"
|
|
113
|
+
# The binding check. Each of these being wrong means the agent is
|
|
114
|
+
# retrying with an approval granted for a different call.
|
|
115
|
+
for field, actual in (
|
|
116
|
+
("tool", tool),
|
|
117
|
+
("subject", subject),
|
|
118
|
+
("resource", resource),
|
|
119
|
+
("args_digest", args_digest),
|
|
120
|
+
):
|
|
121
|
+
if row[field] != actual:
|
|
122
|
+
return False, f"approval was granted for a different {field}"
|
|
123
|
+
conn.execute("UPDATE approvals SET state='consumed' WHERE id=?", (approval_id,))
|
|
124
|
+
conn.execute("COMMIT")
|
|
125
|
+
return True, "approved"
|
|
126
|
+
except BaseException:
|
|
127
|
+
conn.execute("ROLLBACK")
|
|
128
|
+
raise
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
def pending() -> list[Pending]:
|
|
132
|
+
"""Everything still waiting on a human, oldest first. Expired entries are hidden."""
|
|
133
|
+
with _connect() as conn:
|
|
134
|
+
rows = conn.execute(
|
|
135
|
+
"SELECT id, tool, subject, resource, created, expires FROM approvals"
|
|
136
|
+
" WHERE state='pending' AND expires > ? ORDER BY created",
|
|
137
|
+
(time.time(),),
|
|
138
|
+
).fetchall()
|
|
139
|
+
return [Pending(**dict(row)) for row in rows]
|
obstat/guard.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
1
|
+
"""`@guard` — the decorator, and the order it does things in (§3).
|
|
2
|
+
|
|
3
|
+
1 reject a caller-supplied subject
|
|
4
|
+
2 stop file
|
|
5
|
+
3 resolve the resource from the arguments
|
|
6
|
+
4 policy
|
|
7
|
+
5 approval, if policy asked for one
|
|
8
|
+
6 write the decision record — durable
|
|
9
|
+
7 run the body
|
|
10
|
+
8 write the outcome — best effort
|
|
11
|
+
|
|
12
|
+
Step 6 is before step 7 and that is not a stylistic choice. Everything a reader
|
|
13
|
+
needs to trust the record depends on it.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import functools
|
|
19
|
+
import inspect
|
|
20
|
+
from collections.abc import Callable
|
|
21
|
+
from dataclasses import dataclass
|
|
22
|
+
from typing import Any, Literal
|
|
23
|
+
|
|
24
|
+
from . import approval, paths, policy, record
|
|
25
|
+
|
|
26
|
+
ANONYMOUS = policy.ANONYMOUS
|
|
27
|
+
APPROVAL_ARG = "obstat_approval_id"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class Denied(Exception):
|
|
31
|
+
"""Refused. Carries the record id and nothing else.
|
|
32
|
+
|
|
33
|
+
A denial that explains itself teaches a caller which rule to work around, so
|
|
34
|
+
the detail lives in the record, where the operator can read it and the agent
|
|
35
|
+
cannot.
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(self, record_id: str) -> None:
|
|
39
|
+
super().__init__(f"Not permitted. Do not retry. Reference: {record_id}")
|
|
40
|
+
self.record_id = record_id
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
class _Pending(Exception):
|
|
44
|
+
"""Not an error: an approval was opened and the agent should come back.
|
|
45
|
+
|
|
46
|
+
Raised only because it unwinds the same path a denial does; the wrapper turns
|
|
47
|
+
it into a return value, because a call that needs a human has not failed.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
def __init__(self, approval_id: str, ttl: int, record_id: str) -> None:
|
|
51
|
+
super().__init__(approval_id)
|
|
52
|
+
self.approval_id = approval_id
|
|
53
|
+
self.ttl = ttl
|
|
54
|
+
self.record_id = record_id
|
|
55
|
+
|
|
56
|
+
def payload(self) -> dict[str, Any]:
|
|
57
|
+
return {
|
|
58
|
+
"obstat": "approval_required",
|
|
59
|
+
"approval_id": self.approval_id,
|
|
60
|
+
"expires_in_seconds": self.ttl,
|
|
61
|
+
"record": self.record_id,
|
|
62
|
+
"retry": (
|
|
63
|
+
"A human must approve this call. Once approved, call the same tool "
|
|
64
|
+
f"again with identical arguments plus {APPROVAL_ARG}='{self.approval_id}'."
|
|
65
|
+
),
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
@dataclass(frozen=True)
|
|
70
|
+
class Subject:
|
|
71
|
+
"""Who is calling, as far as the host application can tell.
|
|
72
|
+
|
|
73
|
+
`verified` is the honest flag: False means the identity came from somewhere a
|
|
74
|
+
caller could have influenced — a header, an argument, a config file.
|
|
75
|
+
|
|
76
|
+
ponytail: policy matches on `kind:id` and ignores `verified`, which is
|
|
77
|
+
recorded but not enforced. Gate on it in your resolver (return None rather
|
|
78
|
+
than an unverified Subject) until there is a reason for a rule to say so.
|
|
79
|
+
"""
|
|
80
|
+
|
|
81
|
+
id: str
|
|
82
|
+
kind: Literal["human", "agent", "service"] = "agent"
|
|
83
|
+
via: tuple[str, ...] = () # delegation chain, most recent first
|
|
84
|
+
verified: bool = False
|
|
85
|
+
|
|
86
|
+
def __str__(self) -> str:
|
|
87
|
+
return f"{self.kind}:{self.id}"
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _no_subject() -> Subject | None:
|
|
91
|
+
return None
|
|
92
|
+
|
|
93
|
+
|
|
94
|
+
_resolver: Callable[[], Subject | None] = _no_subject
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
def set_subject_resolver(resolver: Callable[[], Subject | None]) -> None:
|
|
98
|
+
"""Tell obstat how to find out who is calling.
|
|
99
|
+
|
|
100
|
+
Called with no arguments on every guarded call; return None when there is no
|
|
101
|
+
identity, which is the normal case for a stdio MCP server on a laptop. An
|
|
102
|
+
anonymous call is a legitimate call — it is recorded as `anonymous`, and the
|
|
103
|
+
policy decides what that may do.
|
|
104
|
+
"""
|
|
105
|
+
global _resolver
|
|
106
|
+
_resolver = resolver
|
|
107
|
+
|
|
108
|
+
|
|
109
|
+
@dataclass(frozen=True)
|
|
110
|
+
class _Checked:
|
|
111
|
+
"""What steps 1-5 established, handed to step 6."""
|
|
112
|
+
|
|
113
|
+
subject: Subject | None
|
|
114
|
+
subject_name: str
|
|
115
|
+
resource: str
|
|
116
|
+
args_digest: str
|
|
117
|
+
verdict: policy.Decision
|
|
118
|
+
approval_id: str | None
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _public_signature(fn: Callable[..., Any]) -> inspect.Signature:
|
|
122
|
+
"""The signature callers see: `subject` removed, `obstat_approval_id` added.
|
|
123
|
+
|
|
124
|
+
`subject` is injected by obstat, so leaving it in the advertised schema would
|
|
125
|
+
invite a client to supply its own. The approval id is the opposite — the
|
|
126
|
+
retry protocol needs the caller to send it, so it has to be advertised.
|
|
127
|
+
"""
|
|
128
|
+
original = inspect.signature(fn)
|
|
129
|
+
kept = [p for name, p in original.parameters.items() if name != "subject"]
|
|
130
|
+
var_keyword = [p for p in kept if p.kind is inspect.Parameter.VAR_KEYWORD]
|
|
131
|
+
positional = [p for p in kept if p.kind is not inspect.Parameter.VAR_KEYWORD]
|
|
132
|
+
approval_param = inspect.Parameter(
|
|
133
|
+
APPROVAL_ARG,
|
|
134
|
+
inspect.Parameter.KEYWORD_ONLY,
|
|
135
|
+
default=None,
|
|
136
|
+
annotation="str | None",
|
|
137
|
+
)
|
|
138
|
+
return original.replace(parameters=[*positional, approval_param, *var_keyword])
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def _resource_for(
|
|
142
|
+
spec: str | Callable[[dict[str, Any]], str] | None, tool: str, args: dict[str, Any]
|
|
143
|
+
) -> str:
|
|
144
|
+
if spec is None:
|
|
145
|
+
return f"tool:{tool}"
|
|
146
|
+
if callable(spec):
|
|
147
|
+
return spec(args)
|
|
148
|
+
return spec.format(**args)
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def guard(
|
|
152
|
+
*,
|
|
153
|
+
resource: str | Callable[[dict[str, Any]], str] | None = None,
|
|
154
|
+
tool: str | None = None,
|
|
155
|
+
):
|
|
156
|
+
"""Wrap a tool so that no call happens without a written decision.
|
|
157
|
+
|
|
158
|
+
@guard(resource="jira_issue:{issue_key}")
|
|
159
|
+
def transition_issue(issue_key: str, transition: str) -> str:
|
|
160
|
+
...
|
|
161
|
+
|
|
162
|
+
`resource` is a format template over the call arguments, or a callable that
|
|
163
|
+
takes them. Omit it and the resource is `tool:<name>`, which is enough when
|
|
164
|
+
the tool is the only thing policy needs to distinguish.
|
|
165
|
+
"""
|
|
166
|
+
|
|
167
|
+
def decorate(fn: Callable[..., Any]) -> Callable[..., Any]:
|
|
168
|
+
name = tool or fn.__name__
|
|
169
|
+
wants_subject = "subject" in inspect.signature(fn).parameters
|
|
170
|
+
public = _public_signature(fn)
|
|
171
|
+
# Arguments are bound against the public signature minus the approval id,
|
|
172
|
+
# so the digest covers what the tool will actually receive and nothing else.
|
|
173
|
+
bind_against = public.replace(
|
|
174
|
+
parameters=[p for p in public.parameters.values() if p.name != APPROVAL_ARG]
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
def refuse(
|
|
178
|
+
reason: str,
|
|
179
|
+
*,
|
|
180
|
+
subject: str = ANONYMOUS,
|
|
181
|
+
resource_id: str | None = None,
|
|
182
|
+
args_digest: str | None = None,
|
|
183
|
+
rule: int | None = None,
|
|
184
|
+
approval_id: str | None = None,
|
|
185
|
+
) -> Denied:
|
|
186
|
+
return Denied(
|
|
187
|
+
record.decision(
|
|
188
|
+
tool=name,
|
|
189
|
+
subject=subject,
|
|
190
|
+
resource=resource_id or f"tool:{name}",
|
|
191
|
+
effect="deny",
|
|
192
|
+
reason=reason,
|
|
193
|
+
rule=rule,
|
|
194
|
+
args_digest=args_digest or record.digest({}),
|
|
195
|
+
approval_id=approval_id,
|
|
196
|
+
)
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
def check(args: tuple, kwargs: dict) -> _Checked:
|
|
200
|
+
"""Steps 1-5. Raises Denied, raises _Pending, or returns."""
|
|
201
|
+
approval_id = kwargs.pop(APPROVAL_ARG, None)
|
|
202
|
+
|
|
203
|
+
# 1. `subject` is not advertised, so its presence is a caller trying to
|
|
204
|
+
# say who it is. Denied before anything reads it — including the
|
|
205
|
+
# record, which would otherwise quote an attacker's string.
|
|
206
|
+
if "subject" in kwargs:
|
|
207
|
+
raise refuse("caller supplied a subject")
|
|
208
|
+
|
|
209
|
+
try:
|
|
210
|
+
bound = bind_against.bind_partial(*args, **kwargs)
|
|
211
|
+
except TypeError as exc:
|
|
212
|
+
raise refuse(f"arguments do not fit the tool: {exc}") from exc
|
|
213
|
+
bound.apply_defaults()
|
|
214
|
+
call_args = dict(bound.arguments)
|
|
215
|
+
args_digest = record.digest(call_args)
|
|
216
|
+
|
|
217
|
+
who = _resolver()
|
|
218
|
+
subject = str(who) if who is not None else ANONYMOUS
|
|
219
|
+
|
|
220
|
+
# 2. The stop file, before policy: stopping must not depend on the
|
|
221
|
+
# policy file still being parseable.
|
|
222
|
+
if paths.halt().exists():
|
|
223
|
+
raise refuse("halted", subject=subject, args_digest=args_digest)
|
|
224
|
+
|
|
225
|
+
# 3. Resource.
|
|
226
|
+
try:
|
|
227
|
+
target = _resource_for(resource, name, call_args)
|
|
228
|
+
except (KeyError, IndexError, AttributeError, TypeError) as exc:
|
|
229
|
+
raise refuse(
|
|
230
|
+
f"resource template did not resolve: {exc!r}",
|
|
231
|
+
subject=subject,
|
|
232
|
+
resource_id="unresolved",
|
|
233
|
+
args_digest=args_digest,
|
|
234
|
+
) from exc
|
|
235
|
+
|
|
236
|
+
# 4. Policy. Evaluated once; step 6 records this verdict, not a re-read.
|
|
237
|
+
verdict = policy.decide(tool=name, subject=subject, resource=target)
|
|
238
|
+
refusal = functools.partial(
|
|
239
|
+
refuse, subject=subject, resource_id=target, args_digest=args_digest
|
|
240
|
+
)
|
|
241
|
+
if verdict.effect == "deny":
|
|
242
|
+
raise refusal(verdict.reason, rule=verdict.rule)
|
|
243
|
+
|
|
244
|
+
# 5. Approval.
|
|
245
|
+
if verdict.effect == "approve":
|
|
246
|
+
if approval_id is None:
|
|
247
|
+
record_id = record.decision(
|
|
248
|
+
tool=name,
|
|
249
|
+
subject=subject,
|
|
250
|
+
resource=target,
|
|
251
|
+
effect="approval_required",
|
|
252
|
+
reason=verdict.reason,
|
|
253
|
+
rule=verdict.rule,
|
|
254
|
+
args_digest=args_digest,
|
|
255
|
+
)
|
|
256
|
+
new_id, ttl = approval.request(
|
|
257
|
+
tool=name,
|
|
258
|
+
subject=subject,
|
|
259
|
+
resource=target,
|
|
260
|
+
args_digest=args_digest,
|
|
261
|
+
record_id=record_id,
|
|
262
|
+
)
|
|
263
|
+
raise _Pending(new_id, ttl, record_id)
|
|
264
|
+
ok, why = approval.consume(
|
|
265
|
+
approval_id,
|
|
266
|
+
tool=name,
|
|
267
|
+
subject=subject,
|
|
268
|
+
resource=target,
|
|
269
|
+
args_digest=args_digest,
|
|
270
|
+
)
|
|
271
|
+
if not ok:
|
|
272
|
+
raise refusal(why, rule=verdict.rule, approval_id=approval_id)
|
|
273
|
+
|
|
274
|
+
return _Checked(who, subject, target, args_digest, verdict, approval_id)
|
|
275
|
+
|
|
276
|
+
def authorise(args: tuple, kwargs: dict) -> tuple[str, dict]:
|
|
277
|
+
"""Steps 1-6. Returns the record id and the kwargs the body will get."""
|
|
278
|
+
checked = check(args, kwargs)
|
|
279
|
+
record_id = record.decision(
|
|
280
|
+
tool=name,
|
|
281
|
+
subject=checked.subject_name,
|
|
282
|
+
resource=checked.resource,
|
|
283
|
+
effect="allow",
|
|
284
|
+
reason=checked.verdict.reason,
|
|
285
|
+
rule=checked.verdict.rule,
|
|
286
|
+
args_digest=checked.args_digest,
|
|
287
|
+
approval_id=checked.approval_id,
|
|
288
|
+
extra={"subject_verified": bool(checked.subject and checked.subject.verified)},
|
|
289
|
+
)
|
|
290
|
+
if wants_subject:
|
|
291
|
+
kwargs = {**kwargs, "subject": checked.subject}
|
|
292
|
+
return record_id, kwargs
|
|
293
|
+
|
|
294
|
+
if inspect.iscoroutinefunction(fn):
|
|
295
|
+
|
|
296
|
+
@functools.wraps(fn)
|
|
297
|
+
async def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
298
|
+
try:
|
|
299
|
+
record_id, kwargs = authorise(args, dict(kwargs))
|
|
300
|
+
except _Pending as pending:
|
|
301
|
+
return pending.payload()
|
|
302
|
+
try:
|
|
303
|
+
result = await fn(*args, **kwargs)
|
|
304
|
+
except Exception as exc:
|
|
305
|
+
record.outcome(record_id, ok=False, error=type(exc).__name__)
|
|
306
|
+
raise
|
|
307
|
+
record.outcome(record_id, ok=True)
|
|
308
|
+
return result
|
|
309
|
+
|
|
310
|
+
else:
|
|
311
|
+
|
|
312
|
+
@functools.wraps(fn)
|
|
313
|
+
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
|
314
|
+
try:
|
|
315
|
+
record_id, kwargs = authorise(args, dict(kwargs))
|
|
316
|
+
except _Pending as pending:
|
|
317
|
+
return pending.payload()
|
|
318
|
+
try:
|
|
319
|
+
result = fn(*args, **kwargs)
|
|
320
|
+
except Exception as exc:
|
|
321
|
+
record.outcome(record_id, ok=False, error=type(exc).__name__)
|
|
322
|
+
raise
|
|
323
|
+
record.outcome(record_id, ok=True)
|
|
324
|
+
return result
|
|
325
|
+
|
|
326
|
+
wrapper.__signature__ = public # type: ignore[attr-defined]
|
|
327
|
+
return wrapper
|
|
328
|
+
|
|
329
|
+
return decorate
|
obstat/paths.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Where obstat keeps things.
|
|
2
|
+
|
|
3
|
+
Read at call time, never at import. A governance library that raises
|
|
4
|
+
`ConfigError` on import is one you cannot try, and a library you cannot try is
|
|
5
|
+
one nobody adopts — which is worse for security than a permissive default.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
|
|
13
|
+
DEFAULT_DIR = ".obstat"
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _env(name: str, default: str) -> Path:
|
|
17
|
+
return Path(os.environ.get(name) or default).expanduser()
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def policy() -> Path:
|
|
21
|
+
return _env("OBSTAT_POLICY", "obstat.toml")
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def log() -> Path:
|
|
25
|
+
return _env("OBSTAT_LOG", f"{DEFAULT_DIR}/decisions.jsonl")
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def db() -> Path:
|
|
29
|
+
return _env("OBSTAT_DB", f"{DEFAULT_DIR}/approvals.db")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def halt() -> Path:
|
|
33
|
+
"""Presence of this file stops every guarded call. Deleting it resumes."""
|
|
34
|
+
return _env("OBSTAT_HALT", f"{DEFAULT_DIR}/halt")
|
obstat/policy.py
ADDED
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
"""Rules, and the decision they produce (§2).
|
|
2
|
+
|
|
3
|
+
A rule matches on three things — who, which tool, which object — and says one of
|
|
4
|
+
`allow`, `deny`, `approve`. First match wins. Nothing matching is a deny: an
|
|
5
|
+
absent rule is not permission.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import tomllib
|
|
11
|
+
from dataclasses import dataclass
|
|
12
|
+
from fnmatch import fnmatchcase
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import Literal
|
|
15
|
+
|
|
16
|
+
from . import paths
|
|
17
|
+
|
|
18
|
+
Effect = Literal["allow", "deny", "approve"]
|
|
19
|
+
EFFECTS: tuple[Effect, ...] = ("allow", "deny", "approve")
|
|
20
|
+
|
|
21
|
+
ANONYMOUS = "anonymous"
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class PolicyError(RuntimeError):
|
|
25
|
+
"""The policy file is missing or malformed. Raised on the first guarded call."""
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
@dataclass(frozen=True)
|
|
29
|
+
class Rule:
|
|
30
|
+
effect: Effect
|
|
31
|
+
tool: str = "*"
|
|
32
|
+
subject: str = "*"
|
|
33
|
+
resource: str = "*"
|
|
34
|
+
|
|
35
|
+
def matches(self, *, tool: str, subject: str, resource: str) -> bool:
|
|
36
|
+
return (
|
|
37
|
+
fnmatchcase(tool, self.tool)
|
|
38
|
+
and fnmatchcase(subject, self.subject)
|
|
39
|
+
and fnmatchcase(resource, self.resource)
|
|
40
|
+
)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
@dataclass(frozen=True)
|
|
44
|
+
class Decision:
|
|
45
|
+
effect: Effect
|
|
46
|
+
reason: str
|
|
47
|
+
rule: int | None # index into the file, so a record points at the line that decided
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
_DENY_UNMATCHED = Decision("deny", "no rule matched", None)
|
|
51
|
+
|
|
52
|
+
# (path, mtime, size) -> rules. Editing the policy takes effect on the next call
|
|
53
|
+
# rather than the next restart; a stat() per call is cheaper than the confusion.
|
|
54
|
+
_cache: tuple[tuple[str, float, int], list[Rule]] | None = None
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _parse(raw: dict) -> list[Rule]:
|
|
58
|
+
rules: list[Rule] = []
|
|
59
|
+
for index, entry in enumerate(raw.get("rule", [])):
|
|
60
|
+
if not isinstance(entry, dict):
|
|
61
|
+
raise PolicyError(f"rule {index}: expected a table")
|
|
62
|
+
effect = entry.get("effect")
|
|
63
|
+
if effect not in EFFECTS:
|
|
64
|
+
raise PolicyError(f"rule {index}: effect must be one of {', '.join(EFFECTS)}")
|
|
65
|
+
unknown = set(entry) - {"effect", "tool", "subject", "resource"}
|
|
66
|
+
if unknown:
|
|
67
|
+
# A typo'd key would otherwise silently widen the rule to match everything.
|
|
68
|
+
raise PolicyError(f"rule {index}: unknown key(s) {', '.join(sorted(unknown))}")
|
|
69
|
+
rules.append(
|
|
70
|
+
Rule(
|
|
71
|
+
effect=effect,
|
|
72
|
+
tool=str(entry.get("tool", "*")),
|
|
73
|
+
subject=str(entry.get("subject", "*")),
|
|
74
|
+
resource=str(entry.get("resource", "*")),
|
|
75
|
+
)
|
|
76
|
+
)
|
|
77
|
+
return rules
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def load(path: Path | None = None) -> list[Rule]:
|
|
81
|
+
global _cache
|
|
82
|
+
path = path or paths.policy()
|
|
83
|
+
try:
|
|
84
|
+
stat = path.stat()
|
|
85
|
+
except FileNotFoundError as exc:
|
|
86
|
+
raise PolicyError(
|
|
87
|
+
f"no policy at {path}. Write one (see README) or set OBSTAT_POLICY. "
|
|
88
|
+
"obstat has no implicit allow."
|
|
89
|
+
) from exc
|
|
90
|
+
|
|
91
|
+
key = (str(path), stat.st_mtime, stat.st_size)
|
|
92
|
+
if _cache is not None and _cache[0] == key:
|
|
93
|
+
return _cache[1]
|
|
94
|
+
|
|
95
|
+
try:
|
|
96
|
+
raw = tomllib.loads(path.read_text(encoding="utf-8"))
|
|
97
|
+
except tomllib.TOMLDecodeError as exc:
|
|
98
|
+
raise PolicyError(f"{path}: {exc}") from exc
|
|
99
|
+
|
|
100
|
+
rules = _parse(raw)
|
|
101
|
+
_cache = (key, rules)
|
|
102
|
+
return rules
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
def decide(*, tool: str, subject: str, resource: str, path: Path | None = None) -> Decision:
|
|
106
|
+
for index, rule in enumerate(load(path)):
|
|
107
|
+
if rule.matches(tool=tool, subject=subject, resource=resource):
|
|
108
|
+
return Decision(rule.effect, f"rule {index}", index)
|
|
109
|
+
return _DENY_UNMATCHED
|
obstat/record.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
"""The decision record (§5), and the one ordering that is a security property.
|
|
2
|
+
|
|
3
|
+
`decision()` returns only after the record is on disk — written, flushed, and
|
|
4
|
+
fsynced. Everything else in this library is a convenience; this is the part an
|
|
5
|
+
examiner relies on. A log written after the call is a story about what happened.
|
|
6
|
+
A record written before it is evidence of what was authorised.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import contextlib
|
|
12
|
+
import hashlib
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import time
|
|
16
|
+
import uuid
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from . import paths
|
|
21
|
+
|
|
22
|
+
SCHEMA = 1
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def digest(args: dict[str, Any]) -> str:
|
|
26
|
+
"""A stable fingerprint of the call arguments.
|
|
27
|
+
|
|
28
|
+
The values themselves are deliberately not recorded: tool arguments carry
|
|
29
|
+
credentials, personal data and free text, and a governance log that leaks
|
|
30
|
+
them is a liability rather than a control. The digest is enough to prove
|
|
31
|
+
that the call executed is the call that was approved.
|
|
32
|
+
|
|
33
|
+
ponytail: no per-key allowlist yet. Add `record_args=("issue_key",)` to
|
|
34
|
+
@guard when someone needs the values in the record itself.
|
|
35
|
+
"""
|
|
36
|
+
canonical = json.dumps(args, sort_keys=True, default=repr, separators=(",", ":"))
|
|
37
|
+
return "sha256:" + hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _append(entry: dict[str, Any], *, durable: bool) -> None:
|
|
41
|
+
path = paths.log()
|
|
42
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
43
|
+
line = json.dumps(entry, separators=(",", ":"), default=str) + "\n"
|
|
44
|
+
# Append mode, one write, one line: concurrent writers interleave records but
|
|
45
|
+
# never split one. O_APPEND makes the offset kernel-side, so no lock is needed.
|
|
46
|
+
with path.open("a", encoding="utf-8") as handle:
|
|
47
|
+
handle.write(line)
|
|
48
|
+
if durable:
|
|
49
|
+
handle.flush()
|
|
50
|
+
os.fsync(handle.fileno())
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def decision(
|
|
54
|
+
*,
|
|
55
|
+
tool: str,
|
|
56
|
+
subject: str,
|
|
57
|
+
resource: str,
|
|
58
|
+
effect: str,
|
|
59
|
+
reason: str,
|
|
60
|
+
rule: int | None,
|
|
61
|
+
args_digest: str,
|
|
62
|
+
approval_id: str | None = None,
|
|
63
|
+
extra: dict[str, Any] | None = None,
|
|
64
|
+
) -> str:
|
|
65
|
+
"""Write the decision. Returns the record id, which is also the deny reference.
|
|
66
|
+
|
|
67
|
+
Durable before the caller continues — that is the whole point, and
|
|
68
|
+
`tests/test_guard.py::test_record_is_durable_before_the_body_runs` fails if
|
|
69
|
+
this is ever relaxed for speed.
|
|
70
|
+
"""
|
|
71
|
+
record_id = uuid.uuid4().hex
|
|
72
|
+
_append(
|
|
73
|
+
{
|
|
74
|
+
"schema": SCHEMA,
|
|
75
|
+
"id": record_id,
|
|
76
|
+
"ts": time.time(),
|
|
77
|
+
"phase": "decision",
|
|
78
|
+
"tool": tool,
|
|
79
|
+
"subject": subject,
|
|
80
|
+
"resource": resource,
|
|
81
|
+
"effect": effect,
|
|
82
|
+
"reason": reason,
|
|
83
|
+
"rule": rule,
|
|
84
|
+
"args": args_digest,
|
|
85
|
+
"approval_id": approval_id,
|
|
86
|
+
**(extra or {}),
|
|
87
|
+
},
|
|
88
|
+
durable=True,
|
|
89
|
+
)
|
|
90
|
+
return record_id
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def outcome(record_id: str, *, ok: bool, error: str | None = None) -> None:
|
|
94
|
+
"""Best effort, and deliberately not durable.
|
|
95
|
+
|
|
96
|
+
If the process dies mid-call the decision record still stands alone, which
|
|
97
|
+
reads as "authorised, outcome unknown" — the honest state. Blocking the
|
|
98
|
+
caller on a second fsync to record something that is only informative would
|
|
99
|
+
be paying the cost twice for half the value.
|
|
100
|
+
"""
|
|
101
|
+
# A full disk must not turn a completed call into a failed one.
|
|
102
|
+
with contextlib.suppress(OSError):
|
|
103
|
+
_append(
|
|
104
|
+
{
|
|
105
|
+
"schema": SCHEMA,
|
|
106
|
+
"id": record_id,
|
|
107
|
+
"ts": time.time(),
|
|
108
|
+
"phase": "outcome",
|
|
109
|
+
"ok": ok,
|
|
110
|
+
"error": error,
|
|
111
|
+
},
|
|
112
|
+
durable=False,
|
|
113
|
+
)
|
|
114
|
+
|
|
115
|
+
|
|
116
|
+
def read(path: Path | None = None) -> list[dict[str, Any]]:
|
|
117
|
+
"""Every record, oldest first. For tests and for `obstat log`."""
|
|
118
|
+
path = path or paths.log()
|
|
119
|
+
if not path.exists():
|
|
120
|
+
return []
|
|
121
|
+
with path.open(encoding="utf-8") as handle:
|
|
122
|
+
return [json.loads(line) for line in handle if line.strip()]
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: obstat
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: An auditable decision record for agent tool calls. The clearance is written down before the call runs.
|
|
5
|
+
Project-URL: Homepage, https://github.com/marcinmarzeta/obstat
|
|
6
|
+
Project-URL: Issues, https://github.com/marcinmarzeta/obstat/issues
|
|
7
|
+
Author: Marcin Marzęta
|
|
8
|
+
License-Expression: Apache-2.0
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: agents,approval,audit,authorization,llm,mcp
|
|
11
|
+
Classifier: Development Status :: 3 - Alpha
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
16
|
+
Classifier: Topic :: Security
|
|
17
|
+
Requires-Python: >=3.11
|
|
18
|
+
Provides-Extra: mcp
|
|
19
|
+
Requires-Dist: mcp>=2; extra == 'mcp'
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# obstat
|
|
23
|
+
|
|
24
|
+
**An auditable decision record for agent tool calls.** The clearance is written
|
|
25
|
+
down before the call runs — not reconstructed from logs afterwards.
|
|
26
|
+
|
|
27
|
+
*Nihil obstat*: nothing stands in the way. It was the formal clearance a censor
|
|
28
|
+
granted **in writing, before publication**. That is the whole idea here. An agent
|
|
29
|
+
asks to do something, a rule decides, and the decision goes to disk *before* the
|
|
30
|
+
tool body executes. If the process dies mid-call, the record still says what was
|
|
31
|
+
authorised and why.
|
|
32
|
+
|
|
33
|
+
```bash
|
|
34
|
+
pip install obstat
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
No dependencies. Not AWS, not an identity provider, not a policy service — the
|
|
38
|
+
decorator, `tomllib`, `sqlite3` and a file.
|
|
39
|
+
|
|
40
|
+
## 60 seconds
|
|
41
|
+
|
|
42
|
+
`obstat.toml`:
|
|
43
|
+
|
|
44
|
+
```toml
|
|
45
|
+
[[rule]]
|
|
46
|
+
tool = "read_*"
|
|
47
|
+
effect = "allow"
|
|
48
|
+
|
|
49
|
+
[[rule]]
|
|
50
|
+
tool = "delete_*"
|
|
51
|
+
effect = "approve"
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
Your tool:
|
|
55
|
+
|
|
56
|
+
```python
|
|
57
|
+
from obstat import guard
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@guard(resource="doc:{doc_id}")
|
|
61
|
+
def delete_document(doc_id: str) -> str: ... # obstat has already decided this may happen
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
First call returns instead of running:
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
>>> delete_document("q3-report")
|
|
68
|
+
{'obstat': 'approval_required',
|
|
69
|
+
'approval_id': '4f1c2a9b8e07',
|
|
70
|
+
'expires_in_seconds': 900,
|
|
71
|
+
'retry': "A human must approve this call. Once approved, call the same tool
|
|
72
|
+
again with identical arguments plus obstat_approval_id='4f1c2a9b8e07'."}
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
A human decides:
|
|
76
|
+
|
|
77
|
+
```console
|
|
78
|
+
$ obstat pending
|
|
79
|
+
4f1c2a9b8e07 delete_document anonymous doc:q3-report 871s left
|
|
80
|
+
$ obstat approve 4f1c2a9b8e07
|
|
81
|
+
4f1c2a9b8e07 approved by ana
|
|
82
|
+
```
|
|
83
|
+
|
|
84
|
+
The agent retries with the id, the call runs, and `.obstat/decisions.jsonl` holds
|
|
85
|
+
the whole story.
|
|
86
|
+
|
|
87
|
+
## What it is not
|
|
88
|
+
|
|
89
|
+
There are several good libraries that gate MCP tool calls. This one is built
|
|
90
|
+
around a narrower claim: **the record is the product.** Three things follow from
|
|
91
|
+
that, and they are the reason to pick this over a permission wrapper.
|
|
92
|
+
|
|
93
|
+
**The decision is durable before the body runs.** Not flushed after, not written
|
|
94
|
+
in a `finally`, not batched. `record.decision()` returns only after `fsync`. A log
|
|
95
|
+
written after the fact is a story about what happened; a record written before it
|
|
96
|
+
is evidence of what was authorised. There is a test that runs inside a tool body,
|
|
97
|
+
reads the log off disk, and fails if its own decision record is not already there.
|
|
98
|
+
|
|
99
|
+
**Authorisation is per resource, not per tool.** A tier — READ, WRITE,
|
|
100
|
+
DESTRUCTIVE — cannot say "may edit their own ticket, not yours". obstat resolves
|
|
101
|
+
the resource from the call arguments and matches rules against it:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
@guard(resource="jira_issue:{issue_key}")
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
```toml
|
|
108
|
+
[[rule]]
|
|
109
|
+
subject = "human:ana"
|
|
110
|
+
resource = "jira_issue:ACME-*"
|
|
111
|
+
effect = "allow"
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
**An approval is bound to one call.** It carries the tool, the subject, the
|
|
115
|
+
resource and a digest of the arguments, and it is single-use. Approving "delete
|
|
116
|
+
q3-report" cannot be spent on deleting something else, and cannot be spent twice.
|
|
117
|
+
This is enforced in one `BEGIN IMMEDIATE` transaction, so two concurrent retries
|
|
118
|
+
cannot both win.
|
|
119
|
+
|
|
120
|
+
## Identity is optional
|
|
121
|
+
|
|
122
|
+
Most MCP servers today have no token at all: stdio, one local user, or a gateway
|
|
123
|
+
that already terminated auth. Demanding an identity provider before you can try a
|
|
124
|
+
governance library is why governance libraries go untried. An anonymous call is a
|
|
125
|
+
legitimate call here — it is recorded as `anonymous`, and the policy decides what
|
|
126
|
+
`anonymous` may do.
|
|
127
|
+
|
|
128
|
+
When you *do* have identity, hand it over:
|
|
129
|
+
|
|
130
|
+
```python
|
|
131
|
+
from obstat import Subject, set_subject_resolver
|
|
132
|
+
|
|
133
|
+
set_subject_resolver(lambda: Subject(id=current_user(), kind="human", verified=True))
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
`verified=False` is the honest flag for identity that came from somewhere a caller
|
|
137
|
+
could influence — a header, an argument. It is recorded, so a reader can tell the
|
|
138
|
+
difference between "Ana did this" and "something claimed to be Ana did this".
|
|
139
|
+
|
|
140
|
+
## Policy
|
|
141
|
+
|
|
142
|
+
First matching rule wins. Nothing matching is a deny — an absent rule is not
|
|
143
|
+
permission, and a missing policy file is an error rather than an implicit allow.
|
|
144
|
+
|
|
145
|
+
| key | matches | default |
|
|
146
|
+
|---|---|---|
|
|
147
|
+
| `tool` | the function name, or `tool=` on the decorator | `*` |
|
|
148
|
+
| `subject` | `human:ana`, `agent:planner`, `service:etl`, `anonymous` | `*` |
|
|
149
|
+
| `resource` | whatever the resource template produced | `*` |
|
|
150
|
+
| `effect` | `allow`, `deny`, `approve` | required |
|
|
151
|
+
|
|
152
|
+
Patterns are globs. The file is re-read when it changes, so editing policy does
|
|
153
|
+
not need a restart.
|
|
154
|
+
|
|
155
|
+
## The order
|
|
156
|
+
|
|
157
|
+
```
|
|
158
|
+
1 reject a caller-supplied subject
|
|
159
|
+
2 stop file
|
|
160
|
+
3 resolve the resource from the arguments
|
|
161
|
+
4 policy
|
|
162
|
+
5 approval, if policy asked for one
|
|
163
|
+
6 write the decision record — durable <-- before, not after
|
|
164
|
+
7 run the body
|
|
165
|
+
8 write the outcome — best effort
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
Step 1 exists because `subject` is stripped from the tool's advertised signature.
|
|
169
|
+
A client that sends one anyway is trying to name itself, and that is a denial
|
|
170
|
+
before anything reads the value.
|
|
171
|
+
|
|
172
|
+
Step 8 is deliberately not durable. If the process dies between 7 and 8 the record
|
|
173
|
+
reads "authorised, outcome unknown", which is the honest state; paying for a second
|
|
174
|
+
`fsync` to say something merely informative is the wrong trade.
|
|
175
|
+
|
|
176
|
+
## Operator commands
|
|
177
|
+
|
|
178
|
+
```console
|
|
179
|
+
obstat pending # approvals waiting on a human
|
|
180
|
+
obstat approve <id> [--by] # decide
|
|
181
|
+
obstat deny <id> [--by]
|
|
182
|
+
obstat log -n 50 # the decision record
|
|
183
|
+
obstat stop # deny every guarded call
|
|
184
|
+
obstat resume
|
|
185
|
+
```
|
|
186
|
+
|
|
187
|
+
`obstat stop` is checked before policy, so stopping never depends on the policy
|
|
188
|
+
file still being parseable.
|
|
189
|
+
|
|
190
|
+
## What is not here yet
|
|
191
|
+
|
|
192
|
+
Arguments are fingerprinted (`sha256:…`), never stored — tool arguments carry
|
|
193
|
+
credentials and personal data, and a governance log that leaks them is a liability
|
|
194
|
+
rather than a control. A per-key allowlist for recording chosen values is the
|
|
195
|
+
obvious next step.
|
|
196
|
+
|
|
197
|
+
Also absent, deliberately: retention and rotation of the log, Slack and webhook
|
|
198
|
+
approval channels, a policy for where a result may be *sent*, and anything that
|
|
199
|
+
talks to a cloud. Those belong at the edges, and the edges should be adapters
|
|
200
|
+
rather than dependencies.
|
|
201
|
+
|
|
202
|
+
## Configuration
|
|
203
|
+
|
|
204
|
+
| variable | default |
|
|
205
|
+
|---|---|
|
|
206
|
+
| `OBSTAT_POLICY` | `obstat.toml` |
|
|
207
|
+
| `OBSTAT_LOG` | `.obstat/decisions.jsonl` |
|
|
208
|
+
| `OBSTAT_DB` | `.obstat/approvals.db` |
|
|
209
|
+
| `OBSTAT_HALT` | `.obstat/halt` |
|
|
210
|
+
|
|
211
|
+
Read at call time, never at import. A library that raises on import is a library
|
|
212
|
+
you cannot try.
|
|
213
|
+
|
|
214
|
+
## License
|
|
215
|
+
|
|
216
|
+
Apache-2.0.
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
obstat/__init__.py,sha256=_aUFo10VnPb0dMqHr5I2YiPs6yMHT0AUeMdBCF2Z19M,387
|
|
2
|
+
obstat/__main__.py,sha256=Q_1QxvXrnAy6bf3oNZwxVXLyNssI5ZW1X9ihokvQV3M,2694
|
|
3
|
+
obstat/approval.py,sha256=0NIsog2d9g9HY8PudoBc9WL8DYLvjAAZc56_E2MiAeU,5092
|
|
4
|
+
obstat/guard.py,sha256=blRKl0z2mgFAvWs_xoETjqyH0uq484lnpqHdNF4w3IE,12120
|
|
5
|
+
obstat/paths.py,sha256=gfQKEgqNOf1aEv_JNzUlHTlM58TBvLV2v8yTvMV_Gz0,856
|
|
6
|
+
obstat/policy.py,sha256=ks2evlfu4gRlxktpFiRYsAaOQ8WZ10XmBaNN8l6BENw,3465
|
|
7
|
+
obstat/record.py,sha256=GJpOBHgwm0Uy9BcTw5Rvdo8ofMhLM1rXejhu4SgbMNI,3997
|
|
8
|
+
obstat-0.1.0.dist-info/METADATA,sha256=PW3Z11Z9O_UR2NtwzV2ZDlRoSCWENtzWyoIgrPGFJEo,7151
|
|
9
|
+
obstat-0.1.0.dist-info/WHEEL,sha256=lCkmxWfQsSc9CfIClYeavTdQeEX2toPqufh9gI35EQA,87
|
|
10
|
+
obstat-0.1.0.dist-info/entry_points.txt,sha256=kZZuze70AJ5aQHjtS1k5oeoAyC9jLlOUSHCjz6QSTEk,48
|
|
11
|
+
obstat-0.1.0.dist-info/licenses/LICENSE,sha256=z8d0m5b2O9McPEK1xHG_dWgUBT6EfBDz6wA0F7xSPTA,11358
|
|
12
|
+
obstat-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|