audit-autopilot 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.
- audit_autopilot/__init__.py +58 -0
- audit_autopilot/adapters.py +235 -0
- audit_autopilot/anonymizer.py +436 -0
- audit_autopilot/cli.py +264 -0
- audit_autopilot/models.py +222 -0
- audit_autopilot/pipeline.py +284 -0
- audit_autopilot/promote.py +116 -0
- audit_autopilot/py.typed +0 -0
- audit_autopilot-0.1.0.dist-info/METADATA +127 -0
- audit_autopilot-0.1.0.dist-info/RECORD +13 -0
- audit_autopilot-0.1.0.dist-info/WHEEL +5 -0
- audit_autopilot-0.1.0.dist-info/entry_points.txt +2 -0
- audit_autopilot-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
"""audit-autopilot: Domain-agnostic automated audit batching and isolated label pipeline."""
|
|
2
|
+
|
|
3
|
+
from audit_autopilot.adapters import (
|
|
4
|
+
AuditAdapter,
|
|
5
|
+
AuditValidationError,
|
|
6
|
+
MockAuditAdapter,
|
|
7
|
+
SubprocessJsonAdapter,
|
|
8
|
+
validate_audit_payload,
|
|
9
|
+
)
|
|
10
|
+
from audit_autopilot.anonymizer import (
|
|
11
|
+
AnonymizationContext,
|
|
12
|
+
anonymize_record_data,
|
|
13
|
+
check_no_pii_leak,
|
|
14
|
+
generate_regression_test_scaffold,
|
|
15
|
+
)
|
|
16
|
+
from audit_autopilot.models import (
|
|
17
|
+
ALLOWED_ACTIONS,
|
|
18
|
+
AuditResult,
|
|
19
|
+
CandidateRecord,
|
|
20
|
+
PromotionDiff,
|
|
21
|
+
RejectedAudit,
|
|
22
|
+
RunSummary,
|
|
23
|
+
)
|
|
24
|
+
from audit_autopilot.pipeline import (
|
|
25
|
+
generate_tests_from_candidate_labels,
|
|
26
|
+
load_candidate_pool,
|
|
27
|
+
run_audit_pipeline,
|
|
28
|
+
save_candidate_labels,
|
|
29
|
+
select_batch,
|
|
30
|
+
)
|
|
31
|
+
from audit_autopilot.promote import compute_promotion_diff, promote_candidates
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
"ALLOWED_ACTIONS",
|
|
35
|
+
"AnonymizationContext",
|
|
36
|
+
"AuditAdapter",
|
|
37
|
+
"AuditResult",
|
|
38
|
+
"AuditValidationError",
|
|
39
|
+
"CandidateRecord",
|
|
40
|
+
"MockAuditAdapter",
|
|
41
|
+
"PromotionDiff",
|
|
42
|
+
"RejectedAudit",
|
|
43
|
+
"RunSummary",
|
|
44
|
+
"SubprocessJsonAdapter",
|
|
45
|
+
"anonymize_record_data",
|
|
46
|
+
"check_no_pii_leak",
|
|
47
|
+
"compute_promotion_diff",
|
|
48
|
+
"generate_regression_test_scaffold",
|
|
49
|
+
"generate_tests_from_candidate_labels",
|
|
50
|
+
"load_candidate_pool",
|
|
51
|
+
"promote_candidates",
|
|
52
|
+
"run_audit_pipeline",
|
|
53
|
+
"save_candidate_labels",
|
|
54
|
+
"select_batch",
|
|
55
|
+
"validate_audit_payload",
|
|
56
|
+
]
|
|
57
|
+
|
|
58
|
+
__version__ = "0.1.0"
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
"""Pluggable audit adapters and strict schema/integrity validation."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hmac
|
|
6
|
+
import json
|
|
7
|
+
import subprocess
|
|
8
|
+
from datetime import datetime, timezone
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import Any, Callable, Protocol, Sequence, runtime_checkable
|
|
11
|
+
|
|
12
|
+
from audit_autopilot.models import ALLOWED_ACTIONS, AuditResult, CandidateRecord
|
|
13
|
+
|
|
14
|
+
ALLOWED_PAYLOAD_KEYS: frozenset[str] = frozenset(
|
|
15
|
+
{
|
|
16
|
+
"expected_action",
|
|
17
|
+
"root_cause_category",
|
|
18
|
+
"field_values",
|
|
19
|
+
"evidence",
|
|
20
|
+
"sha256",
|
|
21
|
+
"record_id",
|
|
22
|
+
}
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
REQUIRED_PAYLOAD_KEYS: frozenset[str] = frozenset(
|
|
26
|
+
{
|
|
27
|
+
"expected_action",
|
|
28
|
+
"root_cause_category",
|
|
29
|
+
"field_values",
|
|
30
|
+
"evidence",
|
|
31
|
+
"sha256",
|
|
32
|
+
}
|
|
33
|
+
)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class AuditValidationError(ValueError):
|
|
37
|
+
"""Raised when an adapter payload violates schema, type, or integrity checks."""
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _is_json_safe(value: Any, depth: int = 0) -> bool:
|
|
41
|
+
"""Verify that a value contains only JSON-serializable primitives and containers."""
|
|
42
|
+
if depth > 10:
|
|
43
|
+
return False
|
|
44
|
+
if value is None or isinstance(value, (str, int, float, bool)):
|
|
45
|
+
return True
|
|
46
|
+
if isinstance(value, list):
|
|
47
|
+
return all(_is_json_safe(item, depth + 1) for item in value)
|
|
48
|
+
if isinstance(value, dict):
|
|
49
|
+
return all(
|
|
50
|
+
isinstance(k, str) and _is_json_safe(v, depth + 1)
|
|
51
|
+
for k, v in value.items()
|
|
52
|
+
)
|
|
53
|
+
return False
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def validate_audit_payload(
|
|
57
|
+
payload: Any,
|
|
58
|
+
record: CandidateRecord,
|
|
59
|
+
adapter_name: str = "",
|
|
60
|
+
) -> AuditResult:
|
|
61
|
+
"""Validate an untrusted audit payload against strict schema and SHA-256 rules.
|
|
62
|
+
|
|
63
|
+
Protects against prompt injection and payload tampering by:
|
|
64
|
+
- Requiring a JSON object with only whitelisted top-level keys.
|
|
65
|
+
- Enforcing expected_action in ("submit", "hold", "unsupported").
|
|
66
|
+
- Requiring non-empty single-line root_cause_category.
|
|
67
|
+
- Requiring field_values to be a JSON-safe dict and evidence to be a string.
|
|
68
|
+
- Enforcing strict constant-time SHA-256 equality with the input record.
|
|
69
|
+
"""
|
|
70
|
+
if not isinstance(payload, dict):
|
|
71
|
+
raise AuditValidationError("Audit payload must be a JSON object.")
|
|
72
|
+
|
|
73
|
+
payload_keys = set(payload.keys())
|
|
74
|
+
unexpected = sorted(payload_keys - ALLOWED_PAYLOAD_KEYS)
|
|
75
|
+
if unexpected:
|
|
76
|
+
raise AuditValidationError(
|
|
77
|
+
f"Unexpected keys in audit payload (possible injection): {unexpected}"
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
missing = sorted(REQUIRED_PAYLOAD_KEYS - payload_keys)
|
|
81
|
+
if missing:
|
|
82
|
+
raise AuditValidationError(f"Missing required keys in audit payload: {missing}")
|
|
83
|
+
|
|
84
|
+
if "record_id" in payload:
|
|
85
|
+
payload_record_id = payload["record_id"]
|
|
86
|
+
if not isinstance(payload_record_id, str) or payload_record_id != record.record_id:
|
|
87
|
+
raise AuditValidationError(
|
|
88
|
+
f"Payload record_id mismatch: expected '{record.record_id}', got {payload_record_id!r}."
|
|
89
|
+
)
|
|
90
|
+
|
|
91
|
+
payload_sha256 = payload["sha256"]
|
|
92
|
+
if not isinstance(payload_sha256, str) or not payload_sha256.strip():
|
|
93
|
+
raise AuditValidationError("Payload 'sha256' must be a non-empty string.")
|
|
94
|
+
if not hmac.compare_digest(payload_sha256.strip(), record.sha256.strip()):
|
|
95
|
+
raise AuditValidationError(
|
|
96
|
+
"Payload 'sha256' does not match input record SHA-256."
|
|
97
|
+
)
|
|
98
|
+
|
|
99
|
+
expected_action = payload["expected_action"]
|
|
100
|
+
if not isinstance(expected_action, str) or expected_action not in ALLOWED_ACTIONS:
|
|
101
|
+
raise AuditValidationError(
|
|
102
|
+
f"Invalid 'expected_action': {expected_action!r}. Must be one of {ALLOWED_ACTIONS}."
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
root_cause = payload["root_cause_category"]
|
|
106
|
+
if not isinstance(root_cause, str) or not root_cause.strip():
|
|
107
|
+
raise AuditValidationError("'root_cause_category' must be a non-empty string.")
|
|
108
|
+
if any(ch in root_cause for ch in ("\n", "\r", "\x00")):
|
|
109
|
+
raise AuditValidationError(
|
|
110
|
+
"'root_cause_category' must not contain control or newline characters."
|
|
111
|
+
)
|
|
112
|
+
if len(root_cause.strip()) > 128:
|
|
113
|
+
raise AuditValidationError("'root_cause_category' exceeds maximum length of 128.")
|
|
114
|
+
|
|
115
|
+
field_values = payload["field_values"]
|
|
116
|
+
if not isinstance(field_values, dict) or not _is_json_safe(field_values):
|
|
117
|
+
raise AuditValidationError("'field_values' must be a JSON-safe object.")
|
|
118
|
+
|
|
119
|
+
evidence = payload["evidence"]
|
|
120
|
+
if not isinstance(evidence, str):
|
|
121
|
+
raise AuditValidationError("'evidence' must be a string.")
|
|
122
|
+
|
|
123
|
+
audited_at = datetime.now(timezone.utc).isoformat()
|
|
124
|
+
return AuditResult(
|
|
125
|
+
record_id=record.record_id,
|
|
126
|
+
sha256=record.sha256,
|
|
127
|
+
expected_action=expected_action,
|
|
128
|
+
root_cause_category=root_cause.strip(),
|
|
129
|
+
field_values=dict(field_values),
|
|
130
|
+
evidence=evidence,
|
|
131
|
+
reason_bucket=record.reason_bucket,
|
|
132
|
+
audited_at=audited_at,
|
|
133
|
+
adapter_name=adapter_name,
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
@runtime_checkable
|
|
138
|
+
class AuditAdapter(Protocol):
|
|
139
|
+
"""Protocol implemented by all pluggable audit adapters."""
|
|
140
|
+
|
|
141
|
+
name: str
|
|
142
|
+
|
|
143
|
+
def audit(self, record: CandidateRecord) -> dict[str, Any]:
|
|
144
|
+
"""Run an audit for a single CandidateRecord and return a raw payload dict."""
|
|
145
|
+
...
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
class MockAuditAdapter:
|
|
149
|
+
"""Deterministic in-memory audit adapter for testing and local workflows."""
|
|
150
|
+
|
|
151
|
+
name: str = "mock"
|
|
152
|
+
|
|
153
|
+
def __init__(
|
|
154
|
+
self,
|
|
155
|
+
responses: dict[str, dict[str, Any]] | None = None,
|
|
156
|
+
handler: Callable[[CandidateRecord], dict[str, Any]] | None = None,
|
|
157
|
+
default_action: str = "hold",
|
|
158
|
+
) -> None:
|
|
159
|
+
self._responses = dict(responses) if responses is not None else {}
|
|
160
|
+
self._handler = handler
|
|
161
|
+
self._default_action = default_action
|
|
162
|
+
|
|
163
|
+
def audit(self, record: CandidateRecord) -> dict[str, Any]:
|
|
164
|
+
"""Return a configured or deterministic mock audit payload."""
|
|
165
|
+
if record.record_id in self._responses:
|
|
166
|
+
return dict(self._responses[record.record_id])
|
|
167
|
+
if self._handler is not None:
|
|
168
|
+
return self._handler(record)
|
|
169
|
+
return {
|
|
170
|
+
"record_id": record.record_id,
|
|
171
|
+
"sha256": record.sha256,
|
|
172
|
+
"expected_action": self._default_action,
|
|
173
|
+
"root_cause_category": record.reason_bucket or "general_mismatch",
|
|
174
|
+
"field_values": dict(record.extracted_fields),
|
|
175
|
+
"evidence": f"Mock audit verified blocker '{record.reason_bucket}' on artifact.",
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
class SubprocessJsonAdapter:
|
|
180
|
+
"""Audit adapter that invokes an external command via stdin/stdout JSON."""
|
|
181
|
+
|
|
182
|
+
name: str = "subprocess_json"
|
|
183
|
+
|
|
184
|
+
def __init__(
|
|
185
|
+
self,
|
|
186
|
+
command: Sequence[str],
|
|
187
|
+
timeout_seconds: float = 30.0,
|
|
188
|
+
cwd: str | Path | None = None,
|
|
189
|
+
) -> None:
|
|
190
|
+
if not command:
|
|
191
|
+
raise ValueError("SubprocessJsonAdapter requires a non-empty command.")
|
|
192
|
+
self._command = list(command)
|
|
193
|
+
self._timeout_seconds = timeout_seconds
|
|
194
|
+
self._cwd = str(cwd) if cwd is not None else None
|
|
195
|
+
|
|
196
|
+
def audit(self, record: CandidateRecord) -> dict[str, Any]:
|
|
197
|
+
"""Serialize record to stdin JSON and parse stdout JSON response."""
|
|
198
|
+
request_json = json.dumps(record.to_dict(), ensure_ascii=False)
|
|
199
|
+
try:
|
|
200
|
+
proc = subprocess.run(
|
|
201
|
+
self._command,
|
|
202
|
+
input=request_json,
|
|
203
|
+
capture_output=True,
|
|
204
|
+
text=True,
|
|
205
|
+
timeout=self._timeout_seconds,
|
|
206
|
+
cwd=self._cwd,
|
|
207
|
+
check=False,
|
|
208
|
+
)
|
|
209
|
+
except subprocess.TimeoutExpired as exc:
|
|
210
|
+
raise AuditValidationError(
|
|
211
|
+
f"Subprocess adapter timed out after {self._timeout_seconds}s."
|
|
212
|
+
) from exc
|
|
213
|
+
except OSError as exc:
|
|
214
|
+
raise AuditValidationError(f"Failed to execute subprocess adapter: {exc}") from exc
|
|
215
|
+
|
|
216
|
+
if proc.returncode != 0:
|
|
217
|
+
stderr_preview = (proc.stderr or "").strip()[:300]
|
|
218
|
+
raise AuditValidationError(
|
|
219
|
+
f"Subprocess adapter exited with code {proc.returncode}: {stderr_preview}"
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
raw_stdout = (proc.stdout or "").strip()
|
|
223
|
+
if not raw_stdout:
|
|
224
|
+
raise AuditValidationError("Subprocess adapter returned empty stdout.")
|
|
225
|
+
|
|
226
|
+
try:
|
|
227
|
+
parsed = json.loads(raw_stdout)
|
|
228
|
+
except json.JSONDecodeError as exc:
|
|
229
|
+
raise AuditValidationError(
|
|
230
|
+
f"Subprocess adapter returned invalid JSON: {exc}"
|
|
231
|
+
) from exc
|
|
232
|
+
|
|
233
|
+
if not isinstance(parsed, dict):
|
|
234
|
+
raise AuditValidationError("Subprocess adapter JSON output must be an object.")
|
|
235
|
+
return parsed
|