Metadata-Version: 2.5
Name: badgeia-provenance
Version: 0.2.0
Summary: Badge Provenance Pipeline (BPP-001) helpers and Signed Agent Record verifier: signed manifests, RFC 9421 response signing, trace-id echo, and offline verification of a badgeIA Signed Agent Record for Python agents and CI gates. https://badgeia.com
Project-URL: Homepage, https://badgeia.com
Project-URL: Repository, https://github.com/thehomer87/badgeIA
Author: Badge (badgeia.com)
License: MIT
License-File: LICENSE
Keywords: a2a,ai-agents,badge,ed25519,manifest,provenance,rfc9421,signed-agent-record
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Software Development :: Libraries
Requires-Python: >=3.11
Requires-Dist: cryptography>=42.0.0
Provides-Extra: dev
Requires-Dist: build>=1.0.0; extra == 'dev'
Requires-Dist: jsonschema>=4.18.0; extra == 'dev'
Requires-Dist: pydantic-settings>=2.3.0; extra == 'dev'
Requires-Dist: pydantic>=2.7.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: sqlalchemy[asyncio]>=2.0.0; extra == 'dev'
Requires-Dist: twine>=5.0.0; extra == 'dev'
Description-Content-Type: text/markdown

# badgeia-provenance

Badge Provenance Pipeline (BPP-001) helpers for Python agents: signed
manifests, RFC 9421 signed HTTP responses, and a trace-id echo helper —
byte-for-byte compatible with the verifiers in
[badgeIA](https://github.com/thehomer87/badgeIA)'s backend
(`backend/app/services/bpp_manifest.py` + `bpp_signatures.py`).

> **Status: publish-ready, dry-run verified. NOT published to PyPI** (founder
> OTP gate — see the parent repo's `docs/RUNBOOK-provenance.md`). Install
> from source until a release is cut.

Badge is the credential layer for AI agents — **Screen · Hire · Trust**.
Attaching a signed manifest and signing your agent's HTTP responses raises
your provenance level on the Talent Pool; screening works identically
without either (progressive, never a gate).

---

## Install (from source — not yet on PyPI)

```bash
git clone https://github.com/thehomer87/badgeIA.git
cd badgeIA/integrations/provenance-py
pip install -e .
```

Runtime dependency: `cryptography` only.

## 5-minute quickstart

### 1. Generate a keypair and scaffold a signed manifest

```python
from badgeia_provenance import generate_keypair, scaffold_manifest, sign_manifest

private_key, public_jwk = generate_keypair()  # keep private_key secret; publish public_jwk

manifest = scaffold_manifest(
    "Explorer-Bot",
    models=[{"id": "gpt-4o-mini", "provider": "openai", "role": "primary"}],
    tools=[{"name": "web_search", "kind": "retrieval"}],
    provenance_public_key=public_jwk,
)
signed_manifest = sign_manifest(manifest, private_key)

# Serve `signed_manifest` (as JSON) at /.well-known/agent.json.
# Badge TOFU-pins `public_jwk` on first discover/register.
```

### 2. Sign your agent's HTTP response (RFC 9421)

Badge sends an `Accept-Signature` header on every dispatch when BPP is
enabled — this is a hint, not a requirement; an agent that never signs
screens exactly as it did before this package existed.

```python
from badgeia_provenance import sign_response_headers
from badgeia_provenance.manifest import manifest_sha256
from badgeia_provenance.signatures import build_agent_provenance_header

body = b'{"answer": "42"}'
provenance = build_agent_provenance_header(
    model_ids=["gpt-4o-mini"],
    input_tokens=128,
    output_tokens=16,
    manifest_hash=manifest_sha256(signed_manifest),  # ties the response to the manifest
)
headers = sign_response_headers(
    status=200, agent_provenance=provenance, body=body, private_key=private_key,
)
# headers == {"Agent-Provenance": ..., "Content-Digest": ..., "Signature-Input": ..., "Signature": ...}
# Merge these onto your actual HTTP response headers alongside `body`.
```

### 3. Or wire it all up with the FastAPI/ASGI middleware

```python
from fastapi import FastAPI
from badgeia_provenance.middleware import ProvenanceMiddleware
from badgeia_provenance.signatures import build_agent_provenance_header

app = FastAPI()

def provenance_provider(scope, status_code, body):
    return build_agent_provenance_header(model_ids=["gpt-4o-mini"], input_tokens=128, output_tokens=16)

app.add_middleware(
    ProvenanceMiddleware,
    private_key=private_key,
    provenance_provider=provenance_provider,
)
```

The middleware also echoes `X-Badge-Trace-Id` whenever the request carried a
valid W3C `traceparent` header (BPP-3 cheap binding) — with or without
signing configured. When a request needs neither, it passes straight
through: zero buffering, zero added headers.

### 4. Or do the trace-id echo by hand (no middleware)

```python
from badgeia_provenance import echo_trace_id

# request_headers is whatever mapping your framework hands you
extra_response_headers = echo_trace_id(request_headers)  # {} or {"X-Badge-Trace-Id": "..."}
```

---

## Verify a Signed Agent Record

A **Signed Agent Record** is one badgeIA run certificate as a self-contained
JSON document: the signed fields in signing order, the SHA-256 fingerprint, the
Ed25519 signature, and which key signed it. This package verifies one without
calling badgeIA's runs API. The format, the field order per certificate version
(v1 to v7) and 27 conformance fixtures are in
[`integrations/signed-agent-record/`](../signed-agent-record/README.md); this
library passes all of them, and agrees with the backend reference on each.

### The trust rule (read this first)

Only the record's `signed_fields` are signed. Nothing in the record can say who
you should trust, so **you** supply the trusted key set: badgeIA's published
key file, or a copy you archived. The library never fetches keys from anywhere
the record names, and a record signed by any other key (staging's included) is
`invalid` with the reason `key not trusted`.

### Verify offline

```python
import json
from badgeia_provenance.record import verify_record

# badgeIA's published key set, saved once:
#   curl -s https://api.badgeia.com/.well-known/badge-verification-key.json > badge-keys.json
trusted = json.load(open("badge-keys.json"))
record = json.load(open("record.json"))

result = verify_record(record, trusted)
result.status       # "verified" | "invalid" | "unsigned"
result.reason       # None when verified, else e.g. "fingerprint does not match the signed fields"
result.step         # which step of the README procedure failed (1-7)
result.facts        # the signed field values - ONLY present when verified
result.pack         # v4 / v7 pack_id / pack_version / harness_commit / judge_model - ONLY when verified
result.endpoint_ownership         # v5-v7 only: the SIGNED value; None before v5 - ONLY when verified
result.endpoint_ownership_status  # the /verify reading - ONLY when verified (see below)
result.verify_url   # https://badgeia.com/verify/<signed run_id> - ONLY when verified
```

**Endpoint ownership (certificate versions v5, v6, v7).** These are v2, v3 and
v4 plus one last signed field, `endpoint_ownership`. `endpoint_ownership_status`
is the same reading badgeIA's `/verify` gives for the same certificate:

| Status | When |
| --- | --- |
| `token_verified` | v5-v7 signing `token_verified`: the account that registered the agent served the agent's token at the endpoint's origin when badgeIA checked it. It does not say who built the agent behind that endpoint. |
| `no_endpoint_to_check` | v5-v7 signing `not_applicable` on a `live_endpoint` run (a daemon or an OpenAI Assistant: no owner endpoint). |
| `not_applicable` | v5-v7 signing `not_applicable` on any other run, or a v1-v4 `real_llm` / `simulated` certificate. |
| `not_recorded` | a v1-v4 `live_endpoint` certificate: endpoint ownership was not part of its requirements when it was issued. It does not mean "not checked". |

A signed value badgeIA never issues gets a null status (the signature still
decides the verdict). A certificate version this library does not know
(`v8`, say) is `invalid` at step 1, never read as the newest version it knows.


`verify_record` never raises on hostile input. A record edited after signing, a
wrong key, a relabelled certificate version, a missing field: all `invalid`.
A record with any field the schema does not define (a `verify_url`, a
`key_set_url`, a public key) is `invalid` at step 1: nothing outside the signed
fields may steer verification. `verify_url` on the result is built from the
signed `run_id`, and only when that is a canonical UUID.
`unsigned` means a well-formed record that carries no signature; it never
passes a gate. The algorithm is pinned to Ed25519 + SHA-256; a record that names
another is `invalid`. The key is found by its SHA-256 in your trusted set, then
its `key_id` label is confirmed: a `key_id` alone selects nothing.

`trusted` may be the published key set document, its `keys` list, or a plain
`{key_id: public_key_b64url}` dict.
A key marked `"status": "retired"` in the published set still verifies what it
signed: retirement is rotation, so old certificates keep verifying; it is not
revocation. A gate that must refuse certificates from a retired key has to check
`key_id` itself.

Online, against the key set at badgeIA's published address (hard-coded; pass
`key_set_url` only for a key set YOU run, `https` only):

```python
from badgeia_provenance.record import verify_record_online

result = verify_record_online(record)
# an unreachable key set is status="invalid", reason_code="key_set_unavailable"
```

### Gate CI on a record

A record is one run's certificate, so "a record exists" is not a gate: a failed
or simulated run has one too. **`evaluate_for_gate` is the predicate a CI gate
should call.** It checks the signature first (a bad one fails with exactly
`"signature invalid"` and no policy is read), then your policy:

```python
from badgeia_provenance.record import evaluate_for_gate

gate = evaluate_for_gate(
    record,
    {"max_age_days": 30, "min_score": 70},
    keys=trusted,
    score=agent_composite_score,  # composite_score is already 0-100
)
if not gate.ok:
    for reason in gate.reasons:
        print(f"blocked: {reason}")
    raise SystemExit(1)
```

| Policy field | Default | Fails with |
|---|---|---|
| `require_success` | `True` | `the run did not succeed (success=false)` |
| `allowed_execution_modes` | `["live_endpoint", "real_llm"]` (no `simulated`) | `execution mode "simulated" is not allowed (allowed: ...)` |
| `max_age_days` | `None` (no limit) | `the record is 66.6 days old; the policy allows at most 30` |
| `min_score` | `None` | `score 61.5 is below the required 70 (scores are 0-100)` |
| `require_blueprint_version` | `True` | `no traced Blueprint version; the gate cannot bind this record to a deployable artifact` |

A record does not carry a score (the composite is computed over many runs), so
pass the agent's `composite_score` as `score`; with `min_score` set and no score
supplied, the gate fails closed. Every failed check adds one readable reason.
An unknown policy field raises `TypeError`, so a typo cannot loosen a gate.

### Verify an A2A Agent Card or MCP manifest

A2A v1.0 cards have no attestation field, so the reference lives in a `badgeia`
object next to the card's JWS `signatures` (add it before signing the card). An
MCP server manifest carries it under `_meta["com.badgeia/signed-agent-record"]`.
Schemas and a documented example:
[`integrations/signed-agent-record/reference/`](../signed-agent-record/reference/).

```python
from badgeia_provenance.record import verify_card_from_url, resolve_document

# fetch the card, check it carries the reference, resolve it to a verifying record
outcome = verify_card_from_url(
    "https://agent.example.com/.well-known/agent-card.json", trusted_keys=trusted
)
outcome.resolved  # True only if the record verifies AND is the one the reference names
outcome.reason    # why not, in plain words

# a card or manifest you already hold:
resolve_document(card, trusted_keys=trusted)
```

What this proves: badgeIA signed that run. It does **not** prove the card's
owner is that agent; anyone can paste another agent's record into their card.
Verify the card's own JWS with an A2A client, and check that the `agent_id` is
registered for the card's endpoint. Fetching a card or a linked `record_url`
makes an outbound request to a URL someone else wrote: https only, no
redirects, a byte cap and an overall deadline, and a loopback, private or
link-local host is refused before any request (`allow_private_hosts=True` opts
out, for a card you serve yourself). A public name that *resolves* to a private
address is not caught; pass your own `fetcher` to put it behind your egress
controls.

Validators: `validate_agent_card`, `validate_mcp_manifest`,
`validate_attestation_reference` (structural; they return `Validation(valid, errors)`).

---

## What's in the box

| Module | Purpose |
|---|---|
| `badgeia_provenance.manifest` | `scaffold_manifest` / `sign_manifest` / `canonicalize` / `manifest_sha256` — ARP v2 manifest + `ml_bom` skeleton, Ed25519 detached-JWS signing over JCS-canonical bytes. |
| `badgeia_provenance.signatures` | `sign_response_headers` / `build_agent_provenance_header` — RFC 9421 signed-header response (`@status`, `content-digest`, `agent-provenance`), `ACCEPT_SIGNATURE_HEADER_NAME`/`VALUE` constants. |
| `badgeia_provenance.tracing` | `echo_trace_id` / `extract_trace_id` — W3C `traceparent` -> `X-Badge-Trace-Id` echo. |
| `badgeia_provenance.middleware` | `ProvenanceMiddleware` — pure ASGI3 middleware combining all three for FastAPI/Starlette apps. |
| `badgeia_provenance.record` | `verify_record` / `verify_record_online` / `evaluate_for_gate` / `validate_agent_card` / `validate_mcp_manifest` / `resolve_attestation` / `verify_card_from_url` — Signed Agent Record verifier, CI-gate predicate and attestation reference. |
| `badgeia_provenance.keys` | `generate_keypair` / `ed25519_public_key_to_jwk` / `jwk_to_ed25519_public_key` — JWK (OKP/Ed25519) helpers. |

Every function here is a byte-for-byte mirror of the corresponding backend
verifier — see the docstrings in `src/badgeia_provenance/*.py` for the exact
contract each one satisfies, and `tests/` for round-trip tests that import
the real backend modules (`app.services.bpp_manifest` /
`app.services.bpp_signatures`, via an in-repo `sys.path` insert) to prove it.

## Development

```bash
pip install -e ".[dev]"
pytest
python -m build
twine check dist/*
```

No `twine upload` — this package is publish-ready but not published (founder
OTP gate).
