auditgate 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.
auditgate/__init__.py ADDED
@@ -0,0 +1,46 @@
1
+ """AuditGate: Compliance-grade audit logging for agent systems."""
2
+
3
+ from .core import (
4
+ MISSING,
5
+ AuditEntry,
6
+ AuditPolicy,
7
+ Decision,
8
+ IntegrityMode,
9
+ Mode,
10
+ Result,
11
+ Severity,
12
+ Status,
13
+ StoreErrorMode,
14
+ Trail,
15
+ Verdict,
16
+ compute_hash,
17
+ verify_chain,
18
+ wall_clock,
19
+ )
20
+ from .engine import AuditError, Engine
21
+ from .store import MemoryStore, QueryFilter, Store
22
+
23
+ __all__ = [
24
+ "Trail",
25
+ "AuditPolicy",
26
+ "AuditEntry",
27
+ "Decision",
28
+ "Result",
29
+ "MISSING",
30
+ "compute_hash",
31
+ "verify_chain",
32
+ "wall_clock",
33
+ "Mode",
34
+ "Status",
35
+ "Severity",
36
+ "Verdict",
37
+ "IntegrityMode",
38
+ "StoreErrorMode",
39
+ "Engine",
40
+ "AuditError",
41
+ "Store",
42
+ "MemoryStore",
43
+ "QueryFilter",
44
+ ]
45
+
46
+ __version__ = "0.1.0"
auditgate/core.py ADDED
@@ -0,0 +1,229 @@
1
+ """Core types for AuditGate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import json
7
+ from dataclasses import dataclass, field
8
+ from datetime import datetime, timezone
9
+ from enum import Enum, auto
10
+ from typing import Any
11
+
12
+
13
+ class Mode(Enum):
14
+ """Enforcement mode for audit failures."""
15
+ HARD = auto()
16
+ SOFT = auto()
17
+
18
+
19
+ class StoreErrorMode(Enum):
20
+ """Behavior when audit store backend fails."""
21
+ FAIL_CLOSED = auto()
22
+ FAIL_OPEN = auto()
23
+
24
+
25
+ class Status(Enum):
26
+ """Audit recording outcome."""
27
+ RECORDED = auto()
28
+ DROPPED = auto()
29
+
30
+
31
+ class Severity(Enum):
32
+ """Audit entry severity level."""
33
+ DEBUG = auto()
34
+ INFO = auto()
35
+ WARN = auto()
36
+ ERROR = auto()
37
+ CRITICAL = auto()
38
+
39
+
40
+ class Verdict(Enum):
41
+ """Outcome of the gate decision being audited."""
42
+ ALLOW = auto()
43
+ BLOCK = auto()
44
+ ERROR = auto()
45
+ OVERRIDE = auto()
46
+
47
+
48
+ class IntegrityMode(Enum):
49
+ """Tamper-evidence mode for audit entries."""
50
+ NONE = auto()
51
+ HASH = auto()
52
+ CHAIN = auto()
53
+
54
+
55
+ @dataclass(frozen=True, slots=True)
56
+ class Trail:
57
+ """Identifies an audit trail (log stream)."""
58
+ namespace: str
59
+ source: str
60
+ principal: str = "global"
61
+
62
+ def __str__(self) -> str:
63
+ return f"{self.namespace}:{self.source}@{self.principal}"
64
+
65
+ @property
66
+ def key(self) -> str:
67
+ return f"aud:{self.namespace}:{self.source}:{self.principal}"
68
+
69
+
70
+ @dataclass(frozen=True, slots=True)
71
+ class AuditPolicy:
72
+ """Configuration for an audit trail."""
73
+ mode: Mode = Mode.HARD
74
+ on_store_error: StoreErrorMode = StoreErrorMode.FAIL_CLOSED
75
+ min_severity: Severity = Severity.DEBUG
76
+ retention_seconds: float | None = None
77
+ integrity: IntegrityMode = IntegrityMode.HASH
78
+
79
+ def __post_init__(self) -> None:
80
+ if self.retention_seconds is not None and self.retention_seconds <= 0:
81
+ raise ValueError("retention_seconds must be positive or None")
82
+
83
+
84
+ @dataclass(frozen=True, slots=True)
85
+ class AuditEntry:
86
+ """A single audit log entry."""
87
+ trail: Trail
88
+ ts: float
89
+ wall_ts: str
90
+ verdict: Verdict
91
+ severity: Severity
92
+ gate_type: str
93
+ gate_identity: str
94
+ recorded_by: str = ""
95
+ reason: str | None = None
96
+ detail: dict[str, Any] = field(default_factory=dict)
97
+ entry_hash: str | None = None
98
+ prev_hash: str | None = None
99
+ sequence: int = 0
100
+
101
+ def to_dict(self) -> dict[str, Any]:
102
+ """Canonical JSON-portable format for cross-language compatibility."""
103
+ return {
104
+ "trail": str(self.trail),
105
+ "ts": self.ts,
106
+ "wall_ts": self.wall_ts,
107
+ "verdict": self.verdict.name,
108
+ "severity": self.severity.name,
109
+ "gate_type": self.gate_type,
110
+ "gate_identity": self.gate_identity,
111
+ "recorded_by": self.recorded_by,
112
+ "reason": self.reason,
113
+ "detail": self.detail,
114
+ "entry_hash": self.entry_hash,
115
+ "prev_hash": self.prev_hash,
116
+ "sequence": self.sequence,
117
+ }
118
+
119
+
120
+ @dataclass(frozen=True, slots=True)
121
+ class Decision:
122
+ """Result of attempting to record an audit entry."""
123
+ status: Status
124
+ trail: Trail
125
+ policy: AuditPolicy
126
+ entry: AuditEntry | None = None
127
+ reason: str | None = None
128
+
129
+ @property
130
+ def recorded(self) -> bool:
131
+ return self.status == Status.RECORDED
132
+
133
+ @property
134
+ def dropped(self) -> bool:
135
+ return self.status == Status.DROPPED
136
+
137
+ def __bool__(self) -> bool:
138
+ return self.recorded
139
+
140
+
141
+ class _Missing:
142
+ """Sentinel for distinguishing None from missing value."""
143
+ __slots__ = ()
144
+ def __repr__(self) -> str:
145
+ return "<MISSING>"
146
+
147
+
148
+ MISSING = _Missing()
149
+
150
+
151
+ @dataclass(frozen=True, slots=True)
152
+ class Result[T]:
153
+ """Wrapper for guarded function results."""
154
+ decision: Decision
155
+ _value: T | _Missing = field(default=MISSING)
156
+
157
+ @property
158
+ def ok(self) -> bool:
159
+ return self.decision.recorded
160
+
161
+ def unwrap(self) -> T:
162
+ if isinstance(self._value, _Missing):
163
+ raise RuntimeError(
164
+ f"unwrap() called on dropped audit: {self.decision.reason}"
165
+ )
166
+ return self._value # type: ignore[return-value]
167
+
168
+ def unwrap_or(self, default: T) -> T:
169
+ if isinstance(self._value, _Missing):
170
+ return default
171
+ return self._value # type: ignore[return-value]
172
+
173
+
174
+ # ── Integrity ──
175
+
176
+ def compute_hash(
177
+ entry_data: dict[str, Any],
178
+ prev_hash: str | None = None,
179
+ ) -> str:
180
+ """Deterministic SHA-256 content hash over canonical JSON."""
181
+ hashable = {
182
+ "trail": entry_data.get("trail", ""),
183
+ "ts": entry_data.get("ts", 0),
184
+ "verdict": entry_data.get("verdict", ""),
185
+ "severity": entry_data.get("severity", ""),
186
+ "gate_type": entry_data.get("gate_type", ""),
187
+ "gate_identity": entry_data.get("gate_identity", ""),
188
+ "reason": entry_data.get("reason"),
189
+ "detail": entry_data.get("detail", {}),
190
+ "sequence": entry_data.get("sequence", 0),
191
+ }
192
+ if prev_hash is not None:
193
+ hashable["prev_hash"] = prev_hash
194
+ canonical = json.dumps(hashable, sort_keys=True, separators=(",", ":"))
195
+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()
196
+
197
+
198
+ def verify_chain(entries: list[AuditEntry]) -> tuple[bool, int | None]:
199
+ """Verify hash chain integrity. Returns (valid, broken_at)."""
200
+ for i, entry in enumerate(entries):
201
+ if entry.entry_hash is None:
202
+ continue
203
+
204
+ base_data = {
205
+ "trail": str(entry.trail),
206
+ "ts": entry.ts,
207
+ "verdict": entry.verdict.name,
208
+ "severity": entry.severity.name,
209
+ "gate_type": entry.gate_type,
210
+ "gate_identity": entry.gate_identity,
211
+ "reason": entry.reason,
212
+ "detail": entry.detail,
213
+ "sequence": entry.sequence,
214
+ }
215
+
216
+ expected = compute_hash(base_data, prev_hash=entry.prev_hash)
217
+ if entry.entry_hash != expected:
218
+ return False, entry.sequence
219
+
220
+ if entry.prev_hash is not None and i > 0:
221
+ if entries[i - 1].entry_hash != entry.prev_hash:
222
+ return False, entry.sequence
223
+
224
+ return True, None
225
+
226
+
227
+ def wall_clock() -> str:
228
+ """Current wall-clock time as ISO 8601 UTC."""
229
+ return datetime.now(timezone.utc).isoformat()
auditgate/engine.py ADDED
@@ -0,0 +1,266 @@
1
+ """AuditGate engine for compliance-grade audit logging."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import time
6
+ from functools import wraps
7
+ from typing import Any, Callable, ParamSpec, TypeVar
8
+
9
+ from .core import (
10
+ MISSING,
11
+ AuditEntry,
12
+ AuditPolicy,
13
+ Decision,
14
+ IntegrityMode,
15
+ Mode,
16
+ Result,
17
+ Severity,
18
+ Status,
19
+ StoreErrorMode,
20
+ Trail,
21
+ Verdict,
22
+ compute_hash,
23
+ wall_clock,
24
+ )
25
+ from .store import MemoryStore, Store
26
+
27
+ P = ParamSpec("P")
28
+ T = TypeVar("T")
29
+
30
+
31
+ class AuditError(RuntimeError):
32
+ """Raised when audit logging fails in HARD mode."""
33
+
34
+ def __init__(self, decision: Decision) -> None:
35
+ super().__init__(decision.reason or f"Audit failure: {decision.status}")
36
+ self.decision = decision
37
+
38
+
39
+ class Engine:
40
+ """AuditGate engine for compliance-grade audit logging."""
41
+
42
+ __slots__ = (
43
+ "_store", "_clock", "_wall_clock", "_recorded_by",
44
+ "_policies", "_sequences", "_listeners", "_errors",
45
+ )
46
+
47
+ def __init__(
48
+ self,
49
+ store: Store | None = None,
50
+ clock: Callable[[], float] | None = None,
51
+ wall_clock_fn: Callable[[], str] | None = None,
52
+ recorded_by: str = "",
53
+ ) -> None:
54
+ self._store: Store = store or MemoryStore()
55
+ self._clock = clock or time.monotonic
56
+ self._wall_clock = wall_clock_fn or wall_clock
57
+ self._recorded_by = recorded_by
58
+ self._policies: dict[Trail, AuditPolicy] = {}
59
+ self._sequences: dict[Trail, int] = {}
60
+ self._listeners: list[Callable[[Decision], None]] = []
61
+ self._errors = 0
62
+
63
+ # ── Configuration ──
64
+
65
+ def register(self, trail: Trail, policy: AuditPolicy) -> None:
66
+ self._policies[trail] = policy
67
+
68
+ def policy_for(self, trail: Trail) -> AuditPolicy | None:
69
+ return self._policies.get(trail)
70
+
71
+ def on_decision(self, listener: Callable[[Decision], None]) -> None:
72
+ self._listeners.append(listener)
73
+
74
+ @property
75
+ def listener_errors(self) -> int:
76
+ return self._errors
77
+
78
+ # ── Core API ──
79
+
80
+ def record(
81
+ self,
82
+ trail: Trail,
83
+ *,
84
+ verdict: Verdict,
85
+ severity: Severity,
86
+ gate_type: str,
87
+ gate_identity: str,
88
+ reason: str | None = None,
89
+ detail: dict[str, Any] | None = None,
90
+ policy: AuditPolicy | None = None,
91
+ ) -> Decision:
92
+ """Record an audit entry for a gate decision."""
93
+ if policy is not None:
94
+ self._policies[trail] = policy
95
+
96
+ p = self._policies.get(trail)
97
+ if p is None:
98
+ p = AuditPolicy()
99
+ self._policies[trail] = p
100
+
101
+ if _sev_rank(severity) < _sev_rank(p.min_severity):
102
+ return self._decide(trail, p, Status.DROPPED,
103
+ reason=f"Below min_severity ({p.min_severity.name})")
104
+
105
+ now = self._clock()
106
+
107
+ try:
108
+ entry = self._build_entry(trail, p, now, verdict, severity,
109
+ gate_type, gate_identity, reason, detail or {})
110
+ except Exception as exc:
111
+ return self._on_store_error(trail, p, f"Entry build failed: {exc}")
112
+
113
+ try:
114
+ self._store.append(entry)
115
+ except Exception as exc:
116
+ return self._on_store_error(trail, p, f"Store append failed: {exc}")
117
+
118
+ if p.retention_seconds is not None:
119
+ try:
120
+ self._store.prune(trail, now - p.retention_seconds)
121
+ except Exception:
122
+ pass
123
+
124
+ return self._decide(trail, p, Status.RECORDED, entry=entry)
125
+
126
+ def enforce(self, decision: Decision) -> None:
127
+ """Raise AuditError if dropped in HARD mode."""
128
+ if decision.dropped and decision.policy.mode == Mode.HARD:
129
+ raise AuditError(decision)
130
+
131
+ def clear(self, trail: Trail) -> None:
132
+ self._store.clear(trail)
133
+ self._sequences.pop(trail, None)
134
+
135
+ def clear_all(self) -> None:
136
+ self._store.clear_all()
137
+ self._sequences.clear()
138
+
139
+ # ── Decorator API ──
140
+
141
+ def guard(
142
+ self,
143
+ trail: Trail,
144
+ *,
145
+ policy: AuditPolicy | None = None,
146
+ verdict: Verdict = Verdict.ALLOW,
147
+ severity: Severity = Severity.INFO,
148
+ gate_type: str = "auditgate",
149
+ meta: dict[str, Any] | None = None,
150
+ ) -> Callable[[Callable[P, T]], Callable[P, T]]:
151
+ """Decorator that audits function calls. Raises on audit failure."""
152
+ if policy is not None:
153
+ self.register(trail, policy)
154
+
155
+ def decorator(fn: Callable[P, T]) -> Callable[P, T]:
156
+ @wraps(fn)
157
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
158
+ d = self._guard_record(trail, verdict, severity, gate_type, fn, meta)
159
+ if d.dropped:
160
+ self.enforce(d)
161
+ return fn(*args, **kwargs)
162
+ return wrapper
163
+ return decorator
164
+
165
+ def guard_result(
166
+ self,
167
+ trail: Trail,
168
+ *,
169
+ policy: AuditPolicy | None = None,
170
+ verdict: Verdict = Verdict.ALLOW,
171
+ severity: Severity = Severity.INFO,
172
+ gate_type: str = "auditgate",
173
+ meta: dict[str, Any] | None = None,
174
+ ) -> Callable[[Callable[P, T]], Callable[P, Result[T]]]:
175
+ """Decorator that audits function calls. Returns Result instead of raising."""
176
+ if policy is not None:
177
+ self.register(trail, policy)
178
+
179
+ def decorator(fn: Callable[P, T]) -> Callable[P, Result[T]]:
180
+ @wraps(fn)
181
+ def wrapper(*args: P.args, **kwargs: P.kwargs) -> Result[T]:
182
+ d = self._guard_record(trail, verdict, severity, gate_type, fn, meta,
183
+ prefix="guard_result")
184
+ if d.dropped:
185
+ return Result(decision=d)
186
+ return Result(decision=d, _value=fn(*args, **kwargs))
187
+ return wrapper
188
+ return decorator
189
+
190
+ # ── Internal ──
191
+
192
+ def _guard_record(
193
+ self, trail: Trail, verdict: Verdict, severity: Severity,
194
+ gate_type: str, fn: Callable, meta: dict[str, Any] | None,
195
+ prefix: str = "guard",
196
+ ) -> Decision:
197
+ return self.record(
198
+ trail=trail, verdict=verdict, severity=severity,
199
+ gate_type=gate_type, gate_identity=str(trail),
200
+ reason=f"{prefix}:{fn.__qualname__}", detail=meta or {},
201
+ )
202
+
203
+ def _build_entry(
204
+ self, trail: Trail, policy: AuditPolicy, now: float,
205
+ verdict: Verdict, severity: Severity, gate_type: str,
206
+ gate_identity: str, reason: str | None, detail: dict[str, Any],
207
+ ) -> AuditEntry:
208
+ seq = self._next_seq(trail)
209
+ base = {
210
+ "trail": str(trail), "ts": now,
211
+ "verdict": verdict.name, "severity": severity.name,
212
+ "gate_type": gate_type, "gate_identity": gate_identity,
213
+ "reason": reason, "detail": detail, "sequence": seq,
214
+ }
215
+
216
+ entry_hash: str | None = None
217
+ prev_hash: str | None = None
218
+
219
+ if policy.integrity == IntegrityMode.HASH:
220
+ entry_hash = compute_hash(base)
221
+ elif policy.integrity == IntegrityMode.CHAIN:
222
+ prev = self._store.last_entry(trail)
223
+ prev_hash = prev.entry_hash if prev is not None else None
224
+ entry_hash = compute_hash(base, prev_hash=prev_hash)
225
+
226
+ return AuditEntry(
227
+ trail=trail, ts=now, wall_ts=self._wall_clock(),
228
+ verdict=verdict, severity=severity,
229
+ gate_type=gate_type, gate_identity=gate_identity,
230
+ recorded_by=self._recorded_by, reason=reason, detail=detail,
231
+ entry_hash=entry_hash, prev_hash=prev_hash, sequence=seq,
232
+ )
233
+
234
+ def _next_seq(self, trail: Trail) -> int:
235
+ if trail not in self._sequences:
236
+ last = self._store.last_entry(trail)
237
+ self._sequences[trail] = (last.sequence + 1) if last is not None else 0
238
+ seq = self._sequences[trail]
239
+ self._sequences[trail] = seq + 1
240
+ return seq
241
+
242
+ def _on_store_error(self, trail: Trail, policy: AuditPolicy, msg: str) -> Decision:
243
+ decision = self._decide(trail, policy, Status.DROPPED, reason=msg)
244
+ if policy.on_store_error == StoreErrorMode.FAIL_CLOSED and policy.mode == Mode.HARD:
245
+ raise AuditError(decision)
246
+ return decision
247
+
248
+ def _decide(
249
+ self, trail: Trail, policy: AuditPolicy, status: Status,
250
+ entry: AuditEntry | None = None, reason: str | None = None,
251
+ ) -> Decision:
252
+ d = Decision(status=status, trail=trail, policy=policy, entry=entry, reason=reason)
253
+ self._emit(d)
254
+ return d
255
+
256
+ def _emit(self, decision: Decision) -> None:
257
+ for listener in self._listeners:
258
+ try:
259
+ listener(decision)
260
+ except Exception:
261
+ self._errors += 1
262
+
263
+
264
+ def _sev_rank(severity: Severity) -> int:
265
+ return {Severity.DEBUG: 0, Severity.INFO: 1, Severity.WARN: 2,
266
+ Severity.ERROR: 3, Severity.CRITICAL: 4}[severity]
auditgate/py.typed ADDED
File without changes
auditgate/store.py ADDED
@@ -0,0 +1,130 @@
1
+ """Storage backends for AuditGate."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import threading
6
+ from dataclasses import dataclass
7
+ from typing import Protocol, Sequence
8
+
9
+ from .core import AuditEntry, Severity, Trail, Verdict
10
+
11
+
12
+ @dataclass(frozen=True, slots=True)
13
+ class QueryFilter:
14
+ """Filter criteria for querying audit entries."""
15
+ trail: Trail | None = None
16
+ verdict: Verdict | None = None
17
+ min_severity: Severity | None = None
18
+ after_ts: float | None = None
19
+ before_ts: float | None = None
20
+ gate_type: str | None = None
21
+ offset: int = 0
22
+ limit: int | None = None
23
+
24
+
25
+ class Store(Protocol):
26
+ """Protocol for audit storage backends. Must be thread-safe."""
27
+
28
+ def append(self, entry: AuditEntry) -> None: ...
29
+ def query(self, filter: QueryFilter) -> Sequence[AuditEntry]: ...
30
+ def last_entry(self, trail: Trail) -> AuditEntry | None: ...
31
+ def count(self, trail: Trail) -> int: ...
32
+ def prune(self, trail: Trail, before_ts: float) -> int: ...
33
+ def clear(self, trail: Trail) -> None: ...
34
+ def clear_all(self) -> None: ...
35
+
36
+
37
+ _SEV_ORDER: dict[Severity, int] = {
38
+ Severity.DEBUG: 0, Severity.INFO: 1, Severity.WARN: 2,
39
+ Severity.ERROR: 3, Severity.CRITICAL: 4,
40
+ }
41
+
42
+
43
+ class MemoryStore:
44
+ """Thread-safe in-memory audit store."""
45
+
46
+ __slots__ = ("_trails", "_locks", "_global_lock")
47
+
48
+ def __init__(self) -> None:
49
+ self._trails: dict[Trail, list[AuditEntry]] = {}
50
+ self._locks: dict[Trail, threading.Lock] = {}
51
+ self._global_lock = threading.Lock()
52
+
53
+ def _get_lock(self, trail: Trail) -> threading.Lock:
54
+ with self._global_lock:
55
+ if trail not in self._locks:
56
+ self._locks[trail] = threading.Lock()
57
+ return self._locks[trail]
58
+
59
+ def append(self, entry: AuditEntry) -> None:
60
+ lock = self._get_lock(entry.trail)
61
+ with lock:
62
+ if entry.trail not in self._trails:
63
+ self._trails[entry.trail] = []
64
+ self._trails[entry.trail].append(entry)
65
+
66
+ def query(self, filter: QueryFilter) -> Sequence[AuditEntry]:
67
+ with self._global_lock:
68
+ if filter.trail is not None:
69
+ keys = [filter.trail] if filter.trail in self._trails else []
70
+ else:
71
+ keys = list(self._trails.keys())
72
+
73
+ results: list[AuditEntry] = []
74
+ for k in keys:
75
+ lock = self._get_lock(k)
76
+ with lock:
77
+ for entry in self._trails.get(k, []):
78
+ if self._matches(entry, filter):
79
+ results.append(entry)
80
+
81
+ results.sort(key=lambda e: (e.ts, e.sequence))
82
+ if filter.offset > 0:
83
+ results = results[filter.offset:]
84
+ if filter.limit is not None:
85
+ results = results[:filter.limit]
86
+ return results
87
+
88
+ def last_entry(self, trail: Trail) -> AuditEntry | None:
89
+ lock = self._get_lock(trail)
90
+ with lock:
91
+ entries = self._trails.get(trail)
92
+ return entries[-1] if entries else None
93
+
94
+ def count(self, trail: Trail) -> int:
95
+ lock = self._get_lock(trail)
96
+ with lock:
97
+ return len(self._trails.get(trail, []))
98
+
99
+ def prune(self, trail: Trail, before_ts: float) -> int:
100
+ lock = self._get_lock(trail)
101
+ with lock:
102
+ entries = self._trails.get(trail, [])
103
+ original = len(entries)
104
+ self._trails[trail] = [e for e in entries if e.ts >= before_ts]
105
+ return original - len(self._trails[trail])
106
+
107
+ def clear(self, trail: Trail) -> None:
108
+ lock = self._get_lock(trail)
109
+ with lock:
110
+ self._trails.pop(trail, None)
111
+
112
+ def clear_all(self) -> None:
113
+ with self._global_lock:
114
+ self._trails.clear()
115
+ self._locks.clear()
116
+
117
+ @staticmethod
118
+ def _matches(entry: AuditEntry, filter: QueryFilter) -> bool:
119
+ if filter.verdict is not None and entry.verdict != filter.verdict:
120
+ return False
121
+ if filter.min_severity is not None:
122
+ if _SEV_ORDER[entry.severity] < _SEV_ORDER[filter.min_severity]:
123
+ return False
124
+ if filter.after_ts is not None and entry.ts < filter.after_ts:
125
+ return False
126
+ if filter.before_ts is not None and entry.ts > filter.before_ts:
127
+ return False
128
+ if filter.gate_type is not None and entry.gate_type != filter.gate_type:
129
+ return False
130
+ return True
@@ -0,0 +1,200 @@
1
+ Metadata-Version: 2.4
2
+ Name: auditgate
3
+ Version: 0.1.0
4
+ Summary: Compliance-grade audit logging for agent systems.
5
+ Project-URL: Homepage, https://github.com/actiongate-oss/auditgate
6
+ Project-URL: Documentation, https://github.com/actiongate-oss/auditgate#readme
7
+ Project-URL: Repository, https://github.com/actiongate-oss/auditgate
8
+ Author-email: ActionGate OSS <actiongate-oss@users.noreply.github.com>
9
+ License-Expression: BUSL-1.1
10
+ License-File: LICENSE
11
+ Keywords: ai-agents,audit,compliance,llm,tamper-evident
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: Other/Proprietary License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.12
17
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
18
+ Classifier: Typing :: Typed
19
+ Requires-Python: >=3.12
20
+ Provides-Extra: dev
21
+ Requires-Dist: mypy>=1.0; extra == 'dev'
22
+ Requires-Dist: pytest-cov>=4.0; extra == 'dev'
23
+ Requires-Dist: pytest>=8.0; extra == 'dev'
24
+ Requires-Dist: ruff>=0.1; extra == 'dev'
25
+ Description-Content-Type: text/markdown
26
+
27
+ # AuditGate
28
+
29
+ **Compliance-grade audit logging for agent systems.**
30
+
31
+ Every decision, every verdict, every override — structured, queryable, and tamper-evident.
32
+
33
+ ```bash
34
+ pip install auditgate
35
+ ```
36
+
37
+ ---
38
+
39
+ ## What It Does
40
+
41
+ AuditGate records every gate decision as a structured audit entry with optional tamper-evidence via content hashing or hash chaining. It pairs with [ActionGate](https://github.com/actiongate-oss/actiongate), [BudgetGate](https://github.com/actiongate-oss/budgetgate), and [RuleGate](https://github.com/actiongate-oss/rulegate) as the fourth composable primitive in the agent execution layer.
42
+
43
+ AuditGate does **not** make allow/block decisions. It records what other gates decided and guarantees the record exists.
44
+
45
+ **Vendoring encouraged.** This is a small, stable primitive. Copy it, fork it, reimplement it. If you vendor AuditGate, you must preserve the LICENSE file, preserve copyright headers in source files, and not remove or modify the BSL terms. The production use restriction applies to vendored copies. See [SEMANTICS.md](SEMANTICS.md) for the behavioral contract if you reimplement.
46
+
47
+ ## Quick Start
48
+
49
+ ```python
50
+ from auditgate import (
51
+ Engine, Trail, AuditPolicy, Verdict, Severity, IntegrityMode
52
+ )
53
+
54
+ engine = Engine()
55
+
56
+ # Define an audit trail with hash chain integrity
57
+ trail = Trail("billing", "actiongate", "user:123")
58
+ policy = AuditPolicy(integrity=IntegrityMode.CHAIN)
59
+ engine.register(trail, policy)
60
+
61
+ # Record a decision from ActionGate
62
+ decision = engine.record(
63
+ trail=trail,
64
+ verdict=Verdict.ALLOW,
65
+ severity=Severity.INFO,
66
+ gate_type="actiongate",
67
+ gate_identity="billing:refund@user:123",
68
+ reason="Rate limit check passed",
69
+ detail={"calls_in_window": 3, "max_calls": 10},
70
+ )
71
+
72
+ assert decision.recorded
73
+ assert decision.entry.entry_hash is not None
74
+ ```
75
+
76
+ ## Integrity Modes
77
+
78
+ | Mode | Behavior | Use Case |
79
+ |---------|----------|----------|
80
+ | `NONE` | No hashing | Maximum throughput, trust the store |
81
+ | `HASH` | SHA-256 per entry | Detect tampering of individual entries |
82
+ | `CHAIN` | Hash includes previous entry's hash | Detect tampering or deletion of any entry |
83
+
84
+ ## Failure Modes
85
+
86
+ | Policy | Behavior |
87
+ |--------|----------|
88
+ | `HARD` + `FAIL_CLOSED` | No action can proceed without a recorded audit entry |
89
+ | `HARD` + `FAIL_OPEN` | Raises on failure but allows unaudited actions |
90
+ | `SOFT` + `FAIL_CLOSED` | Returns DROPPED decision, caller decides |
91
+ | `SOFT` + `FAIL_OPEN` | Fire-and-forget audit (best-effort) |
92
+
93
+ ## Decorator API
94
+
95
+ ```python
96
+ # Raises AuditError if audit recording fails (HARD mode default)
97
+ @engine.guard(
98
+ Trail("api", "combined", "global"),
99
+ policy=AuditPolicy(integrity=IntegrityMode.HASH),
100
+ severity=Severity.INFO,
101
+ gate_type="auditgate",
102
+ )
103
+ def process_order(order_id: str) -> dict:
104
+ return {"status": "processed", "id": order_id}
105
+
106
+ # Or use guard_result for no-exception handling
107
+ @engine.guard_result(
108
+ Trail("api", "combined", "global"),
109
+ policy=AuditPolicy(mode=Mode.SOFT),
110
+ severity=Severity.INFO,
111
+ gate_type="auditgate",
112
+ )
113
+ def fetch_data(query: str) -> list:
114
+ return db.search(query)
115
+
116
+ result = fetch_data(query="recent orders")
117
+ data = result.unwrap_or([])
118
+ ```
119
+
120
+ ## Querying the Audit Trail
121
+
122
+ ```python
123
+ from auditgate import QueryFilter, Verdict, Severity
124
+
125
+ # All blocked decisions in the last hour
126
+ entries = engine._store.query(QueryFilter(
127
+ trail=trail,
128
+ verdict=Verdict.BLOCK,
129
+ after_ts=time.monotonic() - 3600,
130
+ ))
131
+
132
+ # All critical events across all trails
133
+ critical = engine._store.query(QueryFilter(
134
+ min_severity=Severity.CRITICAL,
135
+ ))
136
+ ```
137
+
138
+ ## Composing with Other Gates
139
+
140
+ ```python
141
+ from actiongate import Engine as ActionEngine, Gate, Policy
142
+ from auditgate import Engine as AuditEngine, Trail, AuditPolicy, Verdict, Severity
143
+
144
+ action_engine = ActionEngine()
145
+ audit_engine = AuditEngine()
146
+
147
+ trail = Trail("api", "actiongate", "global")
148
+ audit_engine.register(trail, AuditPolicy())
149
+
150
+ # Listen to ActionGate decisions and auto-audit them
151
+ def audit_listener(action_decision):
152
+ audit_engine.record(
153
+ trail=trail,
154
+ verdict=Verdict.ALLOW if action_decision.allowed else Verdict.BLOCK,
155
+ severity=Severity.INFO if action_decision.allowed else Severity.WARN,
156
+ gate_type="actiongate",
157
+ gate_identity=str(action_decision.gate),
158
+ reason=str(action_decision.reason) if action_decision.reason else None,
159
+ )
160
+
161
+ action_engine.on_decision(audit_listener)
162
+ ```
163
+
164
+ ## Performance
165
+
166
+ Sub-20µs per audit entry with MemoryStore and SHA-256 hashing (benchmarked). Hash chain mode adds negligible overhead. For context, a single LLM API call is 200ms–2s.
167
+
168
+ ## File Structure
169
+
170
+ ```
171
+ auditgate/
172
+ ├── __init__.py # Public API, exports, version
173
+ ├── core.py # All value types (Trail, AuditPolicy, AuditEntry, Decision, Result)
174
+ ├── engine.py # Engine class (record, guard, guard_result)
175
+ └── store.py # Store protocol + MemoryStore
176
+ ```
177
+
178
+ ## Specification
179
+
180
+ See [SEMANTICS.md](SEMANTICS.md) for the normative behavior specification. When this document and the code conflict, the specification governs.
181
+
182
+ ## License
183
+
184
+ AuditGate is licensed under the [Business Source License 1.1](LICENSE).
185
+
186
+ ```
187
+ Licensor: actiongate-oss
188
+ Licensed Work: AuditGate
189
+ Additional Use Grant: None
190
+ Change Date: 2030-02-28 (four years from initial publication)
191
+ Change License: Mozilla Public License 2.0
192
+ ```
193
+
194
+ **What this means:** You may copy, modify, create derivative works, redistribute, and make non-production use of AuditGate. The Additional Use Grant is "None", which means any use in a live environment that provides value to end users or internal business operations — including SaaS, internal enterprise deployment, and paid betas — requires a commercial license from the licensor. On the Change Date, AuditGate becomes available under [MPL 2.0](https://www.mozilla.org/en-US/MPL/2.0/) and the production restriction terminates. Each version has its own Change Date calculated from its publication.
195
+
196
+ **If you vendor AuditGate:** Preserve the LICENSE file and copyright headers. Do not remove or modify the BSL terms. The production restriction applies to all copies, vendored or otherwise.
197
+
198
+ **Licensing difference from siblings:** [ActionGate](https://github.com/actiongate-oss/actiongate) and [BudgetGate](https://github.com/actiongate-oss/budgetgate) are Apache 2.0. AuditGate is BSL 1.1. If composing all three, ensure your use complies with both license terms.
199
+
200
+ See [LICENSE](LICENSE) for the legally binding text.
@@ -0,0 +1,9 @@
1
+ auditgate/__init__.py,sha256=-IoNAVxMrXz123D_fo9HY8fpaGlDN075ztykeMnvOxU,777
2
+ auditgate/core.py,sha256=Xqkh_E-6tW1kHzyseZR4kq3QYerdU5qa3pBTsjXYAng,6303
3
+ auditgate/engine.py,sha256=kYRPHncOJwbAwElDecakjLsnj-1qDD-wlhi-Rlv6vbw,8995
4
+ auditgate/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
5
+ auditgate/store.py,sha256=Qc3Tb_5EN5A1i82yxYbuM0kwPsDQBM1m5TXssyZBy7I,4428
6
+ auditgate-0.1.0.dist-info/METADATA,sha256=uTY6A40g85QlLNz9rMbRAIiAkenvJBqxfmpTImoCHgw,7610
7
+ auditgate-0.1.0.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
8
+ auditgate-0.1.0.dist-info/licenses/LICENSE,sha256=KNgpFwRANZuqhI7xCqS2jIIN3u8MhcSfH7rYrEZpnUM,4128
9
+ auditgate-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.29.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,96 @@
1
+ Business Source License 1.1
2
+
3
+ License text copyright (c) 2017 MariaDB Corporation Ab, All Rights
4
+ Reserved. “Business Source License” is a trademark of MariaDB
5
+ Corporation Ab.
6
+
7
+ ------------------------------------------------------------------------
8
+
9
+ Parameters
10
+
11
+ Licensor: actiongate-oss Licensed Work: AuditGate Additional Use Grant:
12
+ None Change Date: February 28, 2030 Change License: Mozilla Public
13
+ License 2.0
14
+
15
+ ------------------------------------------------------------------------
16
+
17
+ Terms
18
+
19
+ The Licensor hereby grants you the right to copy, modify, create
20
+ derivative works, redistribute, and make non-production use of the
21
+ Licensed Work. The Licensor may make an Additional Use Grant, above,
22
+ permitting limited production use.
23
+
24
+ Effective on the Change Date, or the fourth anniversary of the first
25
+ publicly available distribution of a specific version of the Licensed
26
+ Work under this License, whichever comes first, the Licensor hereby
27
+ grants you rights under the terms of the Change License, and the rights
28
+ granted in the paragraph above terminate.
29
+
30
+ If your use of the Licensed Work does not comply with the requirements
31
+ currently in effect as described in this License, you must purchase a
32
+ commercial license from the Licensor, its affiliated entities, or
33
+ authorized resellers, or you must refrain from using the Licensed Work.
34
+
35
+ All copies of the original and modified Licensed Work, and derivative
36
+ works of the Licensed Work, are subject to this License. This License
37
+ applies separately for each version of the Licensed Work and the Change
38
+ Date may vary for each version of the Licensed Work released by
39
+ Licensor.
40
+
41
+ You must conspicuously display this License on each original or modified
42
+ copy of the Licensed Work. If you receive the Licensed Work in original
43
+ or modified form from a third party, the terms and conditions set forth
44
+ in this License apply to your use of that work.
45
+
46
+ Any use of the Licensed Work in violation of this License will
47
+ automatically terminate your rights under this License for the current
48
+ and all other versions of the Licensed Work.
49
+
50
+ This License does not grant you any right in any trademark or logo of
51
+ Licensor or its affiliates (provided that you may use a trademark or
52
+ logo of Licensor as expressly required by this License).
53
+
54
+ TO THE EXTENT PERMITTED BY APPLICABLE LAW, THE LICENSED WORK IS PROVIDED
55
+ ON AN “AS IS” BASIS. LICENSOR HEREBY DISCLAIMS ALL WARRANTIES AND
56
+ CONDITIONS, EXPRESS OR IMPLIED, INCLUDING (WITHOUT LIMITATION)
57
+ WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
58
+ NON-INFRINGEMENT, AND TITLE.
59
+
60
+ MariaDB hereby grants you permission to use this License’s text to
61
+ license your works, and to refer to it using the trademark “Business
62
+ Source License”, as long as you comply with the Covenants of Licensor
63
+ below.
64
+
65
+ ------------------------------------------------------------------------
66
+
67
+ Covenants of Licensor
68
+
69
+ In consideration of the right to use this License’s text and the
70
+ “Business Source License” name and trademark, Licensor covenants to
71
+ MariaDB, and to all other recipients of the licensed work to be provided
72
+ by Licensor:
73
+
74
+ 1. To specify as the Change License the GPL Version 2.0 or any later
75
+ version, or a license that is compatible with GPL Version 2.0 or a
76
+ later version, where “compatible” means that software provided under
77
+ the Change License can be included in a program with software
78
+ provided under GPL Version 2.0 or a later version. Licensor may
79
+ specify additional Change Licenses without limitation.
80
+
81
+ 2. To either: (a) specify an additional grant of rights to use that
82
+ does not impose any additional restriction on the right granted in
83
+ this License, as the Additional Use Grant; or (b) insert the text
84
+ “None”.
85
+
86
+ 3. To specify a Change Date.
87
+
88
+ 4. Not to modify this License in any other way.
89
+
90
+ ------------------------------------------------------------------------
91
+
92
+ Notice
93
+
94
+ The Business Source License (this document, or the “License”) is not an
95
+ Open Source license. However, the Licensed Work will eventually be made
96
+ available under an Open Source License, as stated in this License.