Metadata-Version: 2.4
Name: pq-http-message-signatures
Version: 0.1.0
Summary: Post-quantum HTTP Message Signatures (RFC 9421 + C2SP httpsig-pq, ML-DSA / FIPS 204) for Python
Author: PQ-HTTP contributors
License: MIT
Project-URL: Homepage, https://github.com/OWNER/pq-http-message-signatures
Project-URL: Issues, https://github.com/OWNER/pq-http-message-signatures/issues
Keywords: post-quantum,ml-dsa,fips-204,http-signatures,rfc9421,httpsig-pq,fastapi,api-security
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.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security :: Cryptography
Classifier: Typing :: Typed
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: cryptography>=47.0.0
Provides-Extra: starlette
Requires-Dist: starlette>=0.37; extra == "starlette"
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.110; extra == "fastapi"
Requires-Dist: starlette>=0.37; extra == "fastapi"
Provides-Extra: requests
Requires-Dist: requests>=2.31; extra == "requests"
Provides-Extra: dev
Requires-Dist: pytest>=8; extra == "dev"
Requires-Dist: pytest-cov>=5; extra == "dev"
Requires-Dist: hypothesis>=6.100; extra == "dev"
Requires-Dist: httpx>=0.27; extra == "dev"
Requires-Dist: fastapi>=0.110; extra == "dev"
Requires-Dist: starlette>=0.37; extra == "dev"
Requires-Dist: requests>=2.31; extra == "dev"
Requires-Dist: ruff>=0.5; extra == "dev"
Requires-Dist: mypy>=1.10; extra == "dev"
Requires-Dist: types-requests; extra == "dev"
Requires-Dist: build>=1.2; extra == "dev"
Requires-Dist: twine>=5; extra == "dev"
Requires-Dist: pip-audit>=2.7; extra == "dev"
Requires-Dist: bandit>=1.7; extra == "dev"
Requires-Dist: http-sfv>=0.9; extra == "dev"
Dynamic: license-file

# PQ-HTTP: post-quantum HTTP Message Signatures for Python

[RFC 9421](https://www.rfc-editor.org/rfc/rfc9421.html) HTTP Message Signatures with the
[C2SP `httpsig-pq`](https://c2sp.org/httpsig-pq) ML-DSA algorithms (NIST [FIPS 204](https://csrc.nist.gov/pubs/fips/204/final)),
with a secure-by-default verifier and FastAPI / Starlette / `requests` integrations.

> **Status: alpha, unaudited.** See [Verification status](#verification-status) for exactly what has and has not been run.
> This project does not invent cryptography: ML-DSA is provided by the [`cryptography`](https://cryptography.io) package.
> It is not affiliated with or endorsed by NIST, the IETF, C2SP or any vendor.

## Features

- C2SP `httpsig-pq` v1.0.1 identifiers `ml-dsa-44`, `ml-dsa-65`, `ml-dsa-87`; signature base passed to ML-DSA unchanged, empty context, 32-octet seed keys only.
- Signing and verification of **requests and responses**, `Content-Digest` (RFC 9530, sha-256/sha-512), `created` / `expires` / `nonce` / `tag` / `keyid` / `alg`.
- Verifier policy: algorithm allow-list, required covered components, body must be covered, clock skew and max age, optional nonce replay protection, signature/header/component/body limits.
- Strict RFC 8941 parser (bounded work on untrusted input), no extra runtime dependencies besides `cryptography`.
- Starlette middleware, FastAPI dependency, `requests` auth plugin.

## Security scope

Provides: authenticity and integrity of the *covered* message components, bound to a trusted key and algorithm.
Does **not** provide: confidentiality, replay protection unless you configure it, key distribution, authorization,
or protection of components you do not cover. Read [docs/security.md](docs/security.md) before deploying.

## Standards

RFC 9421 (subset, see [Known limitations](#known-limitations)), C2SP httpsig-pq v1.0.1, FIPS 204, RFC 8941, RFC 9530.

## Supported algorithms

| `alg` | Public key | Signature | Base64 `Signature` value |
|---|---|---|---|
| `ml-dsa-44` | 1,312 B | 2,420 B | 3,228 chars |
| `ml-dsa-65` | 1,952 B | 3,309 B | 4,412 chars |
| `ml-dsa-87` | 2,592 B | 4,627 B | 6,172 chars |

Signing keys are the 32-octet FIPS 204 seed. Expanded private keys are rejected, as C2SP requires.

## Installation

Requires Python 3.10+ and `cryptography >= 47` built against an OpenSSL with ML-DSA.

```bash
pip install pq-http-message-signatures                       # core (not yet published; use the source install below)
pip install "pq-http-message-signatures[fastapi,requests]"   # with integrations
# from source:
git clone https://github.com/OWNER/pq-http-message-signatures.git && cd pq-http-message-signatures
pip install -e ".[dev]"
python -m pq_http.diagnostics        # prints which ML-DSA parameter sets your backend supports
```

## Quick start

```python
from pq_http import Signer, StaticKeyResolver, Verifier

signer = Signer.generate(algorithm="ml-dsa-65")
signed = signer.sign_request(
    method="POST",
    url="https://api.example.com/data",
    headers={"content-type": "application/json"},
    body=b'{"message": "hello"}',
)

verifier = Verifier(
    key_resolver=StaticKeyResolver({signer.keyid: signer.public_key()}),
    allowed_algorithms=["ml-dsa-65"],
)
result = verifier.verify_request(signed)
print(result.valid)                 # True
print(result.covered_components)    # trust only these verified values
```

`verify_*` never raises for a bad message: it returns a `VerificationResult` with `valid=False` and a
`FailureReason`. Call `result.raise_for_failure()` if you prefer exceptions.

## Key generation

```python
from pq_http import SigningKey, VerifyingKey

key = SigningKey.generate("ml-dsa-87")      # 32 random bytes from the OS CSPRNG
key.save("signing-key.json")                # new file, mode 0600, never overwrites
key.public_key().save("public-key.json")    # share this one
key = SigningKey.load("signing-key.json")   # rejects group/world-readable files on POSIX
```

The key file format is this project's own (C2SP defines no container); the file contains the algorithm and seed.

## Signing examples

Responses can be bound to their request with the `req` parameter:

```python
response = signer.sign_response(status=200, headers={"content-type": "text/plain"}, body=b"ok", request=original_request)
```

`Signer` options: `request_components`, `response_components`, `include_alg`, `expires_in`, `include_nonce`, `tag`,
`add_content_digest`, `label`, `keyid`. A missing covered header raises `SigningError`; nothing is silently dropped.

## Verification examples

```python
from pq_http import VerificationPolicy, Limits

verifier = Verifier(
    resolver, ["ml-dsa-65"],
    policy=VerificationPolicy(
        required_request_components=("@method", "@target-uri", "content-type"),
        max_age=120, max_clock_skew=10, required_tag="my-app",
        limits=Limits(max_body_bytes=256 * 1024),
    ),
)
```

Verification order: size limits, structured-field parse, label selection, `keyid` and algorithm checks (allow-list and
key binding; `alg` can only narrow, never widen), time checks, required components, body coverage, signature,
`Content-Digest`, then replay storage (only after the signature is valid).

## FastAPI integration

```python
from fastapi import Depends, FastAPI
from pq_http import VerificationResult
from pq_http.integrations.fastapi import SignatureVerification

app = FastAPI()
require_signature = SignatureVerification(verifier, trusted_base_url="https://api.example.com")

@app.post("/data")
async def data(payload: dict, result: VerificationResult = Depends(require_signature)):
    return {"signed_by": result.keyid}
```

For whole-app protection use `pq_http.integrations.starlette.PQHTTPSignatureMiddleware(app, verifier, exclude_paths=["/health"])`.
Behind a proxy always set `trusted_base_url`, otherwise `@target-uri` is derived from the client-controlled `Host` header.
Runnable: `python examples/fastapi_server.py --self-test`.

## Client integration

```python
import requests
from pq_http.integrations.requests import PQHTTPSignatureAuth

requests.post("https://api.example.com/data", json={"message": "hello"}, auth=PQHTTPSignatureAuth(signer))
```

Streaming request bodies are rejected (the digest cannot be computed without consuming them).

## Replay protection

Signatures alone can be replayed. Protection exists only when **all three** are true: signers include a `nonce`,
the policy has `require_nonce=True`, and the verifier has a replay store.

```python
from pq_http import InMemoryReplayStore, VerificationPolicy

signer = Signer.generate("ml-dsa-65", include_nonce=True)
verifier = Verifier(resolver, ["ml-dsa-65"], policy=VerificationPolicy(require_nonce=True), replay_store=InMemoryReplayStore())
```

`InMemoryReplayStore` is per process: it is **not shared** across workers or machines and is lost on restart. In
production implement `ReplayStore.check_and_store(key, expires_at)` atomically on shared storage (e.g. Redis
`SET key 1 NX EXAT ...`). The verifier refuses to run a replay store without `require_nonce`, `require_created` and a
finite `max_age`, and `VerificationResult.replay_checked` tells you whether a nonce was actually recorded.

## Key management

Never commit keys; generate at deploy time and keep seeds in a secrets manager, KMS-wrapped storage or an HSM-backed
vault; give each signer its own key; keep one key per algorithm; rotate by publishing a new `keyid` in the resolver
before the signer switches, then retire the old one after `max_age`. `SigningKey` redacts itself in `repr`, cannot be
pickled, and `save()` refuses to overwrite. Test keys must be generated in tests, never reused in production.

## Configuration

| Setting | Default |
|---|---|
| `VerificationPolicy.max_age` / `max_clock_skew` | 300 s / 30 s |
| `require_created`, `require_content_digest_when_body`, `verify_content_digest` | `True` |
| `Limits.max_header_bytes` / `max_signatures` / `max_components` / `max_nodes` / `max_body_bytes` | 16 KiB / 4 / 32 / 512 / 1 MiB |

Size limits matter: one ML-DSA-87 signature uses ~6.2 KB of the typical 8 KB header budget of proxies and servers.

## Testing

```bash
make install && make vectors && make test     # lint/type/fuzz/examples: make all
```

## Benchmarks

```bash
python benchmarks/bench.py --output benchmarks/results.json
```

Reports key generation, raw sign/verify, full HTTP sign/verify, sizes, header overhead and an Ed25519 reference
(same backend, same process). **No benchmark numbers are published here**: the author's environment had no ML-DSA
backend, so nothing was measured. Run it on your hardware and report the JSON (it records OS, CPU, Python and
dependency versions).

## Compatibility

Python 3.10-3.13 targeted; Linux/macOS/Windows in the CI matrix (not yet run). Wire-compatible by construction with
other C2SP httpsig-pq implementations such as Linzer (Ruby); no cross-implementation exchange has been performed yet.
See [docs/interoperability.md](docs/interoperability.md).

## Known limitations

- Unsupported (rejected, never approximated): `@query-param`; component parameters `sf`, `bs`, `key`, `tr`; covering `signature`/`signature-input`.
- The signer adds exactly one signature per message; the verifier checks one label. No hybrid/classical+PQ policy engine.
- `@target-uri` is normalised (lower-case scheme/host, default port dropped, empty path -> `/`). ASGI cannot distinguish `/p` from `/p?`.
- Signing uses the backend's default mode; hedged behaviour is asserted by a test but depends on the backend. No deterministic mode is exposed.
- Seeds come from `secrets.token_bytes` (OS CSPRNG); no claim is made that this meets FIPS 204's approved-RBG requirement.
- RFC 9421 Appendix B vectors are not cross-checked. `Accept-Signature` is not implemented. Response signing is not offered by the ASGI middleware.

## Security warning

Alpha software, never independently audited, no side-channel or FIPS-validation claims. See [SECURITY.md](SECURITY.md).

## Roadmap

Run the official vectors and cross-implementation tests in CI; RFC 9421 Appendix B vectors; `@query-param`; Redis
replay store example; multiple-signature signing; hybrid policy helpers; PyPI release.

## Contributing

See [CONTRIBUTING.md](CONTRIBUTING.md).

## License

MIT, see [LICENSE](LICENSE). Runtime dependency `cryptography` is Apache-2.0 OR BSD-3-Clause (compatible). Check the
licenses of the exact versions you install (`pip-licenses`).

## Architecture

```mermaid
flowchart LR
  App[Application] --> Signer
  Signer --> Base[signature_base: RFC 9421 base]
  Base --> Keys[keys: SigningKey / VerifyingKey]
  Keys --> Crypto[(cryptography ML-DSA)]
  Req[HTTP request] --> MW[Starlette middleware / FastAPI dependency]
  MW --> Verifier
  Verifier --> SF[structured_fields parser + limits]
  Verifier --> Resolver[KeyResolver]
  Verifier --> Base
  Verifier --> Replay[ReplayStore]
```

## Verification status

Honest record of what was actually executed when this repository was produced (sandbox without network, with
`cryptography 46.0.6`, which has **no** ML-DSA API):

| Item | Status |
|---|---|
| Structured-field parser/serializer, message model, signature base | **Executed, passed** (offline). Signature bases for all three C2SP vectors match the published SHA-256 values. |
| Signer/verifier/replay/limits/key-file logic (~150 test cases) | **Executed, passed**, but first against an *insecure stand-in* and, for key/signer tests, against the reference oracle above (both kept outside this repository). |
| Parser fuzz harness | **Executed**: 30,000 inputs, no unexpected exception. |
| `requests` plugin; ASGI middleware (driven by hand-written ASGI calls: 200/401/413 paths); benchmark and example scripts | Executed against the stand-in only (timings discarded). The package also builds with setuptools (`pip install --no-build-isolation .`). |
| Official C2SP vector **ML-DSA-44**, end to end through this library (seed -> public key, signature base, `Signature-Input` text, official signature verified directly and via the full `Verifier`, all negative cases of the spec, hedged control) | **Executed, all passed.** Run against an independent pure-Python FIPS 204 reference that I wrote as a test oracle (kept outside this repo, not shipped). It reproduced the official deterministic signature byte-for-byte, which validates both the oracle and the vector transcription. Key and signer tests (48 cases) also passed on it. |
| Official vectors **ML-DSA-65 / ML-DSA-87**; the same checks against the real `cryptography` backend; hedged-signing test on the real backend | **Written, NOT executed** (vectors were not transcribed offline; needs `cryptography>=47` and `make vectors`). |
| Starlette/FastAPI `TestClient` tests, FastAPI dependency, Hypothesis tests, `http-sfv` cross-check | **Written, NOT executed** (packages unavailable offline). |
| ruff, mypy, build, twine, pip-audit, bandit, CI workflows | **NOT executed**. Run `make format` before the first `make lint`. |
| Real benchmarks | **NOT run**. |

Run `make vectors && make all` on a normal machine and fix anything that fails before relying on this code.
