# TLS and Network Security

Source: https://docs.formance.com/v4.0/modules/ledger/operations/tls-and-network-security

Stack: v4.0

Use TLS for Ledger's service gRPC API and inter-node traffic. In a multi-node authenticated cluster, TLS also protects the shared cluster secret that followers use when they forward a caller's write to the leader.

TLS does not decide which user may call an API. Configure [authentication and authorization](https://docs.formance.com/v4.0/modules/ledger/operations/authentication) separately, and terminate HTTPS for the HTTP API at your ingress or load balancer.

## Prepare the certificate

The server certificate must cover every DNS name that Ledger nodes and clients use. Take the exact service and pod names from your Stack release. If it uses the example names below for a deployment named `payments` in the `formance` namespace, include both names:

```text
ledger-payments.formance.svc.cluster.local
*.ledger-payments-headless.formance.svc.cluster.local
```

Add the external gRPC hostname when the connection reaches Ledger with that server name:

```text
grpc.ledger.example.com
```

The wildcard covers pod addresses such as:

```text
ledger-payments-0.ledger-payments-headless.formance.svc.cluster.local
```

Do not issue a certificate only for `localhost` or a load-balancer address. Raft members and Stack jobs dial internal service and pod names. A missing SAN can leave pods running while inter-node calls fail certificate verification.

The leaf certificate and key must use PEM encoding. Protect the private key; clients only need the CA bundle. Use only the Secret reference and key names documented by your Stack release.

## Prepare the Stack v4 TLS rollout

Operator-managed TLS is not available in this Stack v4 preview. Use the direct-server workflow below only for evaluation, and wait for your release's Stack Operator reference before changing production TLS.

Ledger supports three modes. A production rollout must use the compatibility mode to move a running cluster through two rolling updates:

```mermaid
flowchart LR
    D["disabled<br/>plaintext"] --> O["optional<br/>TLS and plaintext"]
    O --> R["required<br/>TLS only"]
```

In `optional` mode, an updated node accepts TLS and plaintext while other members restart. After every node has converged, the controller can roll the cluster again in `required` mode. Before production, verify that the released Operator owns both passes, references the Secret, and reports which member prevents convergence.

Do not edit the generated workload or its environment variables. Let the released Stack Operator own both passes.

### Verify the direct server behavior

Use a disposable single-node deployment to verify the Ledger flags. This command creates a new evaluation cluster and requires TLS from its first start:

```bash
export LEDGER_CLUSTER_SECRET='<random-evaluation-secret>'

ledger run \
  --node-id 1 \
  --cluster-id tls-evaluation \
  --bind-addr 127.0.0.1:7777 \
  --grpc-port 8888 \
  --http-port 9000 \
  --wal-dir ./tls-evaluation/wal/node-1 \
  --data-dir ./tls-evaluation/data/node-1 \
  --bootstrap \
  --tls-mode required \
  --tls-cert-file ./tls.crt \
  --tls-key-file ./tls.key \
  --tls-ca-cert-file ./ca.crt \
  --cluster-secret "$LEDGER_CLUSTER_SECRET"
```

Ledger refuses to start with `--cluster-secret` while TLS is disabled. Use `--bootstrap` only on the first start; keep the same identity, storage paths, TLS files, and cluster secret when restarting without that flag.

## Understand cluster trust

When a cluster secret is configured, every Ledger node must receive the same value. Inter-node gRPC calls use that static bearer token to identify a trusted peer. The Stack Operator must generate or reference this value and distribute it without exposing it in the resource.

This internal identity matters when a client sends a mutation to a follower:

1. The follower authenticates the client and records its subject and scopes.
2. The follower forwards the mutation and caller snapshot to the leader.
3. The follower authenticates that internal call with the cluster secret.
4. The leader accepts the forwarded caller snapshot only from a trusted cluster connection.

Ledger refuses to start with a cluster secret while TLS is disabled because the secret would cross the network in plaintext. Do not copy the cluster secret into application clients; it grants the internal path all Ledger scopes.

## Require client certificates

By default Ledger verifies an inbound client certificate only if one is presented. A peer that presents none still completes the TLS handshake and falls through to cluster-secret or JWT authentication. That is the permissive posture, and it is the one you get unless you change it.

`--tls-require-client-cert` switches inbound verification to reject any connection without a CA-signed client certificate. It needs a CA to verify against, so Ledger refuses to start if `--tls-ca-cert-file` is not also set.

```bash
ledger run \
  --tls-mode required \
  --tls-cert-file ./tls.crt \
  --tls-key-file ./tls.key \
  --tls-ca-cert-file ./ca.crt \
  --tls-require-client-cert \
  ...
```

Enabling this rejects every client that does not present a CA-signed certificate — including a `ledgerctl` invocation that passes only `--tls-ca-cert`, which verifies the _server_ and sends no client certificate of its own. Issue client certificates to every caller, including your own administrative tooling, before you turn it on.

## Connect with ledgerctl

Dial a DNS name present in the certificate and pass the CA bundle:

```bash
ledgerctl \
  --server ledger-payments.formance.svc.cluster.local:8888 \
  --tls-ca-cert ./ca.crt \
  ledgers list
```

If the dial address cannot match a certificate SAN, keep the network address and verification name separate:

```bash
ledgerctl \
  --server 127.0.0.1:8888 \
  --tls-server-name ledger-payments.formance.svc.cluster.local \
  --tls-ca-cert ./ca.crt \
  ledgers list
```

`--tls-server-name` cannot be combined with `--insecure`. A profile can store `tlsCaCert` and `tlsServerName` so operators do not need to repeat them.

## Verify every replica

After the released Stack v4 status reports that every member requires TLS, test TLS and a forwarded write through each directly reachable replica. The example assumes `security-smoke` already exists and that `LEDGERCTL_AUTH_TOKEN` contains `ledger:read` and `ledger:TransactionWrite`. If the cluster requires request signatures, add the signing key and key ID described in [Request and Response Signing](https://docs.formance.com/v4.0/modules/ledger/operations/signing).

```bash
for server in \
  "ledger-0.internal.example.com:8888" \
  "ledger-1.internal.example.com:8888" \
  "ledger-2.internal.example.com:8888"
do
  ledgerctl \
    --server "$server" \
    --tls-ca-cert ./ca.crt \
    transactions create \
    --ledger security-smoke \
    --posting "world,security:tls-probe:${server%%.*},1,TEST"
done
```

Every command must succeed regardless of which node is the current leader. This validates more than pod readiness: it exercises certificate verification, the cluster secret, caller forwarding, leader routing, and the response path.

Verify the resulting accounts through the stable service:

```bash
for account in ledger-0 ledger-1 ledger-2; do
  ledgerctl \
    --server ledger.internal.example.com:8888 \
    --tls-ca-cert ./ca.crt \
    accounts get "security:tls-probe:${account}" \
    --ledger security-smoke
done
```

## Restrict network access

Keep network policy in platform-owned configuration unless your Stack release explicitly manages it. Permit only the paths Ledger requires:

- Raft, gRPC, and HTTP traffic between members of the same Ledger deployment;
- DNS over TCP and UDP;
- the exact OIDC, event broker, object-store, and OpenTelemetry destinations configured for the deployment.

Define ingress rules separately to limit callers to the gateway, Stack Operator, monitoring, and approved application namespaces.

Private OIDC providers, databases, event brokers, object stores, and telemetry collectors need explicit egress where applicable. Test every dependency after enabling the policy; a healthy Ledger API does not prove that backups or event delivery can leave the pod.

## Terminate external traffic intentionally

Ledger's server TLS protects service and inter-node gRPC. Treat external endpoints separately:

| Endpoint                   | Recommended boundary                                                                                                |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| HTTP API                   | HTTPS terminated by the ingress or load balancer, with TLS from the edge to Ledger according to your cluster policy |
| External gRPC              | A gRPC-capable ingress or load balancer whose certificate and backend mode match the connection path                |
| Headless and Raft services | Cluster-internal only; do not expose them through an external load balancer                                         |

Avoid a TLS mode where the ingress speaks plaintext to a Ledger gRPC service that already requires TLS. This usually surfaces as `error reading server preface` or a connection reset rather than an HTTP error.

## Rotate certificates

Ledger watches the mounted leaf certificate, private key, and inbound CA bundle and reloads them for new server handshakes. Outbound gRPC trust pools do not reload a changed CA bundle in place.

For a leaf-only rotation signed by the same CA:

1. issue a certificate with the same required SANs;
2. update `tls.crt` and `tls.key` together;
3. open a new connection to every replica and verify the presented certificate;
4. repeat the forwarded-write test.

For a CA rotation, publish a bundle containing both old and new CA certificates, restart one node at a time so outbound trust picks up the bundle, rotate leaf certificates, verify every peer, then remove the old CA in a second rolling update. Preserve quorum throughout both passes.

## Disable TLS

The production disable workflow must reverse the two passes: `required` → `optional` → `disabled`. The Stack Operator must remove the cluster secret only after every node has stopped referencing it. Do not attempt this rollout unless the released workflow explicitly supports and reports both passes.

Do not disable TLS on an externally reachable production cluster. In particular, do not disable it while a multi-node deployment relies on authenticated forwarded writes. The final state removes the encrypted inter-node trust channel and accepts plaintext gRPC.

## Diagnose connection failures

| Symptom                                                                  | Likely cause                                                                               | Check                                                                                                  |
| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------ |
| `x509: certificate is valid for ...`                                     | The dialed name is missing from the SAN list                                               | Dial a covered DNS name or set `--tls-server-name` to one                                              |
| `certificate signed by unknown authority`                                | Wrong or incomplete CA bundle                                                              | Compare the server certificate chain with the file passed to `--tls-ca-cert`                           |
| Stack TLS rollout does not converge                                      | A member cannot become ready in the current compatibility pass                             | Inspect the released Stack conditions and the affected Ledger node's TLS startup logs                  |
| `error reading server preface`                                           | Client and server disagree about plaintext versus TLS                                      | Remove `--insecure` and provide the CA when the cluster is `required`; check ingress backend protocol  |
| Direct leader writes work, follower writes fail                          | Cluster secret drift, TLS failure between nodes, or an untrusted forwarded caller snapshot | Confirm every member received the same TLS files and cluster secret; repeat the per-replica write test |
| Server rejects `--cluster-secret` at startup                             | TLS mode is `disabled` or the certificate/key flags are missing                            | Move through `optional` before `required`, or let the released Stack controller coordinate the change  |
| Private IdP or broker becomes unreachable after NetworkPolicy activation | The egress policy blocks its private address                                               | Add a narrowly scoped platform-owned egress rule and retest that dependency                            |
