> ## Documentation Index
> Fetch the complete documentation index at: https://developer.onetrust.com/llms.txt
> Use this file to discover all available pages before exploring further.

# TLS & Certificate Pinning

AI Guard supports TLS encryption for all SDK-to-service communication. Certificate pinning provides an additional layer of security by verifying the server's identity using its public key, without the overhead of managing internal DNS and CA-signed certificates.

## TLS Configuration

### Service-Side TLS

TLS is configured in the `service.tls` section of the AI Guard configuration file:

```yaml
service:
  tls:
    key-path: "${TLS_KEY_PATH:-/etc/ssl/litenode/tls.key}"
    certificate-path: "${CERTIFICATE_PATH:-/etc/ssl/litenode/tls.crt}"
```

| Field              | Env Var            | Default                     | Description                          |
| ------------------ | ------------------ | --------------------------- | ------------------------------------ |
| `key-path`         | `TLS_KEY_PATH`     | `/etc/ssl/litenode/tls.key` | Path to TLS private key (PEM format) |
| `certificate-path` | `CERTIFICATE_PATH` | `/etc/ssl/litenode/tls.crt` | Path to TLS certificate (PEM format) |

> 📘 Disabling TLS
>
> If the `tls` section is omitted, the server falls back to plain HTTP. Use the `--no-tls` CLI flag to explicitly disable TLS. **Not recommended for production.**

### Generating a Self-Signed Certificate

For development or internal deployments, create a self-signed certificate:

```ini
# ai-guard.cnf
[req]
default_bits       = 4096
distinguished_name = req_distinguished_name
x509_extensions    = v3_ca
prompt             = no

[req_distinguished_name]
CN = ai-guard.local

[v3_ca]
basicConstraints     = critical, CA:true
keyUsage             = critical, digitalSignature, keyCertSign, keyEncipherment
extendedKeyUsage     = serverAuth
subjectKeyIdentifier = hash
subjectAltName = @alt_names

[alt_names]
DNS.1 = ai-guard.local
DNS.2 = localhost
# Add your actual hostnames and IPs
```

```bash
openssl req -x509 -newkey rsa:4096 -sha256 -days 365 -nodes \
  -keyout server.key -out server.crt -config ai-guard.cnf
```

## Certificate Pinning

Certificate pinning verifies the server's identity by matching the SHA-256 hash of its public key. This approach:

* Works with self-signed certificates without needing a CA trust chain
* Survives certificate rotation as long as the same key pair is reused
* Eliminates the need for hostname verification — the URL can use IP addresses or `localhost`

### Generating the Pin

Extract the pin from the server certificate:

```bash
openssl x509 -in server.crt -pubkey -noout \
  | openssl pkey -pubin -outform DER \
  | openssl dgst -sha256 -binary \
  | base64
```

This outputs a base64-encoded string like: `x48Lk2iu3R3nAhSiz07bExGHTusDRjHqBx9ArK3cFGE=`

### SDK Certificate Pinning

Pass the `pin_sha256` parameter when creating the client:

```python
from ai_guard import AIGuardClient
from ai_guard.api import AIPlatform

client = AIGuardClient(
    "https://ai-guard.example.com:4443",
    token="your-api-key",
    agent_id="my-agent",
    platform=AIPlatform.AMAZON_BEDROCK,
    pin_sha256="x48Lk2iu3R3nAhSiz07bExGHTusDRjHqBx9ArK3cFGE=",
)
```

#### How Pinning Works

After the TLS handshake completes:

1. The SDK extracts the server certificate's public key
2. Computes the SHA-256 hash of the public key
3. Compares it against the pinned digest
4. If they don't match, the connection is closed **before any HTTP data is sent**

#### Pinning Behavior

When `pin_sha256` is provided (and no custom `session` is given):

| Behavior            | Description                                                                          |
| ------------------- | ------------------------------------------------------------------------------------ |
| **CA chain bypass** | CA-based verification is disabled; the connection is secured by the pinned key alone |
| **Hostname skip**   | The certificate's Common Name and Subject Alternative Names are not checked          |
| **Rotation safe**   | Certificate rotation is transparent as long as the same key pair is reused           |

> ⚠️ Key Pair Changes
>
> If the server's key pair changes, the `pin_sha256` value must be updated. The connection will be refused until the pin is updated.

#### Validation

The pin is validated eagerly at construction time. Invalid base64 or a digest that isn't exactly 32 bytes raises `ValueError` immediately.

### curl Certificate Pinning

Use curl's `--pinnedpubkey` option for command-line testing:

```bash
curl --pinnedpubkey "sha256//x48Lk2iu3R3nAhSiz07bExGHTusDRjHqBx9ArK3cFGE=" \
  https://ai-guard.example.com:4443/health
```

> 📘 Note the double slash
>
> curl uses `sha256//` (with double slash), while the SDK uses just the base64 string.

## Custom CA Bundle

If your organization uses a corporate CA, pass a pre-configured `requests.Session` instead of using certificate pinning:

```python
import requests
from ai_guard import AIGuardClient
from ai_guard.api import AIPlatform

session = requests.Session()
session.verify = "/path/to/corporate-ca-bundle.pem"

client = AIGuardClient(
    "https://ai-guard.example.com:4443",
    token="your-api-key",
    agent_id="my-agent",
    platform=AIPlatform.AMAZON_BEDROCK,
    session=session,
)
```

> ⚠️ Mutual Exclusivity
>
> `session` and `pin_sha256` are **mutually exclusive**. If you provide a custom `requests.Session`, the `pin_sha256` parameter is ignored. The SDK assumes you have already configured TLS on your session.

## Choosing the Right Approach

| Scenario                         | Recommended Approach                               |
| -------------------------------- | -------------------------------------------------- |
| Self-signed certificates         | Certificate pinning (`pin_sha256`)                 |
| Corporate CA-signed certificates | Custom session with `verify` pointing to CA bundle |
| Public CA-signed certificates    | No extra configuration needed (default TLS)        |
| Development / testing            | Certificate pinning or `--no-tls`                  |

## What's Next?

* [Authentication & Authorization](https://developer.onetrust.com/onetrust/docs/ai-guard-authentication) — Configure how tokens are validated
* [Service Configuration](https://developer.onetrust.com/onetrust/docs/ai-guard-service-configuration) — Full configuration reference
* [Deploy the Light Worker Node](https://developer.onetrust.com/onetrust/docs/ai-guard-deploy-worker-node) — TLS setup during deployment