audit-autopilot 0.1.0__tar.gz
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-0.1.0/PKG-INFO +127 -0
- audit_autopilot-0.1.0/README.md +109 -0
- audit_autopilot-0.1.0/pyproject.toml +38 -0
- audit_autopilot-0.1.0/setup.cfg +4 -0
- audit_autopilot-0.1.0/src/audit_autopilot/__init__.py +58 -0
- audit_autopilot-0.1.0/src/audit_autopilot/adapters.py +235 -0
- audit_autopilot-0.1.0/src/audit_autopilot/anonymizer.py +436 -0
- audit_autopilot-0.1.0/src/audit_autopilot/cli.py +264 -0
- audit_autopilot-0.1.0/src/audit_autopilot/models.py +222 -0
- audit_autopilot-0.1.0/src/audit_autopilot/pipeline.py +284 -0
- audit_autopilot-0.1.0/src/audit_autopilot/promote.py +116 -0
- audit_autopilot-0.1.0/src/audit_autopilot/py.typed +0 -0
- audit_autopilot-0.1.0/src/audit_autopilot.egg-info/PKG-INFO +127 -0
- audit_autopilot-0.1.0/src/audit_autopilot.egg-info/SOURCES.txt +17 -0
- audit_autopilot-0.1.0/src/audit_autopilot.egg-info/dependency_links.txt +1 -0
- audit_autopilot-0.1.0/src/audit_autopilot.egg-info/entry_points.txt +2 -0
- audit_autopilot-0.1.0/src/audit_autopilot.egg-info/top_level.txt +1 -0
- audit_autopilot-0.1.0/tests/test_pipeline.py +554 -0
- audit_autopilot-0.1.0/tests/test_sanitization.py +87 -0
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: audit-autopilot
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Domain-agnostic automated audit batching, strict schema validation, isolated candidate label management, and anonymized regression test generation.
|
|
5
|
+
Author: audit-autopilot contributors
|
|
6
|
+
License: MIT
|
|
7
|
+
Keywords: audit,evaluation,regression-testing,anonymization,cli
|
|
8
|
+
Classifier: Development Status :: 3 - Alpha
|
|
9
|
+
Classifier: Intended Audience :: Developers
|
|
10
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
11
|
+
Classifier: Programming Language :: Python :: 3
|
|
12
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
13
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
14
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Python: >=3.10
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
|
|
19
|
+
# audit-autopilot
|
|
20
|
+
|
|
21
|
+
A domain-agnostic, zero-dependency Python 3.10+ toolkit for automated audit batch selection, pluggable audit execution with strict schema and hash verification, isolated candidate label storage, controlled label promotion, and anonymized regression test scaffold generation.
|
|
22
|
+
|
|
23
|
+
## Key Capabilities
|
|
24
|
+
|
|
25
|
+
- **Batch Selection**: Reads candidate pool JSON (compatible with ranker/sampler outputs) and selects up to `N` unaudited, single-blocker records that include required artifacts per reason bucket, while tracking missing-evidence counts by bucket.
|
|
26
|
+
- **Pluggable Audit Adapters**: Includes an `AuditAdapter` protocol, a deterministic `MockAuditAdapter` for local runs and testing, and a `SubprocessJsonAdapter` for integrating external audit workers over stdin/stdout JSON.
|
|
27
|
+
- **Tampering & Prompt-Injection Defense**: Enforces strict JSON schema validation (`expected_action` in `submit`, `hold`, `unsupported`; non-empty `root_cause_category`; `field_values` dict; `evidence` string; strict `sha256` equality with the input record; rejection of unexpected keys). Invalid or tampered responses are safely rejected without crashing the batch.
|
|
28
|
+
- **Strict Label Isolation**: Writes newly audited results exclusively to an isolated `candidate_labels.json` file and never modifies `production_labels.json` during audit runs.
|
|
29
|
+
- **Controlled Promotion**: Provides a `promote` subcommand that defaults to `--dry-run` (showing added/updated/unchanged diffs) and requires explicit `--approve` to merge selected candidates into a target production labels file.
|
|
30
|
+
- **Anonymized Regression Test Generation**: When `>= 3` audited candidates share the same `root_cause_category`, replaces entity names, store names, phone numbers, registration IDs, emails, and raw amounts with deterministic placeholders (`ENTITY_001`, `STORE_001`, `000-0000-0000`, `1000`, etc.), generates a `layout_of(...)` style `unittest` scaffold, and verifies zero PII leakage via `check_no_pii_leak`.
|
|
31
|
+
|
|
32
|
+
## Installation
|
|
33
|
+
|
|
34
|
+
Requires Python 3.10+ with zero third-party runtime dependencies.
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install -e .
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Or run directly from source:
|
|
41
|
+
|
|
42
|
+
```bash
|
|
43
|
+
PYTHONPATH=src python -m audit_autopilot.cli --help
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
## CLI Usage
|
|
47
|
+
|
|
48
|
+
### 1. Run an audit batch
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
audit-autopilot run \
|
|
52
|
+
--pool candidate_pool.json \
|
|
53
|
+
--candidate-labels candidate_labels.json \
|
|
54
|
+
--production-labels production_labels.json \
|
|
55
|
+
--max-per-bucket 5 \
|
|
56
|
+
--adapter mock \
|
|
57
|
+
--tests-dir generated_tests \
|
|
58
|
+
--format table
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Use `--format json` to emit the structured run summary JSON (`audited_count`, `rejected_count`, `by_root_cause`, `pending_promotion_count`, `generated_test_files`, `missing_evidence_by_bucket`).
|
|
62
|
+
|
|
63
|
+
### 2. Preview and promote candidate labels
|
|
64
|
+
|
|
65
|
+
Preview diff (default dry-run, never modifies the target file):
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
audit-autopilot promote \
|
|
69
|
+
--candidate-labels candidate_labels.json \
|
|
70
|
+
--production-labels production_labels.json \
|
|
71
|
+
--format table
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
Apply promotion explicitly:
|
|
75
|
+
|
|
76
|
+
```bash
|
|
77
|
+
audit-autopilot promote \
|
|
78
|
+
--candidate-labels candidate_labels.json \
|
|
79
|
+
--production-labels production_labels.json \
|
|
80
|
+
--approve
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Filter to specific records with repeatable `--record-id`:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
audit-autopilot promote \
|
|
87
|
+
--candidate-labels candidate_labels.json \
|
|
88
|
+
--production-labels production_labels.json \
|
|
89
|
+
--record-id rec-001 \
|
|
90
|
+
--record-id rec-002 \
|
|
91
|
+
--approve
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### 3. Generate anonymized regression tests from candidate labels
|
|
95
|
+
|
|
96
|
+
```bash
|
|
97
|
+
audit-autopilot generate-tests \
|
|
98
|
+
--candidate-labels candidate_labels.json \
|
|
99
|
+
--output-dir generated_tests \
|
|
100
|
+
--min-cluster-size 3 \
|
|
101
|
+
--format json
|
|
102
|
+
```
|
|
103
|
+
|
|
104
|
+
## Running Tests
|
|
105
|
+
|
|
106
|
+
```bash
|
|
107
|
+
PYTHONPATH=src python -m unittest discover -s tests -v
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Project Structure
|
|
111
|
+
|
|
112
|
+
```text
|
|
113
|
+
src/audit_autopilot/
|
|
114
|
+
__init__.py Public package exports
|
|
115
|
+
models.py Typed dataclasses for records, results, summaries, and diffs
|
|
116
|
+
adapters.py AuditAdapter protocol, strict validator, MockAuditAdapter, SubprocessJsonAdapter
|
|
117
|
+
anonymizer.py Deterministic anonymizer, PII leak verifier, unittest scaffold generator
|
|
118
|
+
pipeline.py Batch selector, isolated label persistence, end-to-end runner
|
|
119
|
+
promote.py Dry-run diffing and explicit-approval promotion logic
|
|
120
|
+
cli.py Command-line interface (run, promote, generate-tests)
|
|
121
|
+
py.typed PEP 561 type marker
|
|
122
|
+
docs/
|
|
123
|
+
REQUIREMENTS.md Functional and safety requirements specification
|
|
124
|
+
tests/
|
|
125
|
+
test_pipeline.py End-to-end pipeline, isolation, validation, and promotion tests
|
|
126
|
+
test_sanitization.py Repository hygiene and confidentiality checks
|
|
127
|
+
```
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
# audit-autopilot
|
|
2
|
+
|
|
3
|
+
A domain-agnostic, zero-dependency Python 3.10+ toolkit for automated audit batch selection, pluggable audit execution with strict schema and hash verification, isolated candidate label storage, controlled label promotion, and anonymized regression test scaffold generation.
|
|
4
|
+
|
|
5
|
+
## Key Capabilities
|
|
6
|
+
|
|
7
|
+
- **Batch Selection**: Reads candidate pool JSON (compatible with ranker/sampler outputs) and selects up to `N` unaudited, single-blocker records that include required artifacts per reason bucket, while tracking missing-evidence counts by bucket.
|
|
8
|
+
- **Pluggable Audit Adapters**: Includes an `AuditAdapter` protocol, a deterministic `MockAuditAdapter` for local runs and testing, and a `SubprocessJsonAdapter` for integrating external audit workers over stdin/stdout JSON.
|
|
9
|
+
- **Tampering & Prompt-Injection Defense**: Enforces strict JSON schema validation (`expected_action` in `submit`, `hold`, `unsupported`; non-empty `root_cause_category`; `field_values` dict; `evidence` string; strict `sha256` equality with the input record; rejection of unexpected keys). Invalid or tampered responses are safely rejected without crashing the batch.
|
|
10
|
+
- **Strict Label Isolation**: Writes newly audited results exclusively to an isolated `candidate_labels.json` file and never modifies `production_labels.json` during audit runs.
|
|
11
|
+
- **Controlled Promotion**: Provides a `promote` subcommand that defaults to `--dry-run` (showing added/updated/unchanged diffs) and requires explicit `--approve` to merge selected candidates into a target production labels file.
|
|
12
|
+
- **Anonymized Regression Test Generation**: When `>= 3` audited candidates share the same `root_cause_category`, replaces entity names, store names, phone numbers, registration IDs, emails, and raw amounts with deterministic placeholders (`ENTITY_001`, `STORE_001`, `000-0000-0000`, `1000`, etc.), generates a `layout_of(...)` style `unittest` scaffold, and verifies zero PII leakage via `check_no_pii_leak`.
|
|
13
|
+
|
|
14
|
+
## Installation
|
|
15
|
+
|
|
16
|
+
Requires Python 3.10+ with zero third-party runtime dependencies.
|
|
17
|
+
|
|
18
|
+
```bash
|
|
19
|
+
pip install -e .
|
|
20
|
+
```
|
|
21
|
+
|
|
22
|
+
Or run directly from source:
|
|
23
|
+
|
|
24
|
+
```bash
|
|
25
|
+
PYTHONPATH=src python -m audit_autopilot.cli --help
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## CLI Usage
|
|
29
|
+
|
|
30
|
+
### 1. Run an audit batch
|
|
31
|
+
|
|
32
|
+
```bash
|
|
33
|
+
audit-autopilot run \
|
|
34
|
+
--pool candidate_pool.json \
|
|
35
|
+
--candidate-labels candidate_labels.json \
|
|
36
|
+
--production-labels production_labels.json \
|
|
37
|
+
--max-per-bucket 5 \
|
|
38
|
+
--adapter mock \
|
|
39
|
+
--tests-dir generated_tests \
|
|
40
|
+
--format table
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
Use `--format json` to emit the structured run summary JSON (`audited_count`, `rejected_count`, `by_root_cause`, `pending_promotion_count`, `generated_test_files`, `missing_evidence_by_bucket`).
|
|
44
|
+
|
|
45
|
+
### 2. Preview and promote candidate labels
|
|
46
|
+
|
|
47
|
+
Preview diff (default dry-run, never modifies the target file):
|
|
48
|
+
|
|
49
|
+
```bash
|
|
50
|
+
audit-autopilot promote \
|
|
51
|
+
--candidate-labels candidate_labels.json \
|
|
52
|
+
--production-labels production_labels.json \
|
|
53
|
+
--format table
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Apply promotion explicitly:
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
audit-autopilot promote \
|
|
60
|
+
--candidate-labels candidate_labels.json \
|
|
61
|
+
--production-labels production_labels.json \
|
|
62
|
+
--approve
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
Filter to specific records with repeatable `--record-id`:
|
|
66
|
+
|
|
67
|
+
```bash
|
|
68
|
+
audit-autopilot promote \
|
|
69
|
+
--candidate-labels candidate_labels.json \
|
|
70
|
+
--production-labels production_labels.json \
|
|
71
|
+
--record-id rec-001 \
|
|
72
|
+
--record-id rec-002 \
|
|
73
|
+
--approve
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
### 3. Generate anonymized regression tests from candidate labels
|
|
77
|
+
|
|
78
|
+
```bash
|
|
79
|
+
audit-autopilot generate-tests \
|
|
80
|
+
--candidate-labels candidate_labels.json \
|
|
81
|
+
--output-dir generated_tests \
|
|
82
|
+
--min-cluster-size 3 \
|
|
83
|
+
--format json
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
## Running Tests
|
|
87
|
+
|
|
88
|
+
```bash
|
|
89
|
+
PYTHONPATH=src python -m unittest discover -s tests -v
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
## Project Structure
|
|
93
|
+
|
|
94
|
+
```text
|
|
95
|
+
src/audit_autopilot/
|
|
96
|
+
__init__.py Public package exports
|
|
97
|
+
models.py Typed dataclasses for records, results, summaries, and diffs
|
|
98
|
+
adapters.py AuditAdapter protocol, strict validator, MockAuditAdapter, SubprocessJsonAdapter
|
|
99
|
+
anonymizer.py Deterministic anonymizer, PII leak verifier, unittest scaffold generator
|
|
100
|
+
pipeline.py Batch selector, isolated label persistence, end-to-end runner
|
|
101
|
+
promote.py Dry-run diffing and explicit-approval promotion logic
|
|
102
|
+
cli.py Command-line interface (run, promote, generate-tests)
|
|
103
|
+
py.typed PEP 561 type marker
|
|
104
|
+
docs/
|
|
105
|
+
REQUIREMENTS.md Functional and safety requirements specification
|
|
106
|
+
tests/
|
|
107
|
+
test_pipeline.py End-to-end pipeline, isolation, validation, and promotion tests
|
|
108
|
+
test_sanitization.py Repository hygiene and confidentiality checks
|
|
109
|
+
```
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68.0"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "audit-autopilot"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Domain-agnostic automated audit batching, strict schema validation, isolated candidate label management, and anonymized regression test generation."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [
|
|
13
|
+
{ name = "audit-autopilot contributors" }
|
|
14
|
+
]
|
|
15
|
+
keywords = ["audit", "evaluation", "regression-testing", "anonymization", "cli"]
|
|
16
|
+
classifiers = [
|
|
17
|
+
"Development Status :: 3 - Alpha",
|
|
18
|
+
"Intended Audience :: Developers",
|
|
19
|
+
"License :: OSI Approved :: MIT License",
|
|
20
|
+
"Programming Language :: Python :: 3",
|
|
21
|
+
"Programming Language :: Python :: 3.10",
|
|
22
|
+
"Programming Language :: Python :: 3.11",
|
|
23
|
+
"Programming Language :: Python :: 3.12",
|
|
24
|
+
"Typing :: Typed",
|
|
25
|
+
]
|
|
26
|
+
dependencies = []
|
|
27
|
+
|
|
28
|
+
[project.scripts]
|
|
29
|
+
audit-autopilot = "audit_autopilot.cli:main"
|
|
30
|
+
|
|
31
|
+
[tool.setuptools]
|
|
32
|
+
package-dir = { "" = "src" }
|
|
33
|
+
|
|
34
|
+
[tool.setuptools.packages.find]
|
|
35
|
+
where = ["src"]
|
|
36
|
+
|
|
37
|
+
[tool.setuptools.package-data]
|
|
38
|
+
audit_autopilot = ["py.typed"]
|
|
@@ -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
|