
![Swarmauri Logo](https://github.com/swarmauri/swarmauri-sdk/blob/3d4d1cfa949399d7019ae9d8f296afba773dfb7f/assets/swarmauri.brand.theme.svg)

<p align="center">
    <a href="https://pypi.org/project/swarmauri_certs_cfssl/">
        <img src="https://img.shields.io/pypi/dm/swarmauri_certs_cfssl" alt="PyPI - Downloads"/></a>
    <a href="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_certs_cfssl/">
        <img alt="Hits" src="https://hits.sh/github.com/swarmauri/swarmauri-sdk/tree/master/pkgs/community/swarmauri_certs_cfssl.svg"/></a>
    <a href="https://pypi.org/project/swarmauri_certs_cfssl/">
        <img src="https://img.shields.io/pypi/pyversions/swarmauri_certs_cfssl" alt="PyPI - Python Version"/></a>
    <a href="https://pypi.org/project/swarmauri_certs_cfssl/">
        <img src="https://img.shields.io/pypi/l/swarmauri_certs_cfssl" alt="PyPI - License"/></a>
    <a href="https://pypi.org/project/swarmauri_certs_cfssl/">
        <img src="https://img.shields.io/pypi/v/swarmauri_certs_cfssl?label=swarmauri_certs_cfssl&color=green" alt="PyPI - swarmauri_certs_cfssl"/></a>
</p>

---

# Swarmauri Cert Cfssl

CFSSL-backed certificate service for Swarmauri.

## Features
- `CfsslCertService` adapter that wraps the CFSSL REST API for signing, parsing, and verifying certificates.
- Supports RSA, ECDSA (P-256/P-384), and Ed25519 key material with profile/label routing.
- Optional certificate bundling during verification to ensure complete chains before deployment.
- Detailed parsing utilities that expose SANs, key usage, EKU, Subject/Authority Key Identifiers, and more.

## Prerequisites
- Python 3.10 or newer.
- A reachable CFSSL instance (standalone binary, Kubernetes deployment, or the Cloudflare Docker image).
- Valid CFSSL signing profile(s) configured for your use case (e.g., `www`, `client`, `code_signing`).
- If your CFSSL endpoint is protected, API credentials or access tokens for the headers you plan to use.

## Installation

```bash
# pip
pip install swarmauri_certs_cfssl

# poetry
poetry add swarmauri_certs_cfssl

# uv (pyproject-based projects)
uv add swarmauri_certs_cfssl
```

## Quickstart: Issue a Certificate

`CfsslCertService` consumes CSRs generated by other Swarmauri certificate services (for example, the Azure or ACME packages). The example below submits a CSR to CFSSL and saves the issued certificate:

```python
import asyncio
from datetime import datetime, timedelta, timezone
from pathlib import Path

from swarmauri_certs_cfssl import CfsslCertService
from swarmauri_core.crypto.types import KeyRef


async def main() -> None:
    service = CfsslCertService(
        base_url="https://cfssl.internal",
        default_profile="www",
        timeout_s=15.0,
        auth_header=("X-Auth-Key", "super-secret-token"),
    )

    csr_bytes = Path("site.csr").read_bytes()

    # KeyRef tags allow you to override CFSSL profile/label per request
    ca_key = KeyRef(material=b"", tags={"profile": "www", "label": "primary"})

    certificate_pem = await service.sign_cert(
        csr=csr_bytes,
        ca_key=ca_key,
        extensions={
            "subject_alt_name": {"dns": ["site.example.com", "www.site.example.com"]}
        },
        not_after=int((datetime.now(timezone.utc) + timedelta(days=90)).timestamp()),
    )

    Path("site.pem").write_bytes(certificate_pem)
    await service.aclose()


if __name__ == "__main__":
    asyncio.run(main())
```

## Verify and Parse Certificates

Leverage CFSSL's bundling API to confirm a certificate's trust chain, then inspect the returned metadata:

```python
import asyncio
from pathlib import Path

from swarmauri_certs_cfssl import CfsslCertService


async def verify_and_parse() -> None:
    service = CfsslCertService(
        base_url="https://cfssl.internal",
        use_bundle_for_verify=True,
    )

    cert_bytes = Path("site.pem").read_bytes()

    verification = await service.verify_cert(
        cert=cert_bytes,
        trust_roots=[Path("root.pem").read_bytes()],
    )
    print("Valid:", verification["valid"], "Chain length:", verification["chain_len"])

    parsed = await service.parse_cert(cert_bytes)
    print("Subject CN:", parsed["subject"].get("CN"))
    print("SAN entries:", parsed.get("san", {}))

    await service.aclose()


if __name__ == "__main__":
    asyncio.run(verify_and_parse())
```

## Notes
- `CfsslCertService` focuses on signing and validation. Generate CSRs with other Swarmauri services (e.g., `swarmauri_certs_acme`, `swarmauri_certs_azure`) or your existing PKI tooling.
- The client uses `httpx.AsyncClient`; reuse a service instance for multiple operations and call `aclose()` when finished to release connections.
- Profile and label defaults can be set globally in the constructor or dynamically by attaching tags to the `KeyRef` passed into `sign_cert`.

## Best Practices
- Store CFSSL credentials outside source control (environment variables, secret stores, or Swarmauri state providers).
- Enable TLS on the CFSSL API and pin the certificate when connecting over untrusted networks.
- Use dedicated CFSSL profiles for each application tier and rotate them regularly.
- Capture verification results (e.g., bundle size, expiry) in metrics to stay ahead of certificate renewals.
