aiauditlog 0.1.0a3__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.
@@ -0,0 +1,45 @@
1
+ """Public Python API for AIAuditLog."""
2
+
3
+ from ai_audit_log.builder import EventBuilder
4
+ from ai_audit_log.chain import ChainVerifier, append_integrity
5
+ from ai_audit_log.checkpoint import Checkpoint
6
+ from ai_audit_log.checkpoint_policy import CheckpointSignaturePolicy, verify_checkpoint_policy
7
+ from ai_audit_log.compression import gzip_file
8
+ from ai_audit_log.digest import event_digest
9
+ from ai_audit_log.migration import MigrationResult, migrate_event_document
10
+ from ai_audit_log.models import AuditEvent, Outcome, Source
11
+ from ai_audit_log.otel import correlation_from_traceparent, traceparent_from_correlation
12
+ from ai_audit_log.privacy import PrivacyMode, PrivacyProfile, redact_value
13
+ from ai_audit_log.recorder import AuditRecorder
14
+ from ai_audit_log.rotation import RotationDecision, RotationPolicy
15
+ from ai_audit_log.signatures import Ed25519KeyPair
16
+ from ai_audit_log.storage import JsonlStore, SQLiteIndex
17
+
18
+ __all__ = [
19
+ "AuditEvent",
20
+ "AuditRecorder",
21
+ "ChainVerifier",
22
+ "Checkpoint",
23
+ "CheckpointSignaturePolicy",
24
+ "Ed25519KeyPair",
25
+ "EventBuilder",
26
+ "JsonlStore",
27
+ "MigrationResult",
28
+ "Outcome",
29
+ "PrivacyMode",
30
+ "PrivacyProfile",
31
+ "RotationDecision",
32
+ "RotationPolicy",
33
+ "SQLiteIndex",
34
+ "Source",
35
+ "append_integrity",
36
+ "correlation_from_traceparent",
37
+ "event_digest",
38
+ "gzip_file",
39
+ "migrate_event_document",
40
+ "redact_value",
41
+ "traceparent_from_correlation",
42
+ "verify_checkpoint_policy",
43
+ ]
44
+
45
+ __version__ = "0.1.0a3"
@@ -0,0 +1,35 @@
1
+ """Framework-neutral adapter protocols."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Protocol
6
+
7
+ from ai_audit_log.models import AuditEvent
8
+
9
+
10
+ class EventAdapter(Protocol):
11
+ """Protocol for turning framework-native records into audit events."""
12
+
13
+ def to_audit_event(self, value: Any) -> AuditEvent:
14
+ """Convert a framework record into an AuditEvent."""
15
+
16
+
17
+ class PolicyDecisionAdapter(Protocol):
18
+ """Protocol prepared for AgentPolicyPack-style decisions."""
19
+
20
+ def decision_payload(self, value: Any) -> dict[str, Any]:
21
+ """Return a policy payload dictionary."""
22
+
23
+
24
+ class OntologyContextAdapter(Protocol):
25
+ """Protocol prepared for OpenOntologyLite-style context."""
26
+
27
+ def ontology_context(self, value: Any) -> dict[str, Any]:
28
+ """Return ontology context."""
29
+
30
+
31
+ class BenchmarkContextAdapter(Protocol):
32
+ """Protocol prepared for ModelSwapBench-style context."""
33
+
34
+ def benchmark_context(self, value: Any) -> dict[str, Any]:
35
+ """Return benchmark context."""
@@ -0,0 +1,48 @@
1
+ """Safe event builder."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from typing import Any
7
+
8
+ from ai_audit_log.ids import new_event_id
9
+ from ai_audit_log.models import Actor, AuditEvent, Outcome, Source, payload_for_event
10
+ from ai_audit_log.privacy import PrivacyProfile, redact_value
11
+ from ai_audit_log.time import now_utc
12
+
13
+
14
+ class EventBuilder:
15
+ """Create validated, privacy-filtered audit events."""
16
+
17
+ def __init__(self, *, source: Source, actor: Actor, privacy: PrivacyProfile | None = None) -> None:
18
+ self.source = source
19
+ self.actor = actor
20
+ self.privacy = privacy or PrivacyProfile()
21
+
22
+ def create(
23
+ self,
24
+ *,
25
+ event_type: str,
26
+ outcome: Outcome,
27
+ data: dict[str, Any] | None = None,
28
+ event_time: datetime | None = None,
29
+ recorded_time: datetime | None = None,
30
+ event_id: str | None = None,
31
+ **extra: Any,
32
+ ) -> AuditEvent:
33
+ """Create one event."""
34
+
35
+ raw_data = data or {}
36
+ payload_for_event(event_type, raw_data)
37
+ filtered_data = redact_value(raw_data, self.privacy)
38
+ return AuditEvent(
39
+ event_id=event_id or new_event_id(),
40
+ event_type=event_type,
41
+ event_time=event_time or now_utc(),
42
+ recorded_time=recorded_time or now_utc(),
43
+ source=self.source,
44
+ actor=self.actor,
45
+ outcome=outcome,
46
+ data=filtered_data,
47
+ **extra,
48
+ )
@@ -0,0 +1,60 @@
1
+ """AIAuditLog canonical JSON profile.
2
+
3
+ This profile normalizes AIAuditLog-specific Python values and then delegates
4
+ JSON byte serialization to the maintained ``rfc8785`` package.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import math
10
+ from datetime import date, datetime
11
+ from decimal import Decimal
12
+ from typing import Any
13
+
14
+ import rfc8785
15
+
16
+ from ai_audit_log.exceptions import CanonicalizationError
17
+ from ai_audit_log.time import format_rfc3339
18
+
19
+
20
+ def normalize_for_json(value: Any) -> Any:
21
+ """Convert supported Python values to deterministic JSON-compatible values."""
22
+
23
+ if value is None or isinstance(value, bool | str | int):
24
+ return value
25
+ if isinstance(value, float):
26
+ if not math.isfinite(value):
27
+ raise CanonicalizationError("NaN and Infinity are unsupported")
28
+ return value
29
+ if isinstance(value, Decimal):
30
+ if not value.is_finite():
31
+ raise CanonicalizationError("non-finite Decimal values are unsupported")
32
+ return format(value.normalize(), "f")
33
+ if isinstance(value, datetime):
34
+ return format_rfc3339(value)
35
+ if isinstance(value, date):
36
+ return value.isoformat()
37
+ if isinstance(value, bytes):
38
+ return value.hex()
39
+ if isinstance(value, list | tuple):
40
+ return [normalize_for_json(item) for item in value]
41
+ if isinstance(value, dict):
42
+ normalized: dict[str, Any] = {}
43
+ for key, item in value.items():
44
+ if not isinstance(key, str):
45
+ raise CanonicalizationError("JSON object keys must be strings")
46
+ normalized[key] = normalize_for_json(item)
47
+ return normalized
48
+ if hasattr(value, "model_dump"):
49
+ return normalize_for_json(value.model_dump(mode="python", exclude_none=True))
50
+ raise CanonicalizationError(f"unsupported canonical value type: {type(value).__name__}")
51
+
52
+
53
+ def canonical_json_bytes(value: Any) -> bytes:
54
+ """Return RFC 8785 canonical UTF-8 JSON bytes for supported values."""
55
+
56
+ normalized = normalize_for_json(value)
57
+ try:
58
+ return rfc8785.dumps(normalized)
59
+ except rfc8785.CanonicalizationError as exc:
60
+ raise CanonicalizationError(str(exc)) from exc
ai_audit_log/chain.py ADDED
@@ -0,0 +1,99 @@
1
+ """Hash-chain append and verification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+
7
+ from ai_audit_log.constants import CHAIN_ALGORITHM, DIGEST_ALGORITHM
8
+ from ai_audit_log.digest import event_digest
9
+ from ai_audit_log.models import AuditEvent, Integrity
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class ChainIssue:
14
+ """One chain verification issue."""
15
+
16
+ index: int
17
+ code: str
18
+ message: str
19
+
20
+
21
+ @dataclass(frozen=True)
22
+ class ChainReport:
23
+ """Result of chain verification."""
24
+
25
+ ok: bool
26
+ event_count: int
27
+ stream_id: str | None
28
+ terminal_digest: str | None
29
+ issues: list[ChainIssue] = field(default_factory=list)
30
+
31
+
32
+ def append_integrity(
33
+ event: AuditEvent,
34
+ *,
35
+ stream_id: str,
36
+ sequence: int,
37
+ previous_event_digest: str | None,
38
+ ) -> AuditEvent:
39
+ """Return an event with chain metadata and current digest populated."""
40
+
41
+ event.integrity = Integrity(
42
+ stream_id=stream_id,
43
+ sequence=sequence,
44
+ previous_event_digest=previous_event_digest,
45
+ digest_algorithm=DIGEST_ALGORITHM,
46
+ chain_algorithm=CHAIN_ALGORITHM,
47
+ )
48
+ event.integrity.event_digest = event_digest(event)
49
+ return event
50
+
51
+
52
+ class ChainVerifier:
53
+ """Verify one hash-chained stream."""
54
+
55
+ def verify(self, events: list[AuditEvent], *, stream_id: str | None = None) -> ChainReport:
56
+ """Verify digests, sequence numbers, and previous-digest links."""
57
+
58
+ issues: list[ChainIssue] = []
59
+ expected_previous: str | None = None
60
+ expected_sequence = 1
61
+ seen_sequences: set[int] = set()
62
+ active_stream = stream_id
63
+ terminal: str | None = None
64
+
65
+ for index, event in enumerate(events):
66
+ integrity = event.integrity
67
+ if integrity.stream_id is None:
68
+ issues.append(ChainIssue(index, "missing_stream", "event has no stream_id"))
69
+ elif active_stream is None:
70
+ active_stream = integrity.stream_id
71
+ elif integrity.stream_id != active_stream:
72
+ issues.append(ChainIssue(index, "stream_mixing", "event stream_id differs"))
73
+
74
+ if integrity.sequence is None:
75
+ issues.append(ChainIssue(index, "missing_sequence", "event has no sequence"))
76
+ else:
77
+ if integrity.sequence in seen_sequences:
78
+ issues.append(ChainIssue(index, "duplicate_sequence", "duplicate sequence"))
79
+ seen_sequences.add(integrity.sequence)
80
+ if integrity.sequence != expected_sequence:
81
+ issues.append(ChainIssue(index, "sequence_gap", "sequence is not contiguous"))
82
+ expected_sequence += 1
83
+
84
+ if integrity.previous_event_digest != expected_previous:
85
+ issues.append(ChainIssue(index, "previous_digest", "previous digest mismatch"))
86
+
87
+ calculated = event_digest(event)
88
+ if integrity.event_digest != calculated:
89
+ issues.append(ChainIssue(index, "event_digest", "event digest mismatch"))
90
+ terminal = integrity.event_digest
91
+ expected_previous = integrity.event_digest
92
+
93
+ return ChainReport(
94
+ ok=not issues,
95
+ event_count=len(events),
96
+ stream_id=active_stream,
97
+ terminal_digest=terminal,
98
+ issues=issues,
99
+ )
@@ -0,0 +1,80 @@
1
+ """Checkpoint creation and verification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass
6
+ from typing import Any
7
+
8
+ from pydantic import BaseModel, Field
9
+
10
+ from ai_audit_log.chain import ChainVerifier
11
+ from ai_audit_log.constants import CHAIN_ALGORITHM
12
+ from ai_audit_log.digest import sha256_digest
13
+ from ai_audit_log.exceptions import IntegrityError
14
+ from ai_audit_log.models import AuditEvent
15
+ from ai_audit_log.time import format_rfc3339, now_utc
16
+
17
+
18
+ class Checkpoint(BaseModel):
19
+ """Signed or unsigned stream checkpoint."""
20
+
21
+ schema_version: str = "1.0"
22
+ stream_id: str
23
+ event_count: int
24
+ terminal_digest: str | None
25
+ chain_algorithm: str = CHAIN_ALGORITHM
26
+ created_time: str = Field(default_factory=lambda: format_rfc3339(now_utc()))
27
+ checkpoint_digest: str | None = None
28
+ signatures: list[dict[str, Any]] = Field(default_factory=list)
29
+
30
+ def unsigned_payload(self) -> dict[str, Any]:
31
+ """Return checkpoint data covered by its digest."""
32
+
33
+ payload = self.model_dump(exclude_none=True)
34
+ payload.pop("checkpoint_digest", None)
35
+ payload.pop("signatures", None)
36
+ return payload
37
+
38
+
39
+ @dataclass(frozen=True)
40
+ class CheckpointResult:
41
+ """Checkpoint verification result."""
42
+
43
+ ok: bool
44
+ issues: list[str]
45
+
46
+
47
+ def create_checkpoint(events: list[AuditEvent], *, stream_id: str | None = None) -> Checkpoint:
48
+ """Create a checkpoint for a verified stream."""
49
+
50
+ report = ChainVerifier().verify(events, stream_id=stream_id)
51
+ if not report.ok:
52
+ issue_codes = ", ".join(issue.code for issue in report.issues)
53
+ raise IntegrityError(f"cannot checkpoint an invalid chain: {issue_codes}")
54
+ active_stream = report.stream_id or stream_id or "default"
55
+ checkpoint = Checkpoint(
56
+ stream_id=active_stream,
57
+ event_count=report.event_count,
58
+ terminal_digest=report.terminal_digest,
59
+ )
60
+ checkpoint.checkpoint_digest = sha256_digest(checkpoint.unsigned_payload())
61
+ return checkpoint
62
+
63
+
64
+ def verify_checkpoint(checkpoint: Checkpoint, events: list[AuditEvent]) -> CheckpointResult:
65
+ """Verify a checkpoint against a stream."""
66
+
67
+ issues: list[str] = []
68
+ calculated = sha256_digest(checkpoint.unsigned_payload())
69
+ if checkpoint.checkpoint_digest != calculated:
70
+ issues.append("checkpoint digest mismatch")
71
+ report = ChainVerifier().verify(events, stream_id=checkpoint.stream_id)
72
+ if not report.ok:
73
+ issues.extend(issue.code for issue in report.issues)
74
+ if checkpoint.event_count != report.event_count:
75
+ issues.append("event count mismatch")
76
+ if checkpoint.terminal_digest != report.terminal_digest:
77
+ issues.append("terminal digest mismatch")
78
+ if checkpoint.stream_id != report.stream_id:
79
+ issues.append("stream mismatch")
80
+ return CheckpointResult(ok=not issues, issues=issues)
@@ -0,0 +1,78 @@
1
+ """Signed checkpoint policy verification."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from dataclasses import dataclass, field
6
+ from typing import Any
7
+
8
+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey
9
+
10
+ from ai_audit_log.checkpoint import Checkpoint
11
+ from ai_audit_log.signatures import public_key_fingerprint, verify_payload_signature
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class CheckpointSignaturePolicy:
16
+ """Policy for required checkpoint signatures."""
17
+
18
+ require_signature: bool = True
19
+ allowed_key_ids: tuple[str, ...] = ()
20
+ allowed_fingerprints: tuple[str, ...] = ()
21
+ minimum_signatures: int = 1
22
+
23
+
24
+ @dataclass(frozen=True)
25
+ class CheckpointPolicyResult:
26
+ """Result of checkpoint signature policy verification."""
27
+
28
+ ok: bool
29
+ issues: list[str] = field(default_factory=list)
30
+ accepted_signatures: int = 0
31
+
32
+
33
+ def verify_checkpoint_policy(
34
+ checkpoint: Checkpoint,
35
+ *,
36
+ public_keys: dict[str, Ed25519PublicKey],
37
+ policy: CheckpointSignaturePolicy | None = None,
38
+ ) -> CheckpointPolicyResult:
39
+ """Verify checkpoint signatures against a simple allow-list policy."""
40
+
41
+ active_policy = policy or CheckpointSignaturePolicy()
42
+ issues: list[str] = []
43
+ accepted = 0
44
+
45
+ if active_policy.require_signature and not checkpoint.signatures:
46
+ return CheckpointPolicyResult(ok=False, issues=["checkpoint has no signatures"])
47
+
48
+ for record in checkpoint.signatures:
49
+ key_id = str(record.get("key_id", ""))
50
+ fingerprint = str(record.get("public_key_fingerprint", ""))
51
+ if active_policy.allowed_key_ids and key_id not in active_policy.allowed_key_ids:
52
+ issues.append(f"signature key_id not allowed: {key_id}")
53
+ continue
54
+ if active_policy.allowed_fingerprints and fingerprint not in active_policy.allowed_fingerprints:
55
+ issues.append(f"signature fingerprint not allowed: {fingerprint}")
56
+ continue
57
+ public_key = public_keys.get(key_id)
58
+ if public_key is None:
59
+ issues.append(f"missing public key for key_id: {key_id}")
60
+ continue
61
+ if fingerprint and fingerprint != public_key_fingerprint(public_key):
62
+ issues.append(f"signature fingerprint does not match public key: {key_id}")
63
+ continue
64
+ if _verify_one(checkpoint, record, public_key):
65
+ accepted += 1
66
+
67
+ if accepted < active_policy.minimum_signatures:
68
+ issues.append("minimum signature count not satisfied")
69
+ return CheckpointPolicyResult(ok=not issues, issues=issues, accepted_signatures=accepted)
70
+
71
+
72
+ def _verify_one(
73
+ checkpoint: Checkpoint,
74
+ record: dict[str, Any],
75
+ public_key: Ed25519PublicKey,
76
+ ) -> bool:
77
+ verify_payload_signature(checkpoint.unsigned_payload(), record, public_key)
78
+ return True