Metadata-Version: 2.4
Name: aleutian-verification
Version: 0.6.0
Summary: Aleutian AI verification SDK for offline chain and anchor verification
Project-URL: Homepage, https://aleutian.ai
Project-URL: Documentation, https://docs.aleutian.ai/sdk/python
Project-URL: Repository, https://github.com/aleutian-ai/verification-python
Author-email: Aleutian AI <jinterlante@aleutian.ai>
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: aleutian,audit,chain,cryptography,verification
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security :: Cryptography
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: cryptography>=41.0.0
Requires-Dist: dilithium-py>=1.4.0
Provides-Extra: dev
Requires-Dist: mypy>=1.0; extra == 'dev'
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
Requires-Dist: pytest>=7.0; extra == 'dev'
Requires-Dist: ruff>=0.1.0; extra == 'dev'
Description-Content-Type: text/markdown

# Aleutian Verification SDK for Python

Offline verification for AleutianChain audit chains.

This is one of three implementations of the same format. Go
([`github.com/aleutian-ai/proof`](https://github.com/aleutian-ai/proof)), Python
and JavaScript are held to a **shared set of conformance vectors** — the same
bytes must produce the same hashes and the same verdict in all three, or a test
fails. See "Conformance" below.

## Installation

```bash
pip install aleutian-verification
```

> **Not yet on PyPI.** Until it is published, install from the repository.
> This note comes out when the package is live.

## Features

- **Chain verification** — SHA-512 chain hash continuity, chain formats
  **v4** (leaf hash and chain hash, erased entries recomputed from their leaf
  hash), **v3** and **v2**, and v2/v3 chains continued in v4
- **Anchor verification** — **ML-DSA-65** (FIPS 204) post-quantum signatures,
  canonical forms v1–v4, v6 and **v7** (bound by sequence, signed with the
  context `aleutian.proof.anchor.v7`)
- **Sink export bundles** — `aleutian.proof.bundle.v1` and **`.v2`**, and the
  record-signature envelopes `aleutian.proof.record.v1` and **`.v2`**
- **Tombstone detection** — identify and validate v2/v3 erasure markers, which
  keep a chain verifiable after content is deleted
- **Webhook verification** — HMAC-SHA-512 signatures

All verification is fully offline. No network, no credentials, no account.

### What this SDK does NOT do

It **verifies**; it does not produce. There is no signing, no chain linking and
no key generation here — those live in the Go implementation. A verifier is
meant to be small, dependency-light and safe to drop into an auditor's
environment.

## Quick Start

### Verify a Chain Export

```python
from aleutian_verification import (
    load_anchor,
    load_exported_entries,
    verify_anchor_locally,
    verify_chain_offline,
    ChainVerifyOptions,
)

# Load and verify anchor signature
anchor = load_anchor("anchor-2026-01-20.json")
verify_anchor_locally(anchor)  # Raises AnchorVerificationError on failure

# Load and verify chain
from aleutian_verification import SEED_ANCHOR_HASH
entries = load_exported_entries("export-2026-01.json")
result = verify_chain_offline(
    entries,
    ChainVerifyOptions(
        anchor=anchor,
        # For genesis anchors pass SEED_ANCHOR_HASH (or omit; the SDK auto-fills).
        # For mid-chain anchors pass the prior anchor's chain_hash here.
        previous_anchor_hash=SEED_ANCHOR_HASH,
    ),
)

# describe() words the verdict safely: entries up to and including the last
# tombstone are reported as NOT verified (result.entries_not_verified).
print(result.describe())
if not result.valid:
    print(f"Chain invalid: {len(result.breaks)} breaks found")
    for brk in result.breaks:
        print(f"  - {brk.break_type} at position {brk.position}")
```

### Verify a proof sink export bundle

A bundle (`aleutian.proof.bundle.v1` or `.v2`, see proof's
`docs/bundle-format.md`; v2 is its §16) is a sink's evidence exported for
someone else to check. The bundle's `format` decides how it is checked: v1 is
chain hash v3, v6 checkpoints and `record.v1`; v2 is chain format v4, v7
checkpoints and `record.v2`. This verifier was written
from the spec alone, independently of proof's code. **Trust is yours:** you
give the keys you trust for checkpoints and for record signatures; the bundle
never adds a key.

```bash
aleutian-verify verify-proof-bundle bundle.json \
    --checkpoint-key checkpoint.pub --record-key record.pub [--json]
```

Key files are PEM `PUBLIC KEY` files holding an ML-DSA-65 key, as
`proof keygen` writes them. Each flag may repeat.

| Exit | Meaning |
|---|---|
| 0 | `ok`: no problem, and every entry is authenticated by a key you trust |
| 1 | `failed`: at least one problem |
| 2 | usage: bad arguments, an unreadable file, an invalid key file |
| 3 | the bundle is unreadable |
| 4 | `unauthenticated`: no problem, but provenance is not established |
| 5 | an internal error in the verifier, never a verdict |

`--json` prints exactly the `aleutian.proof.bundle-result.v1` result, for
either bundle format. Read
bundle-format §1 for what a passing bundle does **not** prove (that it holds
every chain, that a chain is complete to its end, anything after the export).

**Cost.** This verifier is pure Python. Parsing runs at about 2 MB/s on
hostile input made of tiny values (the worst case; long strings parse much
faster), so a 256 MiB bundle, the §5 size limit, can take a couple of minutes.
Each ML-DSA-65 verification takes about 7 ms: at most 100,000 checkpoint
signatures, and about 58,000 record signatures in 256 MiB. A v2 bundle may hold
17,000,000 JSON values (§16 §5) where a v1 bundle may hold 15,000,000. **Memory** is
bounded by the largest readable bundle, not by the input's shape: the bundle
is read in one streaming pass that stops building values at the first reason
it is unreadable (§9.1), and refuses more than 15,000,000 JSON values (§5).
Hostile input costs about the decoded text, at most a few times the input.

```python
from aleutian_verification import parse_mldsa65_public_key_pem, verify_proof_bundle

checkpoint_key = parse_mldsa65_public_key_pem(open("checkpoint.pub", "rb").read())
result = verify_proof_bundle(open("bundle.json", "rb").read(), [checkpoint_key], [])
print(result.verdict)        # "ok", "unauthenticated" or "failed"
print(result.to_dict())      # exactly the §9 JSON
```

### Verify Webhook Signatures

```python
from flask import Flask, request
from aleutian_verification import is_valid_webhook
import os

app = Flask(__name__)

@app.route('/webhook', methods=['POST'])
def webhook():
    if not is_valid_webhook(
        request.headers.get('X-Aleutian-Signature', ''),
        request.get_data(),
        os.environ['WEBHOOK_SECRET']
    ):
        return 'Invalid signature', 401

    # Process verified webhook...
    return 'OK', 200
```

## API Reference

### Chain Verification

```python
compute_chain_hash(previous_hash, run_id, sequence_num, timestamp, content_hash) -> str
compute_chain_hash_ms(previous_hash, run_id, sequence_num, timestamp_ms, content_hash) -> str
compute_chain_hash_v3(previous_hash, global_seq, timestamp, content_hash) -> str
compute_leaf_hash_v4(entry_id, entry_type, content_hash, salt) -> str
compute_chain_hash_v4(previous_hash, global_seq, timestamp, leaf_hash) -> str
verify_chain_offline(entries, options) -> OfflineVerificationResult
bind_anchor_to_entries(anchor, entries, previous_anchor_hash="", *,
                       expected_subject="", previous_hash="") -> AnchorBindResult
```

**Chain format v4** (format-spec §2.0). Each entry declares its format
(`format_version` 4, 3, or absent for v2); the verifier dispatches on that
alone. A v4 entry carries a `salt` and a `leaf_hash`, the chain links through
the leaf hash, and an erased entry (`erased: true`, with no `entry_id`,
`entry_type`, `content_hash` or `salt`) is recomputed from its stored leaf
hash, so erasure leaves no entry unverified. `result.erased_found` counts
erased v4 entries. A v2 or v3 chain may continue in v4; a v2 or v3 entry after
a v4 entry is `format_field_misuse`.

**v7 anchors** (format-spec §9.7) are bound by sequence: the anchor carries
`range.start_seq`/`end_seq`, a string `entry_count` and its predecessor's
`previous_anchor_hash`. Pass the predecessor you expect as
`previous_anchor_hash` and the subject you expect as `expected_subject` (or
`ChainVerifyOptions(expected_subject=...)`); `bind.subject_checked` says
whether a subject was compared. A chain that has grown since the anchor still
binds, to the entry at `end_seq`.

`verify_chain_offline` follows the public format spec: field shapes are checked
before any hash is recomputed (`invalid_field`, `invalid_timestamp`), a stored
timestamp must be exactly `YYYY-MM-DDTHH:MM:SS.ffffffZ`, the first `global_seq`
is not constrained, and `ChainVerifyOptions(previous_hash=...)` verifies a
segment.

**Tombstones.** A tombstone's chain hash is taken as stored, so nothing links
the entries before a tombstone to the entries after it. `result.valid` and
`bind.bound` say nothing about the entries up to and including the last
tombstone: read `result.entries_not_verified` / `bind.entries_not_bound`, or
print `result.describe()` / `bind.describe()`.

### Anchor Verification

```python
verify_anchor_locally(anchor, public_key=None, previous_anchor_hash=None) -> None
validate_anchor(anchor) -> None
canonicalize_anchor(anchor) -> str
canonicalize_anchor_v7(anchor) -> str
compute_anchor_chain_hash_v7(previous_anchor_hash, subject, start_seq, end_seq, tip) -> str
parse_anchor_text(text) -> Anchor
parse_exported_entries_text(text) -> list[ExportedEntry]
load_anchor(path) -> Anchor
load_exported_entries(path) -> list[ExportedEntry]
```

`verify_anchor_locally` verifies a v7 anchor's signature with the ML-DSA
context `aleutian.proof.anchor.v7`, and v1–v6 with the empty context, chosen
from the declared `version` only.

The `*_text` readers and both loaders are strict. An anchor may carry only the
members the format names, each once, with its subject under its version's name;
it raises `AnchorFormatError` otherwise. An entries file is a JSON array or
JSON Lines of entry objects, or the hosted platform's `{"entries": [...]}`
wrapper; anything else (`{}`, `null`, an export bundle, a repeated member, a
known member in another letter case, a missing required member, a wrong type)
raises `EntriesFormatError`, which is an error and never a broken chain. Both
readers accept a member in snake_case or in its older camelCase alias
(`entryId`, `chainHash`, ...), never both in one object.

`bind_anchor_to_entries` binds to exactly the entries given: for a chain that
has grown since the anchor was signed, pass `entries[:anchor.entry_count]`.

### Webhook Verification

```python
is_valid_webhook(signature_header, payload, secret) -> bool
verify_webhook_signature(signature_header, payload, secret, options) -> None
verify_webhook_with_secrets(signature_header, payload, secrets, options) -> int
decode_secret(secret) -> bytes | None
```

### Processing Mode (v=2 chain entries)

```python
parse_processing_mode(s: str) -> str
encode_processing_mode_canonical_fields(mode: str, set_by_event_id: str) -> bytes
```

`parse_processing_mode` is a byte-strict parser that accepts only `"zk"` or
`"pii_inspection"` (no trimming, no case folding, no Unicode normalization).
It raises `InvalidProcessingMode` (a `ValueError` subclass) on any other input.

`encode_processing_mode_canonical_fields` produces the deterministic TLV byte
sequence for the `processing_mode_at_write` and `processing_mode_set_by_event_id`
fields in a v=2 Aleutian consent chain entry. Output is byte-identical to the Go
encoder in `internal/storage/processing_mode_canonical.go`, enforced by the shared
golden vectors in `sdk/testdata/processing_mode_golden.json`.

```python
from aleutian_verification import (
    ZK,
    PII_INSPECTION,
    InvalidProcessingMode,
    parse_processing_mode,
    encode_processing_mode_canonical_fields,
)

# Byte-strict mode parser
mode = parse_processing_mode("zk")  # returns "zk"
parse_processing_mode("ZK")         # raises InvalidProcessingMode

# Canonical TLV encoder
canonical_bytes = encode_processing_mode_canonical_fields("zk", "system:bootstrap")
# 26 bytes: 4-byte BE u32 length + mode bytes + 4-byte BE u32 length + event id bytes
```

### Tombstone Functions

```python
is_tombstone(entry_type, entry_id) -> bool
is_tombstone_content_hash(content_hash) -> bool
validate_tombstone_content_hash(content_hash) -> bool
```

### V3 SAR chain entry verification (added in 0.2.0)

End-to-end verifier for the V3 canonical SAR (Data Subject Access
Request) chain entry family. Validates entry structure, re-encodes
canonical bytes, constant-time-compares the content hash, and verifies
the ML-DSA-65 signature against a trust manifest.

```python
from aleutian_verification import (
    SARFulfilledEntryV3,
    SARFulfillmentKindV3,
    EventTypeV3,
    TrustManifestV3,
    verify_chain_entry_v3,
    ErrContentHashMismatchV3,
    ErrSignatureInvalidV3,
    ErrUnknownSigningKeyV3,
)

# 1. Reconstruct the typed entry from your chain row.
entry = SARFulfilledEntryV3(
    company_id="comp_01HKACCESSAAAAAAAAAAAAAAAA",
    entry_type=EventTypeV3.SAR_FULFILLED,
    signing_key_id="duncan-chain-anchor-mldsa65/cryptoKeyVersions/1",
    timestamp_ms=1747500000000,
    certificate_id="",                                  # access has empty cert
    fulfillment_kind=SARFulfillmentKindV3.ACCESS,
    intent_entry_id="01900000-0000-7000-8000-1234567890ab",
    legal_basis="art_15_access",
    manifest_root="a" * 128,                            # SHA-512 hex of export bundle
    request_id="01HK7BBBBBBBBBBBBBBBBBBBBB",
    tombstone_count=0,
)

# 2. Build a trust manifest from the issuer's published public keys.
#    Each key is validated against the ML-DSA-65 length at construction.
manifest = TrustManifestV3.from_map({
    "duncan-chain-anchor-mldsa65/cryptoKeyVersions/1": pubkey_bytes,
})

# 3. Verify. Raises a typed subclass of ErrInvalidEntryV3 on failure.
try:
    verify_chain_entry_v3(
        entry=entry,
        signature=signature_bytes,        # 3309 bytes ML-DSA-65
        content_hash=content_hash_bytes,  # 64 bytes SHA-512
        trust_manifest=manifest,
    )
    print("verified")
except ErrUnknownSigningKeyV3:
    ...  # manifest staleness / operator misconfiguration
except ErrContentHashMismatchV3:
    ...  # entry payload tampered OR cross-language encoder drift
except ErrSignatureInvalidV3:
    ...  # forgery indicator
```

Manifest-root recipe (for end-user reproducibility of the access
export bundle's hash): see `pqc_05c §5.1` or
`verify.aleutian.ai/spec/manifest-root`.

## Conformance

**This SDK passes the vector set whose `MANIFEST.json` has SHA-256
`304583d41eca4e74e2fb19cd799f499e663d60d0366bb70f4f712db903264d3c`**
(`shasum -a 256 sdk/testdata/MANIFEST.json`): proof v0.5.0's set plus the
X-Wing specification's official vectors (`xwing_spec_vectors.json`). That
manifest pins the digest of every vector file below, and
`tests/test_conformance_vectors.py` checks each one against it.

| Format | Vectors | Tests |
|---|---|---|
| chain format v4, continued v3 chains (format-spec §2.0, §2.5, §5.0) | `chain_v4_vectors.json` | `test_chain_v4_vectors.py` |
| chain hash v3, v2 | `chain_v3_vectors.json`, `chain_vectors.json` | `test_shared_vectors.py`, `test_chain_v2_vectors.py` |
| anchor v7: canonical bytes, chain hash, signature (§9) | `anchor_v7_canonical_vectors.json` | `test_anchor_v7_vectors.py` |
| anchors v6, v1–v4, anchor chain hash | `anchor_v6_canonical_vectors.json`, `anchor_v4_canonical_vectors.json`, `anchor_chain_hash_vectors.json` | `test_shared_vectors.py`, `test_anchor_v4_canonical_fixtures.py` |
| verifier verdicts, v4 chains and v7 binds (§5.5, §9.7) | `verify_verdict_v4_vectors.json` | `test_verify_verdict_v4_vectors.py` |
| verifier verdicts, v2/v3 chains and v6 binds | `verify_verdict_vectors.json` | `test_verify_verdict_vectors.py` |
| bundle v2 (bundle-format §16) | `bundle_v2_vectors.json` | `test_proof_bundle_v2_vectors.py` |
| bundle v1 | `bundle_v1_vectors.json` | `test_proof_bundle_vectors.py` |
| `record.v2` envelope and signatures (sink-format §9.1) | `record_v2_vectors.json` | `test_record_v2_vectors.py` |
| `record.v1` envelope, salted commitments | `record_v1_vectors.json`, `commitment_vectors.json` | `test_commitment_record_vectors.py` |
| key ids | `keyid_vectors.json` | `test_shared_vectors.py` |
| capture leaf v3, Merkle trees | `v3_golden_capture_request.json`, `merkle_golden.json` | `test_golden_capture_v3.py`, `test_merkle_golden.py` |

The three implementations share one canonical set of vectors, kept in the public
`proof` repository at `fixtures/testdata/` and vendored here with a manifest of
SHA-256 digests.

```
                    proof/fixtures/testdata/   ← canonical, public
                    proof/fixtures/MANIFEST.json
                              │  vendored + digest-checked
              ┌───────────────┼───────────────┐
              ▼               ▼               ▼
             Go            Python          JavaScript
              └────── all must reproduce ─────┘
```

The expected outputs are **data**. They are never regenerated by an
implementation during a test run — a vector edited to make one implementation
pass fails the other two, which is the point. `tests/test_conformance_vectors.py`
checks this SDK's vendored copy against the manifest before any test trusts it.

Beyond the shared vectors, this SDK is tested against artifacts produced by the
Go implementation directly: `tests/testdata/go_produced_v3_chain.json` came out
of `proof append`, and `go_signed_v6_anchor.json` was signed by `proof anchor`
with a real ML-DSA-65 key. Regenerating either with this SDK would destroy its
value — they are evidence precisely because another implementation made them.

## Requirements

- Python >= 3.10
- cryptography >= 41.0.0

## License

AGPL-3.0-or-later
