Metadata-Version: 2.5
Name: ample-receipts-client
Version: 0.2.0rc3
Summary: Ample receipts client library: an httpx transport tee that records each call for a receipt.
Project-URL: Homepage, https://ample.isrm.ai/receipts
Author: ISRM Labs AB
Maintainer: ISRM Labs AB
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: ample,audit,ed25519,httpx,llm,receipts,transparency-log
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security :: Cryptography
Classifier: Typing :: Typed
Requires-Python: >=3.12
Requires-Dist: cryptography<51,>=50.0.0
Requires-Dist: httpx<0.29,>=0.27
Provides-Extra: httpx2
Requires-Dist: httpx2<2.17,>=2.16.0; extra == 'httpx2'
Description-Content-Type: text/markdown

# ample-receipts-client

The client library of Ample receipts. This release holds the **transport tee** (an
httpx and an `httpx2` transport that sits under a provider client, records each HTTP
attempt and changes nothing about the call), **`record()`** for every other client, the
**spool**, the statement **builder** with your salt key and client key, the client key's
**introduction** request, the **submitter** with its ack check and kept acks, the
**reveal**, and the opt-in **vault**. It is Apache-2.0, by ISRM Labs AB. It talks only to the
receipts service you name: it has no default service address (see "Changes before the first
release" below).

```sh
pip install ample-receipts-client            # Python 3.12
pip install "ample-receipts-client[httpx2]"  # with the httpx2 tee
```

This version is a release candidate, not a stable release; a stable release follows. Pin the
exact version you install (`ample-receipts-client==` and the version this page names).

It depends on `httpx` and `cryptography`, each held to the versions it was tested against
(`httpx>=0.27,<0.29`, `cryptography>=50.0.0,<51`): the tee uses httpx's own content decoders, which
are private to httpx, so a newer httpx is allowed only after a test run on it. Pin them in your own
lock file as you do for the rest of your application.

## Quick start

The operator of the receipts service you use gives you your tenant id, your tenant's URL at the
service, your API key (in a file only you can read) and the service's ledger public keys. Make the
folder your app uses, once:

```sh
ample-receipts init --dir /var/lib/myapp/receipts --tenant acme \
    --service-url https://receipts.example.com/t/acme \
    --api-key-file /run/secrets/receipts-api-key --ledger-keys ledger-public.json
ample-receipts status --dir /var/lib/myapp/receipts
```

`init` sends nothing. It makes your client key and salt key (new files, mode 0600) and
`receipts.json`, which names every file the library reads. It never prints a key and never
overwrites one. Back up `client.key` and `salt.key`: nobody can make them again. If the service's
certificate comes from a private CA, add `--ca-file <private-ca.pem>`. `status` checks the service
and counts the calls recorded and acknowledged; it sends nothing.

In your app:

```python
import ample_receipts_client as ar
import openai

receipts = ar.setup(dir="/var/lib/myapp/receipts")  # or set AMPLE_RECEIPTS_DIR and call ar.setup()
client = openai.OpenAI(http_client=receipts.httpx2_client())  # needs the httpx2 extra
```

`setup()` reads the folder, reaches the service once over verified TLS, introduces your client key
and starts sending in the background; if any step fails, it raises and starts nothing.
`receipts.httpx_client()` and `receipts.async_httpx_client()` give httpx clients, and
`receipts.httpx2_client()` and `receipts.async_httpx2_client()` give `httpx2` clients (the current
`openai` and `anthropic` SDKs take one as `http_client=`). Each gives a new client with its own tee.
The SDK form is the documented wiring, checked earlier at `openai` 3.39.0 and `anthropic` 2.3.0;
this release did not test it again. `AMPLE_RECEIPTS_DIR` is the only environment variable the
library reads, and only inside `setup()`.

At a normal exit the library seals what it recorded, sends what is waiting, checks each ack and
writes the acks to `held-acks.jsonl` in the folder; `receipts.close()` does the same at once. Calls
not yet acknowledged stay in the folder and are sent at the next start. A plain SIGTERM runs no exit
code: let your server turn it into a normal exit, or call `receipts.close()` in your shutdown hook.
With several worker processes, call `setup()` in each worker after the fork.

For your auditor:

```sh
ample-receipts handover --dir /var/lib/myapp/receipts --out for-auditor
```

It writes your held acks, your client public keys and the ledger public keys into the new folder,
never a secret, and prints the verifier's command for your auditor.

## Wiring it by hand

The partner guide (`integration.md`, which Ample gives you with each release) gives every step in
order, each with the requirement it rests on: make the keys, introduce the client key, record,
submit, keep the acks, and hand the auditor your client public keys. In short:

```python
import httpx
from ample_receipts_client import (
    CoreStatementBuilder, HttpxPoster, Spool, Submitter,
    load_client_signing_key_file, load_ledger_public_keys, load_salt_key_file, service_url,
)

builder = CoreStatementBuilder(
    salt_key=load_salt_key_file("salt-key.json"),
    signer=load_client_signing_key_file("client-key.json"),
)
spool = Spool("receipts.spool", builder)
client = httpx.Client(transport=spool.transport())  # each attempt becomes a statement

# the root of the receipts service you use, https only; required (there is no default)
base_url = service_url(tenant, "https://receipts.example.com/receipts")
submitter = Submitter(spool, poster=HttpxPoster(base_url, api_key),
                      ledger_keys=load_ledger_public_keys(ledger_keys_bytes))
submitter.start()
```

`service_url(tenant, root)` gives `<root>/t/<tenant>` and refuses a root that is not `https`. If
your service's certificate comes from a private CA (an internal mesh, say), keep `https` and give
the poster an httpx client that trusts that CA; never turn verification off:

```python
import ssl
private = httpx.Client(timeout=30, verify=ssl.create_default_context(cafile="private-ca.pem"))
poster = HttpxPoster(base_url, api_key, client=private)
```

Without `client=` the poster uses httpx's own CA bundle (certifi's, or the one `SSL_CERT_FILE` or
`SSL_CERT_DIR` names, not the operating system's store), which holds no private CA.

Take the tee from the spool (`spool.transport()`, `Httpx2TeeTransport.for_spool(spool)`):
a bare `TeeTransport(inner, on_capture=...)` only hands each capture to your callback and
makes no statement and no G3 hold (MUST-142).

For a client built on `httpx2` (the current `openai` and `anthropic` SDKs), install the `httpx2`
extra (`ample-receipts-client[httpx2]`) and use the `httpx2` tee, the same tee on the same code path
(unit R05b):

```python
import httpx2, openai
from ample_receipts_client import Httpx2TeeTransport

client = openai.OpenAI(http_client=httpx2.Client(transport=Httpx2TeeTransport.for_spool(spool)))
```

Without the extra, the package never imports `httpx2`. One tee per client: closing a client closes
its tee and the transport the tee wraps. An app that calls `httpx2.alias_httpx()` before importing
the library gets `httpx2` from `import httpx`; the library notices, and `TeeTransport` then runs the
`httpx2` code path with `httpx2`'s decoders, giving the same records as `Httpx2TeeTransport`.

Each capture follows the call-receipt spec (the specification Ample gives you with each release)
wherever it touches it:

- One record per HTTP attempt: retries and redirects each make their own.
- The wire kind (`CHAT_COMPLETIONS`, `RESPONSES`, `MESSAGES`, `OPAQUE`) comes
  from the method and the raw path alone; the terminal follows the spec's
  order (`TRANSPORT_FAILURE`, `OUTCOME_UNKNOWN`, `HTTP_ERROR`, `COMPLETED`).
- Bodies are recorded after content-decoding, with httpx's own decoders, as
  `DECODED` or (an unsupported or failed coding) `WIRE`; a body over the
  capture limit (16 MiB by default, never less) is `NOT_CAPTURED`.
- Header values are their wire bytes read as ISO-8859-1 (one code point per
  byte, as httpx and httpx2 read them): `caf\xe9` is committed as `café`,
  the UTF-8 bytes `caf\xc3\xa9` as `cafÃ©`, so the same bytes always give
  the same commitment.
- Headers are read by two closed allow-lists only, so credential headers are
  never read. Credential query values (the spec's 20 names, plus any the
  customer adds) and URL user-info are replaced by `MASKED` before the head
  and upstream parts are recorded.
- G3: with a `hold_hook` set and the hold on, everything from the hold point
  waits for the hook, at most `hold_deadline_ms` (250 by default, 1 to 10,000)
  from that point, and is then released either way; anything but a hook that
  returned in time is recorded `MISSED`. With no hook it never holds.
  The terminator scan holds a line, and an event's data, only up to the
  capture limit; past it the scan stops for that reply
  (`terminator:EventTooLarge` in `capture_errors`): nothing is held before
  the body's end, where the hold still applies as for any reply with no
  terminator, and the terminal is `OUTCOME_UNKNOWN` unless an earlier
  rule applies. The
  async hold waits on asyncio; under another event loop it fails open and
  records the miss.
- Only httpx- and `httpx2`-based clients are recorded live; every other client is recorded
  after the fact (below). WebSocket/realtime and batch APIs are out of scope.

**After the fact** (`ample_receipts_client.record`, unit R18): for any other client (another
HTTP library, gRPC, another language), hand `Recorder.record` the request and the response your
client already made. It runs the tee's own rules on them (wire kind, reply form, masking, the
allow-lists) and builds the same signed statement with capture basis `REPORTED_AFTER_THE_FACT`
and `hold` `OFF`; each part you do not supply is `NOT_CAPTURED`, and the terminal and times are
your report (with no terminal given it follows the spec's order from what you supplied). A value
it cannot take (a wrong type, text that cannot be encoded, a terminal that contradicts the
response) raises `RecordInputError` or `TypeError` and records nothing; any other failure is
recorded, never raised. A header field whose name is empty or not ASCII is skipped, its value
unread: no allow-list name is such a name. The method is committed as sent, so `post` is not
`POST`, and such a call is `OPAQUE` (MUST-9). Give it a spool file of its own, with G3 off
(`Recorder.open` does both). Each `headers` is a list of `(name, value)` pairs in the order
sent or received, or a mapping, whose order is taken as that order (MUST-44); `recorder.spool`
is the spool a submitter sends:

```python
from ample_receipts_client import Recorder, ReceivedResponse, SentRequest

recorder = Recorder.open("after.spool", salt_key=salt_key, signer=client_key)
recorder.record(
    SentRequest("POST", url, headers=sent_headers, body=sent_body),
    ReceivedResponse(200, headers=received_headers, body=received_body),
)
```

`python -m ample_receipts_client.submit pairs.jsonl --spool after.spool --salt-key FILE
--client-key FILE` does the same for a file of pairs (one JSON object per line, bodies in base64;
the partner guide's `record()` section gives every member) and, with `--service URL --api-key-file FILE
--ledger-keys FILE`, sends the spool's statements through the submitter. A malformed line is
refused with its line number and the rest are still recorded. It prints counts only and reads the
API key from a file, never from the command line.

**Reveal** (`ample_receipts_client.reveal`, unit R17; spec 5.8 and 6): to show an auditor one
part of one call, `python -m ample_receipts_client.reveal` derives that part's salt again from the
salt key file (MUST-65), takes the part's bytes from the opt-in vault (`--vault-dir` and
`--vault-key-file`) or from the app's own copy (`--data-file`), and checks the reveal against the
call receipt as the auditor's `reveal-call` will (MUST-62, and the receipt's own members and
formats, MUST-126 step 3) before it writes anything. The receipt comes from `--receipt` (its
canonical payload as stored) or from `--held-acks FILE --statement-id ID`. Every key comes from a
file; no option takes a key's or a salt's value. On R07's vector S1, with its TEST ONLY salt key:

```
$ python -m ample_receipts_client.reveal --salt-key-file keys/salt.key --receipt s1.receipt \
      --part response_body --data-file response.bin --out reveal-s1
MATCH: part response_body of statement d962c036-24d1-4c5e-b6ee-fddd31e3bd82 is revealed in reveal-s1
  receipt reveal-s1/receipt.txt
  data    reveal-s1/response_body.bin
  salt    reveal-s1/response_body.salt
The auditor checks it offline, with no salt key, with:
  python -m ample_replay.verify reveal-call --receipt reveal-s1/receipt.txt --part response_body --data-file reveal-s1/response_body.bin --salt-file reveal-s1/response_body.salt
```

The directory is new (mode 0700) and each file is 0600; only the one part's salt leaves, never
the salt key (MUST-67). A reveal that would not match writes nothing, prints 5.8's reason (for
other data, `MISMATCH: COMMITMENT_DIFFERS`) and exits 1; an input it refuses (a receipt it cannot
read, a salt key that is not the statement's) exits 2.

The **spool** (`ample_receipts_client.spool.Spool`, unit R11) is the local
store the tee's hook writes to: one SQLite file in WAL mode, fsynced before the
reply's end is released (G3). Each process gets its own instance id and
sequence (1, 2, 3, with a hash chain), a forked child a new one, and several
processes can share one spool file. A record left by a killed process is
numbered by the next instance as `MISSED`; damage found inside the file is
named by a `SPOOL_DAMAGED` declared loss. A deleted spool (a lost tail) is not
detected, nor is a process that dies while its spool keeps failing (the numbers
it would have declared lost were held in memory). The statements themselves (commitments, salts, signatures) come from
the spool's builder (`ample_receipts_client.builder.CoreStatementBuilder`, unit R12):

```python
spool = Spool("receipts.spool", builder)
client = httpx.Client(transport=spool.transport(httpx.HTTPTransport()))
```

**Keys** (spec 6 and 7): `SaltKey.generate(tenant).write_file(path)` and
`ClientKey.generate().write_file(path)` make the two key files once, each new and mode 0600
(MUST-64, MUST-68, MUST-69, MUST-71); `load_salt_key_file` and `load_client_signing_key_file`
read them back and refuse a file group or other can read. `introduction_request(client_key,
tenant)` builds the introduction and `rotation_request(previous_key, new_key, tenant)` a rotation;
`submitter.send_key_request(request)` journals it, posts it through the submitter's poster to the
service's `/v1/client-keys/introductions` or `/v1/client-keys/rotations` with the tenant API key,
sends the same bytes again after a crash or a lost answer, checks the ack with
`check_ack(ack, pinned_keys=ledger_keys, key_request=request)` and keeps it beside the
statements' acks, a failed one marked and alarmed (MUST-77, MUST-93, MUST-107, MUST-108). Its
result is `ACKNOWLEDGED`, `ACK_FAILED`, `REFUSED` with the service's reason, `NOT_WRITTEN` or
`OUTCOME_UNKNOWN`. `client_keys_file_text([client_key])` is the `ample.call-client-keys.v1` file you
hand your auditor (MUST-80).

**Submission** (spec 9 and 11): `Submitter(spool, poster=HttpxPoster(service_url, api_key),
ledger_keys=...)` sends one spool's statements to `<service_url>/v1/statements` and checks
every ack under the pinned ledger keys; `start()` runs it in the background, `drain(timeout)`
until nothing waits (call `spool.flush()` first at shutdown, since the submitter sends only
sealed statements); `acks()` and `key_acks()` list the kept acks and `write_held_acks(path)`
writes the passing ones of both, one per line in `link.seq` order, mode 0600 even over an
existing file, and refuses a symbolic link (MUST-93, MUST-107, MUST-108). `drain()` makes passes
of its own, so it still sends after `stop()`. Give each submitter its own `HttpxPoster`: a poster
takes no lock, and one without `client=` makes its httpx client on its first post. `python -m
ample_receipts_client.held_acks --spool FILE --out FILE` writes the same held-acks file from a spool
without a submitter (a new file, 0600), and with `--spool` once per spool it writes one file of
several spools' acks (an app's live and after-the-fact spools), each ack once; the auditor gives
it to the verifier with `--held-acks`, or to `python -m ample_replay.verify.audit` (MUST-108,
MUST-125). `read_statements(path)` lists a spool's statements read-only, with no `Spool` and no
key; it never changes the database file, but for a closed or copied spool SQLite makes the
`-wal` and `-shm` files beside it, so the directory must be writable. The partner guide (`integration.md`) names each field of
`KeptAck`, `KeptKeyAck`, `SpooledStatement`, `Backlog`, `RecordResult` and `Alarm`, and shows
`check_ack(ack, pinned_keys=..., statement=..., signature=...)` for a statement's ack and
`check_ack(ack, pinned_keys=..., key_request=kept.key_request)` for a kept key ack.

**Demo** (`ample_receipts_client.demo`, the pilot's R23): `python -m ample_receipts_client.demo`
makes receipts with this library alone (it imports the library, the standard library and httpx),
against a mock model inside the process, so a clean venv holding only this wheel and the
verifier's can show the whole path from a call to the auditor's check:

```
$ ROOT=https://receipts.example.com/receipts
$ python -m ample_receipts_client.demo init --dir demo --tenant acme-pilot \
      --service-url "$ROOT/t/acme-pilot" \
      --api-key-file api-key --ledger-keys ledger-public-keys.json --vault
$ python -m ample_receipts_client.demo run --dir demo --calls 6
$ python -m ample_receipts_client.demo handover --dir demo --out for-auditor
```

`init` talks to the `--service-url` it is given, which is required: your tenant's URL at the
receipts service you use, `<root>/t/<tenant>` as `service_url(tenant, root)` makes it, `https`
(plain `http` only to this machine). It makes
the client key and the salt key (and with `--vault` the vault key) in `--dir`, each new and mode
0600, and `demo.json`, which names every file the demo reads; it prints no key and
never overwrites one. A service with a certificate from a public CA needs no CA file:
httpx's default bundle verifies it (certifi's, or the one `SSL_CERT_FILE` or `SSL_CERT_DIR`
names, not the operating system's store). `--ca-file` names another PEM bundle, such as your
private CA's; it is the httpx client's `verify` for every request, and nothing turns verification off.
`run` first reaches the service (`GET /v1/keys` under the tenant API key, read from its file) and
stops with the TLS error, before any call, when the certificate does not verify. It introduces
the client key on the first run (`send_key_request`; a later run finds the kept ack), makes
`--calls` calls through the tee to the mock upstream (`https://api.example.test/v1/chat/completions`,
answered inside the process with fixed JSON and event-stream replies; every `--stream-every`-th
call streams, 2 by default) with G3 on at 250 ms, drains the submitter, checks every ack, and
writes `held-acks.jsonl` and `client-keys.json`. It prints counts, the receipts' ledger range and
the G3 misses, never a text, a body or a key, and exits 1 if any call is left unacknowledged.
`handover` copies the held acks, the client public keys and the ledger public keys into a new
directory with one reveal (`--reveal-call N`, `--reveal-part`, from the vault or the demo's own
copy of the fixture bytes; `--no-reveal` for none), never a private key, the salt key, the vault
key or the API key, and prints the auditor's `python -m ample_replay.verify.audit` command for the
tenant bundle the service's operator exports.

The library commits, signs and spools statements on the machine that makes the calls. It sends
to the receipts service the customer names only the statements with their client signatures,
through the submitter (`ample_receipts_client.submitter`, or `python -m
ample_receipts_client.submit --service URL`), and the client-key requests
(`Submitter.send_key_request`), both under the tenant API key. A statement carries commitments, never a part's data (spec 5); no
salt, salt key or private key is sent.

## Changes before the first release

These changes came before the first release on PyPI, so no published version behaves
otherwise.

- **The service root is required (breaks).** Each customer runs the receipts service on its own
  infrastructure, so the library no longer sends anywhere by default. `DEFAULT_SERVICE_ROOT` is
  gone from the package, `service_url(tenant, root)` takes the root as a required argument
  (`service_url(tenant)` is a `TypeError`), and the demo's `init` requires `--service-url`. Pass
  the root of the service you use; it stays `https` only, and a private CA is trusted through the
  httpx client you give `HttpxPoster` (above).
