# Request and Response Signing

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

Stack: v4.0

Use request signing when you need evidence that a registered key approved the exact composition and order of an admission batch. Response signing places a signed copy of each response log in an embedded envelope. The current `ledgerctl` verification path authenticates that envelope, but it does not prove that the outer `Log` consumed by the command matches the signed copy.

Both mechanisms use Ed25519, but they use different keys and protect different directions. Request signing is available on the gRPC `Apply` path and on `ledgerctl` mutation commands that use that path. The HTTP API does not expose the signed protobuf envelope, and some current `ledgerctl` commands call unsigned unary RPCs instead.

## Keep the security layers separate

| Mechanism                                                                                 | Question it answers                                                                        | What it does not prove or replace                                                    |
| ----------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------ |
| [Authentication](https://docs.formance.com/v4.0/modules/ledger/operations/authentication) | Who is the caller, and which operations may it perform?                                    | TLS, payload approval, or replay protection                                          |
| [TLS](https://docs.formance.com/v4.0/modules/ledger/operations/tls-and-network-security)  | Is the connection encrypted, and is the peer certificate trusted?                          | User authorization or payload approval                                               |
| Request signature                                                                         | Did a registered private key approve these exact ordered mutations?                        | JWT scopes, TLS, or idempotency                                                      |
| Response signature                                                                        | Did the expected Ledger response key sign the bytes in this embedded `SignedLog` envelope? | Proof that the outer returned `Log` matches those bytes, or persistence of the proof |

Request signatures cover the serialized `ApplyBatch`, including its ordered requests and idempotency key. Ledger persists the signed batch proof once per batch on that batch's audit entry, and binds it into the audit hash chain, so the proof is tamper-evident and stays verifiable long after the call. Retrieve it through the audit API; it is not attached to individual logs. A signature alone does not prevent replay. A gRPC client can make a retry idempotent only by persisting the original idempotency key and resending the exact same batch.

For each log in an `ApplyResponse`, Ledger signs a serialized copy and places that copy in the outer log's `SignedLog` envelope. Ledger creates the envelope after consensus and does not persist it. Clients that need the envelope as evidence must retain the signed response.

`ledgerctl --response-verify-key` verifies the signature over `SignedLog.payload`, but the verification helper does not compare that payload with the separate outer `Log`. Commands such as `transactions create` then read data from the outer log. A successful command therefore authenticates the embedded envelope only. It does not establish that the transaction or other data displayed or consumed from the outer log is the data that Ledger signed. Do not use this check alone as a tamper-rejection guarantee. Until a released client binds the two representations and consumes the signed payload, rely on TLS and your established peer trust for the outer response.

## Bootstrap request signing

Request signing is optional until you explicitly require it. Plan the bootstrap as a controlled change:

1. restrict access to the cluster;
2. inventory every application, administrative command, and scheduled mutation against the compatibility table below;
3. complete or remove incompatible scheduled and background work — client-driven work only; the leader's own scheduled proposals are exempt;
4. register the first public key;
5. verify signed writes;
6. require signatures;
7. verify that an unsigned admission mutation fails;
8. when authentication is enabled, verify that a direct cluster-control RPC rejects a JWT without `ledger:ClusterWrite`;
9. reopen normal access.

### Check mutation compatibility

Mandatory request signing in the current 3.0 preview gates admission batches only. It rejects several public and internal paths that submit unsigned `Apply` requests, but it does not add signature checks to direct cluster-control RPCs. Enabling the policy without this preflight can stop configuration changes while other administrative mutations remain outside the signing policy.

| Mutation surface                                                                                                                                    | Behavior while signatures are mandatory                                                                                                                                                                             | Safe gate before enabling                                                                                                                                                                                                    |
| --------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| HTTP mutations                                                                                                                                      | Rejected because HTTP always creates an unsigned `ApplyRequest`                                                                                                                                                     | Move every writer to a tested signed gRPC `Apply` path                                                                                                                                                                       |
| Query-checkpoint create or delete through the unary gRPC methods used by `ledgerctl query-checkpoint`                                               | The server submits an unsigned mutation and rejects it                                                                                                                                                              | Finish checkpoint-based jobs and delete their checkpoints before enabling; see [Consistency and Checkpoints](https://docs.formance.com/v4.0/modules/ledger/querying/consistency-and-checkpoints#request-signing-limitations) |
| Scheduled query-checkpoint creation                                                                                                                 | Unaffected. The scheduler's proposal is leader-internal and exempt from the signature requirement, because admission returns early for a system actor before it reads `require_signatures`                          | None                                                                                                                                                                                                                         |
| Prepared-query create, update, or delete through HTTP or the unary gRPC methods used by `ledgerctl queries`                                         | Both direct mutation surfaces submit unsigned requests and are rejected                                                                                                                                             | Use the signed [configuration-as-code](https://docs.formance.com/v4.0/modules/ledger/operations/configuration-as-code) apply path or a version-pinned client that signs the exact `ApplyBatch`                               |
| Cluster membership changes, leadership transfer, primary or secondary compaction, primary-store checkpoint creation, and full or incremental backup | These direct cluster RPCs do not enter Admission and accept no request-signature envelope. `require_signatures` does not cover them; with authentication enabled, they require a JWT carrying `ledger:ClusterWrite` | Protect cluster administration credentials and network access, and test scope denial separately. Do not treat the signing policy as approval evidence for these operations                                                   |

Reads, including prepared-query execution and checkpoint-scoped reads, remain unsigned and continue to work. Direct cluster-control commands also remain outside request signing, even when the CLI receives `--signing-key` flags. Record the Ledger and `ledgerctl` versions used for this inventory; do not assume that a global signing flag changes a command whose implementation does not use `Apply`.

The first signing key can be registered without a **request signature** because no trusted signing key exists yet. It still requires a valid JWT and `ledger:OpsWrite` when authentication is enabled. Register the first key in a controlled maintenance window.

Generate the root keypair:

```bash
ROOT_KEY_DIR="./root-signing-key"
test ! -e "$ROOT_KEY_DIR" || {
  printf 'refusing to overwrite existing root key directory: %s\n' "$ROOT_KEY_DIR" >&2
  exit 1
}
ledgerctl signing generate-key "$ROOT_KEY_DIR"
```

Store `seed.hex` in your approved secret manager and verify that an authorized operator can recover it before registering the public key. After signatures become mandatory, losing or overwriting the only trusted root seed can prevent every future key-management mutation while its public-key registration remains present.

Register the public key. The unsigned bootstrap path is available whenever Ledger has no signing-key registrations:

```bash
ledgerctl signing register-key \
  --key-id root \
  --public-key-file ./root-signing-key/pubkey.hex
```

Create a ledger through a signed batch. The `--signing-key-id` must match the ID registered above:

```bash
ledgerctl \
  --signing-key ./root-signing-key/seed.hex \
  --signing-key-id root \
  ledgers create signing-smoke
```

List the registered keys and confirm that `root` has `(root)` as its parent:

```bash
ledgerctl signing list-keys
```

Once the signed write succeeds, require a valid request signature for admission mutation batches:

```bash
ledgerctl \
  --signing-key ./root-signing-key/seed.hex \
  --signing-key-id root \
  signing require true
```

Reads remain unsigned. Admission mutations must now provide a registered key ID and valid signature. The direct cluster-control RPCs listed above remain outside this policy and continue to depend on authentication and scope enforcement.

## Verify admission enforcement

An unsigned admission mutation must fail after `signing require true`:

```bash
ledgerctl ledgers create unsigned-must-fail
```

Ledger maps a missing required signature to gRPC `Unauthenticated`. A mutation signed with an unknown key ID, the wrong private key, or a modified payload fails with gRPC `PermissionDenied`.

The same mutation succeeds when the client provides the registered key:

```bash
ledgerctl \
  --signing-key ./root-signing-key/seed.hex \
  --signing-key-id root \
  ledgers create signed-write
```

If authentication is also enabled, repeat the test with a JWT that lacks `ledger:LedgerWrite`. A cryptographically valid request must still fail with `PermissionDenied`: signing approves the payload, while authorization decides whether the caller may execute it.

## Delegate with child keys

Register operational keys under the root instead of distributing the root seed. The key that signs a registration becomes the immutable parent of the new key.

```bash
APPLICATION_KEY_DIR="./application-signing-key"
test ! -e "$APPLICATION_KEY_DIR" || {
  printf 'refusing to overwrite existing application key directory: %s\n' "$APPLICATION_KEY_DIR" >&2
  exit 1
}
ledgerctl signing generate-key "$APPLICATION_KEY_DIR"

ledgerctl \
  --signing-key ./root-signing-key/seed.hex \
  --signing-key-id root \
  signing register-key \
  --key-id application \
  --public-key-file ./application-signing-key/pubkey.hex
```

Use the child key for application writes:

```bash
ledgerctl \
  --signing-key ./application-signing-key/seed.hex \
  --signing-key-id application \
  transactions create \
  --ledger signing-smoke \
  --posting "world,users:001,1000,USD/2"
```

List the hierarchy and verify that `application` reports `root` as its parent:

```bash
ledgerctl signing list-keys
```

## Revoke keys

Revoke one key without affecting its descendants:

```bash
ledgerctl \
  --signing-key ./root-signing-key/seed.hex \
  --signing-key-id root \
  signing revoke-key --key-id application
```

Use `--cascade` only when every descendant must stop signing immediately:

```bash
ledgerctl \
  --signing-key ./root-signing-key/seed.hex \
  --signing-key-id root \
  signing revoke-key --key-id compromised-team-key --cascade
```

After the command commits, retry a mutation with each affected key and confirm that Ledger rejects it. Key registration, revocation, and signing policy changes pass through Raft; consider the change complete only after the committed result is visible and the behavioral check fails as expected.

Cascade revocation follows the complete descendant tree. Do not register a replacement below a compromised key and then cascade-revoke that parent: the replacement will be revoked as well.

Revocation removes keys from the active registry; Ledger does not retain an inactive registry entry for them. The revocation remains in log and audit history. If a revocation or cascade removes the last registration, the unsigned first-key bootstrap path opens again even when `require_signatures` remains `true`. Before removing the last key, restrict access to the cluster and prepare a replacement public key. Register that replacement with a valid JWT carrying `ledger:OpsWrite` when authentication is enabled, verify a signed admission mutation, and confirm the new registration before reopening access.

## Enable response signing

Response signing uses one server seed supplied at startup. Generate a separate keypair; do not reuse a request-signing key:

```bash
RESPONSE_KEY_DIR="./response-signing-key"
test ! -e "$RESPONSE_KEY_DIR" || {
  printf 'refusing to overwrite existing response key directory: %s\n' "$RESPONSE_KEY_DIR" >&2
  exit 1
}
ledgerctl signing generate-key "$RESPONSE_KEY_DIR"
```

Operator-managed response signing is not available in this Stack v4 preview. Before clients require response verification, use a released workflow that mounts one protected seed on every replica and reports full convergence.

To verify the current server contract in a disposable direct deployment, add the seed path to every Ledger process and restart one member at a time:

```bash
--response-signing-key ./response-signing-key/seed.hex
```

This is a Ledger server flag, not a Stack v4 manifest field. Keep the seed out of command output and source control. Wait until every replica has restarted with the same key before requiring clients to verify signatures.

## Verify signed responses

Pass the response **public** key to `ledgerctl`. This example checks the embedded response envelope and signs the request when request signatures are mandatory:

```bash
ledgerctl \
  --signing-key ./root-signing-key/seed.hex \
  --signing-key-id root \
  --response-verify-key ./response-signing-key/pubkey.hex \
  transactions create \
  --ledger signing-smoke \
  --posting "world,response:probe,1,TEST"
```

The command fails if any outer log has no embedded response signature, or if that envelope carries a malformed signature or fails verification with the supplied public key. As described above, this check does not compare the signed payload with the outer log that the command consumes.

SDKs can retrieve the current server public key through the unauthenticated Discovery RPC:

```bash
grpcurl \
  -cacert ./ca.crt \
  ledger-payments.formance.svc.cluster.local:8888 \
  ledger.BucketService/Discovery
```

Pin the discovered key according to your trust policy. Discovery transports the key; it does not by itself establish that a newly observed key is authorized.

## Rotate signing keys

### Request keys

Register the replacement as a child of a still-valid key, deploy the new private seed to its client, and verify a signed mutation. Revoke the old key without `--cascade` only after all intended descendants have been reviewed. Keep the JWT credential rotation separate; a request-signing key does not mint client permissions.

### Response key

Response signing accepts one server key at a time. Distribute and trust the new public key before updating the Kubernetes Secret and rolling Ledger nodes. During the rollout, clients pinned to only one key cannot verify envelopes from both old and new replicas. Route clients that require envelope verification to a converged deployment or coordinate a client trust window that accepts both keys.

After convergence, run the envelope check through every reachable replica, then retire the old public key. This confirms that each replica uses the expected response key; it does not remove the current outer-log binding limitation.

## Recover from signing failures

| Symptom                                                          | Likely cause                                                                                                                                                           | Recovery                                                                                                                                                                                                                    |
| ---------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `missing signature` / `Unauthenticated`                          | Signatures are required but the mutation was unsigned                                                                                                                  | For a command documented as signing-capable, add `--signing-key` and the matching `--signing-key-id`; otherwise follow the owning page's compatibility guidance                                                             |
| `unknown key ID` / `PermissionDenied`                            | Client key ID differs from the registered ID, or the key was revoked                                                                                                   | Run `signing list-keys`; correct the ID or register a replacement through a valid parent                                                                                                                                    |
| `invalid signature` / `PermissionDenied`                         | Wrong seed, modified payload, or corrupted signature                                                                                                                   | Stop retrying the modified batch; rebuild it from the intended inputs and sign once                                                                                                                                         |
| Signed request receives an authorization error                   | JWT is missing or lacks the operation's scope                                                                                                                          | Fix authentication and scopes; do not weaken signing policy                                                                                                                                                                 |
| `missing response signature`                                     | Client envelope verification is enabled before response signing has converged                                                                                          | Complete the deployment rollout and confirm that every replica returns an envelope signed by the expected key                                                                                                               |
| `response signature verification failed`                         | Client has the wrong public key or reached a replica using another response key                                                                                        | Compare Discovery output, the configured Secret, and rollout revision                                                                                                                                                       |
| Ambiguous timeout after a signed gRPC batch                      | The server may have committed the batch before the client lost the response                                                                                            | Reconcile the result; if it is still unknown, resend the persisted signed envelope byte for byte with the original idempotency key                                                                                          |
| Ambiguous timeout after a `ledgerctl` mutation                   | Only `ledgers create` and `indexes create` accept `--idempotency-key`; every other command, and those two without the flag, puts an empty idempotency key in the batch | If the command carried a key, rerun it unchanged with the same key. Otherwise read the affected state and audit or log evidence; do not rerun the CLI mutation blindly                                                      |
| No signing-key registrations remain                              | The last registration was removed by a revocation or cascade                                                                                                           | Keep the cluster isolated, register a new root through the unsigned bootstrap path using a valid JWT with `ledger:OpsWrite` when authentication is enabled, then verify a signed admission mutation before reopening access |
| Registrations remain, but no matching usable private key remains | The corresponding seeds were lost, destroyed, or made unusable                                                                                                         | Keep the cluster isolated and use the release-specific break-glass recovery procedure. Unsigned bootstrap remains closed while any registration exists                                                                      |

The gRPC retry rule applies only when the client retained the exact serialized batch or signed envelope. Rebuilding a protobuf message and changing its requests, ordering, or idempotency key creates a different operation. Current `ledgerctl` commands that use `BucketService` can automatically retry gRPC `Unavailable` failures within one invocation. `ledgers create` and `indexes create` sign the `--idempotency-key` value into the batch, so their retries, and a rerun of the same command with the same key while the key is retained, return the original outcome. Ledger compares the key with the batch's requests, not with its signature, so a rerun signs again and still matches. Every other command, and these two without the flag, sends an empty idempotency key, so a failed or timed-out command can have applied its mutation more than once. For those, reconcile the intended state and audit or log evidence even before considering a manual retry, and retry through the CLI only after you have proved that the intended state change did not commit and have accepted that the new call is not protected by a batch idempotency key.

To turn mandatory request signing off during a planned rollback, sign the policy change with a currently valid key:

```bash
ledgerctl \
  --signing-key ./root-signing-key/seed.hex \
  --signing-key-id root \
  signing require false
```

Record who approved the change and when unsigned mutations became possible again.
