# Authentication and Authorization

Source: https://docs.formance.com/v4.0/modules/ledger/operations/authentication

Stack: v4.0

Enable authentication before exposing a Ledger API outside a trusted development environment. Ledger accepts JWT bearer tokens from an OIDC issuer or from registered Ed25519 machine credentials, then checks the scopes required by each operation.

This page covers client identity and permissions. Configure [TLS](https://docs.formance.com/v4.0/modules/ledger/operations/tls-and-network-security) first: a node started with `--auth-enabled` refuses to boot unless `--tls-mode` is `required`. [Request signing](https://docs.formance.com/v4.0/modules/ledger/operations/signing) is a separate, optional control on top of both.

## Choose a credential source

| Credential source | Use it for                                                               | How Ledger validates the token                                                         |
| ----------------- | ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------- |
| OIDC              | People, services, and environments that already use an identity provider | Ledger discovers the issuer's JWKS and validates the signature, issuer, and expiration |
| Ed25519 JWT       | Workloads that need a Ledger-specific machine identity                   | Ledger verifies an EdDSA JWT against a static public key and its scope allowlist       |

Both sources can be active at the same time. Prefer OIDC when your organization already manages workload identities and rotation. Use Ed25519 credentials for bounded automation such as a CI job or an in-cluster agent.

## Understand scopes

The default virtual scopes provide three useful permission bundles. Their prefix comes from the configured auth service name (`--auth-service`, default `ledger`), so `--auth-service=myapp` makes them `myapp:read`, `myapp:write`, and `myapp:admin`. Granular scope names are unaffected: they always begin with the literal `ledger:`, whatever the service name is.

| Virtual scope  | Grants                                                                              |
| -------------- | ----------------------------------------------------------------------------------- |
| `ledger:read`  | Read ledgers, transactions, accounts, audit records, operational state, and queries |
| `ledger:write` | Write ledgers, transactions, metadata, audit state, operational state, and queries  |
| `ledger:admin` | Read and change cluster state                                                       |

Use granular scopes when a client needs less than a complete bundle:

```text
ledger:LedgerRead       ledger:LedgerWrite
ledger:TransactionRead  ledger:TransactionWrite
ledger:AccountRead      ledger:MetadataWrite
ledger:AuditRead        ledger:AuditWrite
ledger:OpsRead          ledger:OpsWrite
ledger:QueryRead        ledger:QueryWrite
ledger:ClusterRead      ledger:ClusterWrite
```

For example, an application that creates and reads transactions but cannot create ledgers can receive `ledger:TransactionRead`, `ledger:AccountRead`, and `ledger:TransactionWrite`.

## Prepare OIDC for Stack v4

Before you begin, confirm that every Ledger node can resolve and reach the issuer URL. OIDC discovery runs when a node starts; an unreachable issuer prevents an auth-enabled node from becoming ready.

Operator-managed authentication 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 configuring production authentication.

Before production, verify that your Stack release lets you:

- enable authentication explicitly;
- set the OIDC issuer and the scope-service prefix;
- reference credentials through Secrets without placing private key material in the Stack resource;
- observe whether every Ledger replica loaded the intended issuer and key set;
- rotate a key without removing the last credential that clients can use.

The issuer must expose its OpenID configuration at:

```text
https://identity.example.com/.well-known/openid-configuration
```

Configure the identity provider to put one or more Ledger scopes in the token's scope claim. A read-only service token can use:

```text
ledger:read
```

To verify Ledger authentication in a disposable direct deployment, start the first node with the same identity and storage paths described in [Deploy Ledger](https://docs.formance.com/v4.0/modules/ledger/operations/deploy), plus the authentication flags:

```bash
ledger run \
  --node-id 1 \
  --cluster-id auth-evaluation \
  --bind-addr 127.0.0.1:7777 \
  --grpc-port 8888 \
  --http-port 9000 \
  --wal-dir ./auth-evaluation/wal/node-1 \
  --data-dir ./auth-evaluation/data/node-1 \
  --bootstrap \
  --tls-mode required \
  --tls-cert-file ./tls.crt \
  --tls-key-file ./tls.key \
  --auth-enabled \
  --auth-issuer https://identity.example.com \
  --auth-service ledger
```

Use `--bootstrap` only for this node's first start. On restart, keep the same node ID, cluster ID, WAL directory, data directory, and authentication flags, but remove `--bootstrap`.

Authentication requires full TLS

If `--tls-mode` is `disabled` or `optional`, then a node started with `--auth-enabled` refuses to start — bearer tokens would otherwise be exposed to plaintext interception, and `optional` still accepts plaintext connections. This is a startup precondition on every topology, single-node included. Configure [TLS](https://docs.formance.com/v4.0/modules/ledger/operations/tls-and-network-security) first.

On a multi-node cluster it also carries the cluster secret: followers forward writes to the leader with the original caller identity, so every node must share one protected secret over TLS.

### Send a token

HTTP clients send the JWT in the standard header:

```http
Authorization: Bearer <token>
```

For `ledgerctl`, use a short-lived environment variable in automation:

```bash
export LEDGERCTL_AUTH_TOKEN="<token>"

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

An application using gRPC sends the same value in request metadata:

```go
md := metadata.Pairs("authorization", "Bearer "+token)
ctx := metadata.NewOutgoingContext(ctx, md)
```

## Create an Ed25519 machine credential

Operator-managed Ed25519 credentials are not available in this Stack v4 preview. In production, require Secret-backed private seeds, distribute only public keys to Ledger, cap the scopes each key may issue, and verify that every replica loaded the intended key set.

If a key entry in `auth-keys.json` sets `"god": true`, then tokens signed by that key receive every granular scope and the entry's `scopes` allowlist is ignored entirely. Capping scopes per key has no effect on such a key. Never set it on an application credential, and audit for it when reviewing a key set.

### Verify the direct server behavior

For a disposable direct deployment, generate a keypair and write its exact key ID into the server configuration:

```bash
set -euo pipefail

for file in ./payment-service-keys/seed.hex ./payment-service-keys/pubkey.hex; do
  test ! -e "$file" || {
    printf 'refusing to overwrite existing credential: %s\n' "$file" >&2
    exit 1
  }
done

KEY_OUTPUT="$(ledgerctl auth generate-key ./payment-service-keys)"
printf '%s\n' "$KEY_OUTPUT"

KEY_ID="$(awk '/^[[:space:]]*Key ID:/ { print $3; exit }' <<<"$KEY_OUTPUT")"
: "${KEY_ID:?ledgerctl did not return a key ID}"

jq -n \
  --arg keyId "$KEY_ID" \
  '{
    keys: [{
      keyId: $keyId,
      publicKeyFile: "./payment-service-keys/pubkey.hex",
      scopes: [
        "ledger:read",
        "ledger:TransactionWrite",
        "ledger:MetadataWrite"
      ]
    }]
  }' > auth-keys.json
```

Start Ledger with the public-key file in the first terminal. This command remains in the foreground:

```bash
mkdir -p ./payments/wal/node-1 ./payments/data/node-1

ledger run \
  --bootstrap \
  --node-id 1 \
  --cluster-id payments \
  --bind-addr 127.0.0.1:7777 \
  --grpc-port 8888 \
  --http-port 9000 \
  --wal-dir ./payments/wal/node-1 \
  --data-dir ./payments/data/node-1 \
  --tls-mode required \
  --tls-cert-file ./tls.crt \
  --tls-key-file ./tls.key \
  --auth-enabled \
  --auth-ed25519-keys ./auth-keys.json
```

In another terminal, read the same key ID from the configuration, mint a short-lived token, and call Ledger:

```bash
set -euo pipefail

KEY_ID="$(jq -er '.keys[0].keyId' auth-keys.json)"
TOKEN=$(ledgerctl auth generate-token \
  --signing-key ./payment-service-keys/seed.hex \
  --key-id "$KEY_ID" \
  --subject payment-service \
  --scopes ledger:read,ledger:TransactionWrite,ledger:MetadataWrite \
  --expiration 1h)

LEDGERCTL_AUTH_TOKEN="$TOKEN" ledgerctl \
  --server localhost:8888 \
  --tls-ca-cert ./ca.crt \
  --tls-server-name <a-SAN-on-the-server-certificate> \
  ledgers list
```

`--insecure` cannot reach this server, and it is mutually exclusive with both `--tls-ca-cert` and `--tls-server-name` in any case.

The list command must succeed. The scopes in the token must be a subset of the scopes attached to that key in `auth-keys.json`; Ledger rejects a token that claims additional permissions.

Protect `seed.hex` as a private key. Do not print it in CI logs or store it in source control. The public `pubkey.hex` can be distributed to Ledger replicas.

## Allow anonymous reads deliberately

Strict authentication is the default: a request without a token has no scopes. To test reads without a token while keeping writes authenticated in a direct deployment, add this server flag to the authentication configuration:

```bash
--auth-anonymous-scopes '*:read'
```

Operator-managed anonymous scopes are not available in this Stack v4 preview. Do not translate this direct-server flag into an undocumented Stack resource field.

This fallback applies only when the request has no bearer token.

| Request                                          | Expected result                                                        |
| ------------------------------------------------ | ---------------------------------------------------------------------- |
| Read with no token                               | Allowed by `*:read`                                                    |
| Read with an invalid or expired token            | `401 Unauthorized`                                                     |
| Read with a valid write-only token               | `403 Forbidden`; anonymous scopes are not merged into a valid identity |
| Write with no token                              | `401 Unauthorized`                                                     |
| Write with a valid token missing the write scope | `403 Forbidden`                                                        |

Use explicit granular scopes instead of `*:read` when only part of the read API should be public. For a direct server, pass them as a comma-separated value:

```bash
--auth-anonymous-scopes 'ledger:LedgerRead,ledger:TransactionRead'
```

The HTTP endpoints `/health`, `/livez`, `/readyz`, and `/_info` bypass authentication entirely. `/clusterz` carries no scope requirement, so it also answers a request that sends no token — but, unlike those four, it returns `401` if the request presents a malformed or expired one. The gRPC health service, `BucketService.Discovery`, and gRPC reflection are also unauthenticated.

## Verify the policy

Run these checks against the public HTTP endpoint before routing application traffic. Strict mode should produce `401`, `401`, `200`, and `403` in that order:

```bash
export LEDGER_URL=https://ledger.example.com
export READ_TOKEN="<valid-ledger-read-token>"

curl --silent --output /dev/null --write-out '%{http_code}\n' \
  "$LEDGER_URL/v3/"

curl --silent --output /dev/null --write-out '%{http_code}\n' \
  --header 'Authorization: Bearer not-a-valid-token' \
  "$LEDGER_URL/v3/"

curl --silent --output /dev/null --write-out '%{http_code}\n' \
  --header "Authorization: Bearer $READ_TOKEN" \
  "$LEDGER_URL/v3/"

curl --silent --output /dev/null --write-out '%{http_code}\n' \
  --request POST \
  --header "Authorization: Bearer $READ_TOKEN" \
  --header 'Content-Type: application/json' \
  --data '{not-valid-json' \
  "$LEDGER_URL/v3/authz-probe/transactions"
```

The final request targets a real transaction-write route but deliberately sends malformed JSON. Authorization runs before body parsing, so the read-only token must receive `403`. Even if the token unexpectedly has write access, body parsing returns `400` before Ledger can submit a mutation; this probe cannot create a ledger or transaction.

If anonymous reads are enabled, only the first expected status changes from `401` to `200`. The invalid-token request must still return `401`.

## Diagnose authorization failures

| Symptom                                               | Likely cause                                                                               | Check                                                                                                                                              |
| ----------------------------------------------------- | ------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------- |
| Node does not become ready after enabling OIDC        | Discovery URL or JWKS cannot be reached, or the issuer is invalid                          | Fetch the issuer's OpenID configuration from the Ledger network path and inspect node startup logs                                                 |
| `401 Unauthorized`                                    | Token is absent, malformed, expired, signed by an unknown key, or issued by another issuer | Decode the JWT header and claims; verify `kid`, `iss`, and `exp` without logging the token                                                         |
| `403 Forbidden`                                       | The token is valid but lacks the operation's required scope                                | Compare the requested operation with the token scopes and the configured scope mapping                                                             |
| Ed25519 token always returns `403`                    | The token uses `read` or `write` instead of a configured virtual or granular scope         | Use `ledger:read`, `ledger:write`, or an exact `ledger:<Resource><Action>` value                                                                   |
| One replica rejects a token after credential rotation | Its mounted public-key configuration has not converged                                     | Check the deployment rollout and test the same token through every reachable replica                                                               |
| Follower receives a write but the leader rejects it   | Internal TLS or the cluster secret is missing or inconsistent                              | Follow the forwarded-write checks in [TLS and Network Security](https://docs.formance.com/v4.0/modules/ledger/operations/tls-and-network-security) |

## Rotate an Ed25519 credential

Do not replace the only accepted key in one step. Use the release-specific Stack v4 workflow to register the replacement public key alongside the old one, with narrower or equal scopes. Wait until every replica accepts the new key, move clients to tokens signed by the new seed, and remove the old credential only after those tokens succeed through every reachable replica.

OIDC signing-key rotation remains owned by the identity provider. Keep the old key available in its JWKS until issued tokens have expired, and verify a token with the new `kid` before removing the old key.
