# Middleware: onboarding a server

10-Nov-2026.

This is the walk for a vendor whose POS, or whose back office, runs on its own server and calls
the middleware host to host. It goes from the listing that gives the server its code to a certificate
the server renews by itself, with code to paste at each step. You can build the server's side
from this document alone. An agent reads the same bytes through `llms.txt`, and through the
sandbox's MCP server as `mw://onboarding/server`.

A live server proves who it is with a client certificate from the middleware's own CA. Its key is made
by the vendor, kept in the vendor's own custody, and never sent to the middleware: the middleware signs a
certificate for its public key once the server spends a pairing code its listing gave. A server
has no attestation, so the code is all that ties its first certificate to the vendor, and
whoever spends the code first holds the identity. The certificate lasts 30 days and renews from
day 15 with a new key.

Read it beside `docs/api/openapi.yaml`, which holds the schema of every route named here, the
back office's routes among them as the operations tagged `operator`. A vendor writing an app
for a SUNMI device reads `docs/api/onboarding-device.md` instead, and linking a register to a
terminal at the counter is `docs/api/linking.md`. Nothing here runs on a device, so none of the
device walk's bench items applies to a server.

## In short

1. The operator, or the vendor's own `admin` server, lists the server with the scope its
   certificate will reach, and the middleware answers once with a pairing code (step 1).
2. The server makes a P-256 key that stays in the vendor's custody (step 2) and a CSR for it
   (step 3), and spends the code at `POST /v1/enrol` (step 4).
3. It keeps the `CertificateChain` the middleware answers with beside the key, and presents both at
   the TLS handshake of every call after (step 5).
4. A `pos` server names the register it acts for in `Mw-Register` on each call for a
   register (step 6), and an `admin` server lists those registers (step 7).
5. Once a day it asks `GET /v1/certificates/self` (step 8). When `RenewNow` is `true`, one
   instance renews with a new key, and the new certificate is installed on every instance
   inside the overlap (step 9).
6. After a refusal it does what the holder's table says, and never deletes its key (step 10).

## In the sandbox

The same file is served in the sandbox, where three things differ.

- The sandbox's gate answers `404` to every route of the Operator API,
  `POST /v1/vendors/{VendorIdentification}/servers` and `POST /v1/registers` among them.
  In their place, the `201` of `POST /sandbox/v1/keys` holds `Enrolment`, a `pos` server's code
  for your world, and `POST /sandbox/v1/codes` gives another under your tester's key (step 1).
  The same `201` holds `RegisterIdentification`, your world's one register (step 7). Both
  routes are served by the sandbox's own process, `mw-sandbox`, and a `live` middleware has
  neither.
- Nothing a sandbox signs is a record, and a sandbox certificate is refused on `live`.
- Enrolment needs a sandbox with an issuing certificate. A sandbox run without one answers
  `POST /v1/enrol` with `503 ca_unavailable`.

## What you need

- OpenSSL 3 or later, for the key and the CSR. Any tool that makes a P-256 key and a PKCS 10
  request will do, and the commands here are OpenSSL's.
- `curl` built on OpenSSL, and `jq`, for the calls here. In the server itself, any HTTP client
  that can present a client certificate: step 5 gives one in Rust and one in Java.
- The middleware's base URL, one of those `/docs/api/environments.md` names, kept in a setting.
  The commands here read it from `$MW`, and the sandbox's from `$SANDBOX`.

```sh
# The middleware's base URL: /docs/api/environments.md names each environment's. A name under
# `.invalid` never resolves: put the real one here.
MW=https://mw.invalid
```

Every body the middleware takes or gives is one JSON object in UTF-8, and every refusal it gives
has the body `{ "Error": { "Code": "...", "Message": "...", "Fields": [] } }`. On enrolment, the
edge in front of a hosted middleware may also refuse, with a `429` of its own whose body is not
an `Error` (step 4, When enrolment is refused). Where a table here says the
normal backoff, wait 1 second, double the wait after each failure up to 30 seconds, and add a
little randomness.

## 1. The listing and the code

Every server starts with one human act. On `live`, the operator lists a vendor's first server,
and the vendor's own `admin` server may list more, with
`POST /v1/vendors/{VendorIdentification}/servers` and the `Scope` its certificate will reach
(in `docs/api/openapi.yaml`, tagged `operator`):

| `Scope` | What its certificate reaches |
|---|---|
| `pos` | Sales, their reads and the link routes, each for a register the call names in `Mw-Register` (step 6) |
| `admin` | The Operator API inside its own vendor: its registers (step 7), its servers and its app identities, and for a fleet vendor its stores and terminals |
| `operator` | The operator's alone |

Each listed server is its own identity, with its own code, key and certificate, so a vendor
that sells and lists its own registers holds a `pos` server and an `admin` server. Here the
vendor's `admin` server lists a `pos` one, presenting its own key and chain, `admin.key` and
`admin-chain.pem`, made and issued as steps 2 to 4 show:

```sh
curl -s -X POST "$MW/v1/vendors/ven_.../servers" \
  --cert admin-chain.pem --key admin.key \
  -H 'Content-Type: application/json' \
  -d '{"Scope":"pos"}'
```

The answer is `201`:

```json
{ "ServerIdentification": "srv_...", "Scope": "pos", "State": "listed", "PairingCode": "XXXX-XXXX-XXXX-XXXX" }
```

`ServerIdentification` is the server's id. `PairingCode` is 16 characters of Crockford base32 in
four groups of 4, valid 15 minutes and for one use, and shown this once. A device's code is five
words of `docs/api/words.txt` instead, and a server's stays these 16 characters
(`docs/api/onboarding-device.md`, step 2). The code is a secret: whoever listed the server gives
it to whoever runs the server, by a path no one else reads, and it is kept out of every log, the
server's own among them. A code that lapses unspent is not renewed:
remove the listed server with
`DELETE /v1/vendors/{VendorIdentification}/servers/{ServerIdentification}`, and list a new one.

A vendor holds at most two servers of one scope that are not removed, and a third is
`409 too_many_keys`. So a server moves to a new identity with no gap: list the second, enrol
it, move every call to it, then remove the first.

In the sandbox the listing is done for you. The `201` of `POST /sandbox/v1/keys` holds
`Enrolment`, a `pos` server's code for your world, good 15 minutes. After that,
`POST /sandbox/v1/codes` gives a fresh one, under your tester's key:

```sh
curl -s -X POST "$SANDBOX/sandbox/v1/codes" \
  -H 'Authorization: Bearer sbx_...' \
  -H 'Content-Type: application/json' \
  -d '{"Role":"server"}'
```

The answer is `201`, with `PairingCode` and `Next`. A server sends no serial, so enrol with that
code alone, within 15 minutes. The code lists a `pos` server on your world's vendor, or is a
fresh code for one already listed and not yet enrolled, and disturbs nothing else in your world.
Past 6 codes an hour the route answers `429 sandbox_rate`.

## 2. The key, in your own custody

The server's key is P-256, made by you and kept by you. The middleware never sees it, and nothing is
given to you to embed. The middleware takes a P-256 key alone: a CSR for any other key is refused
`400 invalid_field`. Make a new key for each enrolment and each renewal, because a key this
server has used before is refused at renewal.

```sh
umask 077
openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out server.key
```

Keep the SHA-256 of its public key beside it. It is what the middleware shows as the server's
`SpkiDigest` once the key holds a certificate, so you can tell your own enrolment from someone
else's (step 4):

```sh
openssl pkey -in server.key -pubout -outform DER | sha256sum
```

The key is the server's identity. A key on a server's disk can be copied, and a copy renews
exactly as you can, so a copy outlives any one certificate's 30 days. Keep the file readable by
the server's own user alone, or in a secret store or a hardware module where your TLS stack can
sign through one, out of every image and log, and on no more hosts than run the server. The
surest sign of a copy is that one of the two holders is refused `403 certificate_retired` within
an hour of the other's renewal (step 10, and A copied key, below).

## 3. The CSR

The middleware reads one thing from the CSR: its public key. It checks the CSR's own signature and that
the key is P-256, and writes every name in the certificate itself, so the subject says nothing
and holds no one's name. The CSR is never logged: the middleware's log holds its key's SHA-256 alone.

```sh
openssl req -new -key server.key -subj '/CN=server' -sha256 -out server.csr
```

A CSR whose signature does not verify, or whose key is not P-256, is refused
`400 invalid_field`, with `Fields` naming `CertificateSigningRequest`.

## 4. Enrol: `POST /v1/enrol`

With the code and the CSR, the server enrols. The call carries no credential, because the code
is the credential, so it presents no certificate and sends no `Authorization` header.

| Field | Holds |
|---|---|
| `PairingCode` | The code, as the listing showed it. Spaces and hyphens are dropped, and either case is read |
| `CertificateSigningRequest` | The CSR, PEM (step 3) |

A server sends nothing else. `SerialNumber` and `AttestationChain` are a device's. A
`SerialNumber` that is not `null` reads the code as a device's five words, which a server's 16
characters are not, so the body is refused `400 invalid_field` naming `PairingCode`, before the
code is looked up. An `AttestationChain` from a server is refused `400 unknown_field`.

```bash
# The code is a secret: read it, so it stays out of the shell's history.
read -r -s -p 'Pairing code: ' CODE; echo
status=$(jq -n --arg code "$CODE" --rawfile csr server.csr \
    '{PairingCode: $code, CertificateSigningRequest: $csr}' \
  | curl -s -X POST "$MW/v1/enrol" \
      -H 'Content-Type: application/json' \
      --data-binary @- \
      -o enrolled.json -w '%{http_code}')
case "$status" in
  200|201) jq -r .CertificateChain enrolled.json > chain.pem ;;
  *) echo "not enrolled: HTTP $status, Error.Code in enrolled.json" >&2 ;;
esac
```

The answer is `201`:

```json
{ "CertificateChain": "-----BEGIN CERTIFICATE-----\n...", "ServerIdentification": "srv_...", "SpiffeId": "spiffe://.../live/server/srv_...", "NotAfter": "...", "RenewFrom": "..." }
```

`CertificateChain` is two certificates, PEM: the server's own, then the issuing certificate.
Keep it beside the key, in `chain.pem`: a certificate is public, and this one belongs to that
key alone. The server is now `enrolled`. `NotAfter` is when the certificate ends, 30 days on,
and `RenewFrom` is day 15.

`SpiffeId` is the certificate's URI. Its host is the trust domain of the deployment that issued
it, which need not be the address you call, and its first segment is the environment, `live` or
`sandbox`.

If an answer is lost, send the same body again inside the code's 15 minutes: the same code and
the same key answer `200` with the certificate already issued. The same code with another key
is `403 code_not_valid`, so never make a new key to repeat a call that got no answer.

**An intercepted code is the one that wins.** A server has no attestation, so whoever spends a
code first holds the identity, and the real server is then refused `403 code_not_valid`. So
treat `code_not_valid` on a fresh code, one sent as listed and inside its 15 minutes, as an
alarm. Read the vendor's servers, and compare each row's `SpkiDigest` with your key's (step 2):

```sh
curl -s "$MW/v1/vendors/ven_.../servers" --cert admin-chain.pem --key admin.key \
  | jq '.Servers[] | {ServerIdentification, Scope, State, SpkiDigest, FirstSeen}'
```

A row `enrolled` with an `SpkiDigest` that is not your key's was spent by someone else. Remove
it with `DELETE /v1/vendors/{VendorIdentification}/servers/{ServerIdentification}`, which
retires its certificate at once, list a new server, and find how the code left your hands before
you hand over the next. A vendor with no `admin` server asks the operator to read the row.

### When enrolment is refused

A refusal once the code is found counts an attempt against it, unless the code is already spent
or burned, and five attempts burn it, so fix what a refusal names before you try again. A `503`
counts nothing and leaves the code unspent, and the edge's `429` never reaches the middleware, so
it counts nothing either.

Of `invalid_json`, `unknown_field`, `missing_field` and `invalid_field`, the first class that
fails answers alone, with `Fields` naming every field of it, sorted.

| Status | `Error.Code` | When | What to do |
|---|---|---|---|
| `400` | `invalid_json`, `unknown_field`, `missing_field` | The body is not a JSON object, holds a field the route does not name, or lacks one, and `Fields` names each. A server's body holding `AttestationChain` is `unknown_field` | A bug in the caller: fix it. Retrying will not help |
| `400` | `invalid_field` | A field breaks its rule, and `Fields` names it. For `CertificateSigningRequest`: its signature does not verify, or its key is not P-256. For `PairingCode`: it is not 16 characters, or the body holds a `SerialNumber`, which reads the code as a device's five words | For the CSR, make a new P-256 key and a CSR from it (steps 2 and 3), and enrol again inside the 15 minutes. For the code, send it as listed, with no `SerialNumber` |
| `403` | `code_not_valid` | The code is wrong, unknown, expired, spent or burned, the server is not `listed`, or its vendor is suspended. One answer for every reason, so the route tells a stranger nothing | On a fresh code, an alarm: read `GET /v1/vendors/{VendorIdentification}/servers`, where a row whose `SpkiDigest` is not your key's was spent by someone else. Otherwise check the code as listed, then ask for a new listing |
| `429` | None: the body is the edge's own, not an `Error` | Sent by the edge in front of a hosted middleware, never by the middleware itself: more enrolments came from this address in a minute than the edge allows. The code was not read, and no attempt is counted against it | Wait a minute, then try again with the same body. Do not read the body as an `Error` |
| `503` | `ca_unavailable` | The middleware could not sign | Back off and try again with the same body. The code is not spent |
| `503` | `store_unavailable` | The middleware's store did not answer | Back off and try again with the same body |

## 5. Present the certificate on every call

Every call after enrolment presents the certificate at the TLS handshake: the key, and the whole
chain the `201` gave, the server's certificate with the issuing certificate beside it. The middleware
reads who is calling from that alone. Send no `Authorization` header on a call that presents a
certificate: the two together are refused `401 certificate_invalid`.

With `curl` built on OpenSSL, `--cert` names the chain and `--key` the key, and every
certificate in the chain's file is sent:

```sh
curl -s "$MW/v1/certificates/self" --cert chain.pem --key server.key
```

In Rust, with `reqwest` 0.13 and its default features, which take `rustls`, the key and the
chain go into one `Identity`:

```rust
// Cargo.toml: reqwest = "0.13", tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
use std::error::Error;

/// A client presenting `key` with `chain`, the `CertificateChain` the middleware issued for it, both
/// PEM. Build a new one for a new certificate: a client keeps its connections, and each stands
/// on the certificate it was opened with.
fn client(key: &[u8], chain: &[u8]) -> Result<reqwest::Client, reqwest::Error> {
    let mut pem = key.to_vec();
    pem.extend_from_slice(chain);
    let identity = reqwest::Identity::from_pem(&pem)?;
    reqwest::Client::builder().identity(identity).build()
}

#[tokio::main]
async fn main() -> Result<(), Box<dyn Error>> {
    // The middleware's base URL, from the setting `MW`: one of those `/docs/api/environments.md`
    // names, and never written into code.
    let mw = std::env::var("MW").map_err(|error| {
        format!("MW: {error}. /docs/api/environments.md names each environment's base URL")
    })?;
    let client = client(&std::fs::read("server.key")?, &std::fs::read("chain.pem")?)?;
    let answer = client
        .get(format!("{mw}/v1/certificates/self"))
        .send()
        .await?;
    println!("{} {}", answer.status(), answer.text().await?);
    Ok(())
}
```

`Identity::from_pem` reads a key in PKCS 8, which `openssl genpkey` writes, or in SEC1, and
the certificates beside it. It refuses a file that also holds a block of another kind it
knows, such as a `PUBLIC KEY`, a `CERTIFICATE REQUEST` or an `X509 CRL`, and passes over a
block whose label it does not know, such as the `EC PARAMETERS` some tools write beside a key.
Give it the key and the chain and nothing else.

In Java, the key and the chain go into a PKCS 12 file, and a `KeyManagerFactory` gives the key
to the `SSLContext` of the JDK's own `HttpClient`. Make the file once for each certificate,
with a password of your own in `P12_PASSWORD`:

```sh
openssl pkcs12 -export -inkey server.key -in chain.pem -out server.p12 -passout env:P12_PASSWORD
```

```java
import java.io.InputStream;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.KeyStore;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;

public final class MwClient {
    /**
     * A client presenting the key and the chain in the PKCS 12 file at {@code p12}. Build a new
     * one for a new certificate: a client keeps its connections, and each stands on the
     * certificate it was opened with.
     */
    static HttpClient client(Path p12, char[] password) throws Exception {
        KeyStore keys = KeyStore.getInstance("PKCS12");
        try (InputStream in = Files.newInputStream(p12)) {
            keys.load(in, password);
        }
        KeyManagerFactory managers =
                KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
        managers.init(keys, password);
        SSLContext tls = SSLContext.getInstance("TLS");
        tls.init(managers.getKeyManagers(), null, null);
        return HttpClient.newBuilder().sslContext(tls).build();
    }

    public static void main(String[] args) throws Exception {
        // The middleware's base URL, from the setting MW: one of those
        // /docs/api/environments.md names, and never written into code.
        String mw = System.getenv("MW");
        if (mw == null) {
            throw new IllegalStateException(
                    "MW is not set: /docs/api/environments.md names each environment's base URL");
        }
        char[] password = System.getenv("P12_PASSWORD").toCharArray();
        HttpClient client = client(Path.of("server.p12"), password);
        HttpRequest self =
                HttpRequest.newBuilder(URI.create(mw + "/v1/certificates/self")).build();
        HttpResponse<String> answer = client.send(self, HttpResponse.BodyHandlers.ofString());
        System.out.println(answer.statusCode() + " " + answer.body());
    }
}
```

Build one client for each certificate, and use it for every call while that certificate is in
use. Never change which key one client presents: a client keeps its connections and its TLS
sessions, and a resumed session stands on the certificate of the handshake it resumes, so a new
certificate goes with a new client (step 9).

## 6. Name the register: `Mw-Register`

A `pos` server's certificate names its vendor, not a register. So each call a `pos` server makes
for a register names that register in the request header `Mw-Register`, by its
`RegisterIdentification` (step 7), exactly once. The routes that need one are a register's:

- `POST /v1/sales` and `GET /v1/sales/{TransactionReference}`.
- `POST /v1/links`, `GET /v1/links/{LinkIdentification}`,
  `POST /v1/links/{LinkIdentification}/word`, `DELETE /v1/links/{POIIdentification}` and
  `GET /v1/register/terminals` (`docs/api/linking.md`).

```sh
curl -s "$MW/v1/register/terminals" \
  --cert chain.pem --key server.key \
  -H 'Mw-Register: reg_...'
```

On those routes, a `Mw-Register` absent, sent twice, naming a register that is not this
vendor's, or naming a register of `Kind` `device` is refused `403 not_permitted`. A device's
register holds its own certificate, so a server cannot speak for one. An `admin` server names
no register, and the certificate routes take none.

A sale is its register's own: its `IdempotencyKey` is unique within the register, and a read
finds only the register's own sales. So a retry of a sale names the same register as the first
send did, or it makes a second sale. Give each till its own register, and never send two tills'
sales under one.

## 7. List a server's register: `POST /v1/registers`

A register is one till of the POS, and a `pos` server acts for each of its vendor's registers. A
POS vendor's `admin` lists each one with `POST /v1/registers` and an empty body, here on the
`admin` server's certificate:

```sh
curl -s -X POST "$MW/v1/registers" \
  --cert admin-chain.pem --key admin.key \
  -H 'Content-Type: application/json' \
  -d '{}'
```

The answer is `201`:

```json
{ "RegisterIdentification": "reg_...", "Kind": "server", "State": "active" }
```

`RegisterIdentification` is the register's id, the one `Mw-Register` names
(step 6). A server's register needs no code: it starts `active`, and holds no certificate of its
own, because the `pos` server speaks for it. It sits at no store and reaches no terminal until
it links to one at the counter (`docs/api/linking.md`). A body naming a `SerialNumber` lists a
device's register instead, which enrols as a device does (`docs/api/onboarding-device.md`).

`GET /v1/registers` shows each of the vendor's registers with its kind, its state and the
store it sits at. `DELETE /v1/registers/{RegisterIdentification}` removes one, and ends
each of its bindings.

In the sandbox the gate answers `404` to this route. Your world's one register is the
`RegisterIdentification` that `POST /sandbox/v1/keys` answered, a server's register already
bound to your world's terminals, and your `pos` server names it in `Mw-Register`.

## 8. The daily check: `GET /v1/certificates/self`

Once a day the server sends `GET /v1/certificates/self`, on its own certificate. The middleware answers
when the certificate ends, and whether to renew:

```json
{ "NotAfter": "...", "RenewFrom": "...", "RenewNow": true }
```

Renew when `RenewNow` is `true`, and not before. The middleware decides, so the server's clock does not
matter. `RenewNow` reads `true` only on the newest certificate of the identity in use, from
`RenewFrom` on, and `false` on a certificate that is retired.

```sh
curl -s "$MW/v1/certificates/self" --cert chain.pem --key server.key | jq -r .RenewNow
```

Any instance may run the check, and only the one that renews acts on `RenewNow` (step 9). A
refusal of the check is read by the holder's table (step 10).

## 9. Renew, with one renewer per identity

A certificate renews from day 15, always with a new key, on the server's own certificate. A
server skips the challenge a device asks first: `POST /v1/certificates/challenge` is a device's,
and a server asking it is refused `403 not_permitted`.

1. Make a new P-256 key (step 2) and a CSR for it (step 3).
2. Send `POST /v1/certificates/renew` with `CertificateSigningRequest` alone, on the current
   certificate. A server sends no `AttestationChain`, which is refused `400 unknown_field`. The
   `201` is enrolment's. If an answer is lost, send the same body again: a CSR whose key the middleware
   last issued for, and whose certificate is not yet used, answers `200` with that certificate.
3. Install the new key and chain on every instance that presents this identity, and use them
   from each instance's next connection, on a new client (step 5).
4. Once a call on the new certificate has been answered, it is current. Only then delete the
   old key.

The old certificate stays good until the new one is first used, by any instance, and for an
hour after by default, `MW_CERT_OVERLAP_SECS`. That hour is the overlap. Past it, a call on the old
certificate is refused `403 certificate_retired`. So every instance moves to the new certificate
inside the overlap, and one that has not is refused, and reads that refusal by the holder's
table (step 10).

**One renewer per identity.** A vendor running several instances of a server on one identity
lets one instance renew, and installs the new certificate on all of them inside the overlap. If
two instances renew, the second CSR retires the certificate the first was issued, where no one
has used it yet, and the middleware warns the operator, as the sign of a copied key. Where it has been
used, the second is refused `403 certificate_retired`. Past 5 certificates
for one identity in 24 hours, the middleware refuses `429 renewal_rate`. So name the renewer by
configuration, not by a race, and have the others read the new key and chain from where it puts
them, well inside the hour.

The renewer's daily run:

```bash
#!/bin/bash
# The renewer's daily run, on one instance of this identity and on no other.
set -euo pipefail
umask 077

renew_now=$(curl -sf "$MW/v1/certificates/self" --cert chain.pem --key server.key \
  | jq -r .RenewNow)
[ "$renew_now" = true ] || exit 0

# A renewal that got no answer is sent again with the same key, and the middleware answers with what
# it issued.
if [ ! -f next.key ]; then
  openssl genpkey -algorithm EC -pkeyopt ec_paramgen_curve:P-256 -out next.key
  openssl req -new -key next.key -subj '/CN=server' -sha256 -out next.csr
fi
status=$(jq -n --rawfile csr next.csr '{CertificateSigningRequest: $csr}' \
  | curl -s -X POST "$MW/v1/certificates/renew" \
      --cert chain.pem --key server.key \
      -H 'Content-Type: application/json' \
      --data-binary @- \
      -o renewed.json -w '%{http_code}')
case "$status" in
  200|201) jq -r .CertificateChain renewed.json > next-chain.pem ;;
  *) echo "not renewed: HTTP $status, Error.Code in renewed.json" >&2; exit 1 ;;
esac
# Put next.key and next-chain.pem where every instance of this identity reads them.
```

Each instance, once the new key and chain have reached it:

```bash
#!/bin/bash
# The first use of the new certificate. The old key goes only once the middleware answers on the new.
set -euo pipefail
if curl -sf "$MW/v1/certificates/self" --cert next-chain.pem --key next.key > /dev/null; then
  mv next-chain.pem chain.pem
  mv next.key server.key
  rm -f next.csr renewed.json
  # Build the server's HTTP client again from server.key and chain.pem (step 5).
fi
```

If the first call on the new certificate gets no answer, go on with the old one, which is good
until then, and try the new one again later.

### When renewal is refused

A refusal of a renewal leaves the current certificate as it was.

Of `invalid_json`, `unknown_field`, `missing_field` and `invalid_field`, the first class that
fails answers alone, with `Fields` naming every field of it, sorted.

| Status | `Error.Code` | When | What to do |
|---|---|---|---|
| `409` | `renewal_not_due` | Before `RenewFrom` | Wait: renew when the daily check's `RenewNow` is `true` |
| `400` | `invalid_field` | The CSR's signature does not verify, its key is not P-256, or its key was used before | Make a new P-256 key and a CSR from it, and send that |
| `400` | `unknown_field` | The body holds `AttestationChain`, which is a device's | Send `CertificateSigningRequest` alone |
| `429` | `renewal_rate` | 5 certificates for this identity in 24 hours | Back off, and try again tomorrow. A second renewer, or a copy of the key, is the likeliest cause: find it |
| `403` | `not_permitted` | The server is removed, or its vendor is not `active` | Back off to one hour. The certificate was good and the row refused it |
| `403` | `certificate_retired` | The certificate presented is retired | Renew on the newer certificate if this instance holds one. On its newest, stop and tell a person: something else holds a newer certificate of this identity |
| `401` | `certificate_expired` | The certificate is past its `NotAfter` | It cannot renew: the server needs a new code, by a new listing (step 1) |
| `503` | `ca_unavailable`, `store_unavailable`, `edge_not_trusted` | The middleware could not sign, its store did not answer, or the request did not come through a trusted edge | Back off and try again with the same body |

## 10. What a holder of a dead certificate does

A server holding a certificate is its holder, and so is each instance presenting it. A refusal
at the TLS handshake, or of a call, is read by this table, which is `docs/api/terminal.md`'s for
a server.

| What the server sees | What it does next |
|---|---|
| A close, a reset, a timeout, or any failure with no TLS alert | The normal backoff. It says nothing about a certificate |
| A TLS alert naming the certificate: `certificate_expired`, `bad_certificate`, `certificate_unknown`, `unknown_ca` or `decrypt_error`. Only where the middleware ends TLS itself | Back off an hour. After three, an hour apart, tell a person the server needs a new code, by a new listing (step 1), and keep trying hourly |
| `401 certificate_expired` or `401 certificate_invalid` | Back off an hour. After three, an hour apart, tell a person the server needs a new code, and keep trying hourly. `certificate_invalid` is also a certificate sent with an `Authorization` header: send the certificate alone |
| `401 certificate_required` | A client's own bug, or a route it has no certificate for: enrol first |
| `403 certificate_retired`, holding a newer certificate than the one presented | An instance the renewal reached late. Drop that connection and retry on the newer one, with the same idempotency key where the request carried one |
| `403 certificate_retired` on its newest certificate, with no newer one where the renewer puts it | Stop, keep any outcome, and tell a person: another holder of this identity holds a newer certificate, a second renewer or a copy of the key |
| `403 not_permitted` | Back off to one hour, keeping any outcome. The certificate was good and the row refused it: the server was removed, its vendor suspended, or on a register's route its `Mw-Register` names no register of the vendor's own |
| `429`, `503`, `edge_not_trusted` among them | The normal backoff. `503 edge_not_trusted` is an edge fault, and the server's certificate is not in question |

A TLS alert comes only where the middleware ends TLS itself. Behind the middleware's load balancer no
handshake fails on a client certificate, and the refusal comes as a `401` or a `403` instead.

**A server never deletes its key or its certificate on a refusal, any of those above.** A
server can recover from a mistake of the middleware's by a fix on the middleware's side, and a key deleted
cannot be recovered. A server holding a certificate makes a new key only to renew, or when a
person brings a new code, and deletes an old key only once a call on the certificate that
follows it has been answered. A server decides none of this by its own clock.

## A copied key

Three things say that someone else holds this identity's key or spent its code:
`403 certificate_retired` on a newest certificate, a `429 renewal_rate` no renewer of yours
caused, and an `SpkiDigest` you do not know in `GET /v1/vendors/{VendorIdentification}/servers`.
Only
one holder can stay. The operator, or the vendor's own `admin`, removes the server with
`DELETE /v1/vendors/{VendorIdentification}/servers/{ServerIdentification}`, which retires every
certificate of it, the copy's with yours. Then list a new server (step 1), enrol it with a new
key, and find how the key left your custody before the new one takes its place.
