# Mutual TLS

Canonical page: https://docs.ovok.com/signals/standalone/mtls

Learn how to require a client certificate on calls to the Signals API, on top of your credentials. Mutual TLS means the client proves who it is with a certificate, as the server does with its own. Ovok never holds your private key.

It guards every call to `/v1/signals/api/*` of your project's own Signals tenant. Hosts and routes do not change. With it on, Signals also presents its own client certificate on every webhook to your endpoints: see [Webhooks over mutual TLS](#webhooks-over-mutual-tls).

## Turn it on [#turn-it-on]

Save [`SIGNALS_MTLS_ENABLED`](/signals/with-ovok/settings#signals_mtls_enabled) on, in the Console under Signals › Settings or through the project settings API. Register a certificate first: without one the save answers `409` `SETTING_NOT_AVAILABLE`. Saving it on while any Signals webhook subscriber still has an http URL answers `409` `WEBHOOKS_NOT_HTTPS` and names each such subscriber, because Signals presents its client certificate over https only and would drop their events: move them to https, or delete them, first. Saving it off removes the requirement and keeps your certificates.

<Recording name="signals-mtls-turn-on" alt="Turning mutual TLS on in the Console's Signals Settings tab and downloading the certificate and key" />

| Setting | Certificate on the request | Answer |
| --- | --- | --- |
| Off | Any | The call is handled as usual. |
| On | None | `403` [`SIGNALS_MTLS_REQUIRED`](/errors/signals-mtls-required) |
| On | Not registered for the project, or expired | `403` [`SIGNALS_MTLS_CERTIFICATE_UNKNOWN`](/errors/signals-mtls-certificate-unknown) |
| On | Registered and valid | The call is handled as usual. |

`environment` in `GET /v1/signals/certs` says what the environment you call can do. `forwardsCertificates` must be `true` to turn the setting on; `issues` and `registers` say whether issuing and registering work. `caCertificate` is Ovok's CA, to verify Signals' webhook certificate against.

## Manage client certificates [#manage-client-certificates]

A project holds at most two certificates. In the Console, Signals › Settings issues one: your browser makes the key pair, sends Ovok only the signing request, and hands you the certificate and the key to download. The same is available over the API:

| Route | What it does |
| --- | --- |
| `GET /v1/signals/certs` | Lists the certificates (`sha256`, `serialNumber`, `subject`, `notAfter`, `registeredAt`) and the `environment`. |
| `POST /v1/signals/certs` | Registers a certificate you hold. Send its PEM as `certificate`. It must be valid now, for client authentication, and issued by a CA Ovok trusts. |
| `POST /v1/signals/certs/issue` | Issues a certificate from a CSR you send as PEM in `csr`, and registers it. The key is EC on P-256 or P-384, or RSA of at least 2048 bits. |
| `DELETE /v1/signals/certs/:sha256` | Removes a certificate by its SHA-256 fingerprint. Calls presenting it are refused at once. |

- **Who may call them.** A project admin's bearer token, from a Practitioner session. A client application's credential answers `403`, so it can't mint itself a certificate.
- **Issued certificates last six months.** Ovok's CA signs a client-authentication certificate valid for six months, or until the CA itself expires if that comes first. The subject is `CN=<tenant id>`. Nothing else in the CSR is kept.
- **A certificate past `notAfter`** stays listed until you remove it, but calls presenting it are refused.

```bash
curl --request POST 'https://api.sandbox.ovok.com/v1/signals/certs/issue' \
  --header "Authorization: Bearer ${OVOK_TOKEN}" \
  --header 'Content-Type: application/json' \
  --data "{\"csr\": $(jq -Rs . < client.csr)}"
```

| Status | Code | Cause |
| --- | --- | --- |
| `409` | `SIGNALS_TENANT_NOT_OWN` | The project has no Signals tenant of its own. |
| `409` | `CERTIFICATE_ALREADY_REGISTERED` | That certificate is registered already. |
| `409` | `CERTIFICATE_LIMIT_REACHED` | The project holds two. Remove one first. |
| `422` | `CERTIFICATE_NOT_ACCEPTED` | Not a PEM certificate, a CA certificate, not valid now, not for client authentication, or from a CA Ovok doesn't trust. |
| `422` | `CSR_NOT_ACCEPTED` | Not a PEM CSR, a signature that does not verify, an unsupported key, or an EC key that spells out its curve: make it with `-pkeyopt ec_param_enc:named_curve`. |
| `404` | `CERTIFICATE_NOT_FOUND` | No certificate with that fingerprint. |
| `501` | `FEATURE_NOT_CONFIGURED` | The environment has no CA to register against or issue from. |

## Present the certificate [#present-the-certificate]

Send the certificate and its key on every call to `/v1/signals/api/*`. Your credentials don't change: the certificate is checked on top of them.

<Tabs items={["curl", "Node.js", "Python", "Java"]} groupId="language" persist>
<Tab value="curl">

```bash
curl --get 'https://api.sandbox.ovok.com/v1/signals/api/alert' \
  --cert client.crt --key client.key \
  --user "${OVOK_MANAGER_ID}:${OVOK_MANAGER_SECRET}"
```

</Tab>
<Tab value="Node.js">

```ts title="signals-client.ts"
import { readFileSync } from 'node:fs';
import { Agent, fetch } from 'undici';

const dispatcher = new Agent({
  connect: { cert: readFileSync('client.crt'), key: readFileSync('client.key') },
});

const response = await fetch('https://api.sandbox.ovok.com/v1/signals/api/alert', {
  dispatcher,
  headers: { Authorization: `Bearer ${process.env.OVOK_TOKEN}` },
});
```

Use `fetch` from `undici` together with its `Agent`: Node's built-in `fetch` refuses an `Agent` from the `undici` package.

</Tab>
<Tab value="Python">

```python title="signals_client.py"
import os
import requests

response = requests.get(
    "https://api.sandbox.ovok.com/v1/signals/api/alert",
    cert=("client.crt", "client.key"),
    auth=(os.environ["OVOK_MANAGER_ID"], os.environ["OVOK_MANAGER_SECRET"]),
)
```

</Tab>
<Tab value="Java">

Bundle the certificate and key once: `openssl pkcs12 -export -in client.crt -inkey client.key -out client.p12`.

```java title="SignalsClient.java"
char[] password = System.getenv("CLIENT_P12_PASSWORD").toCharArray();
KeyStore keyStore = KeyStore.getInstance("PKCS12");
try (InputStream in = new FileInputStream("client.p12")) {
  keyStore.load(in, password);
}
KeyManagerFactory keys = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
keys.init(keyStore, password);
SSLContext tls = SSLContext.getInstance("TLS");
tls.init(keys.getKeyManagers(), null, null);

HttpClient client = HttpClient.newBuilder().sslContext(tls).build();
HttpRequest request = HttpRequest.newBuilder(URI.create("https://api.sandbox.ovok.com/v1/signals/api/alert"))
    .header("Authorization", "Bearer " + System.getenv("OVOK_TOKEN"))
    .build();
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
```

</Tab>
</Tabs>

A proxy that ends TLS in front of your client drops the certificate: connect to the API host directly.

## Webhooks over mutual TLS [#webhooks-over-mutual-tls]

With `SIGNALS_MTLS_ENABLED` on, Signals presents its own client certificate on every webhook it delivers to your subscribers, which must be `https` endpoints. With it off, deliveries carry no client certificate.

| Field | Value |
| --- | --- |
| Subject | `O=Ovok, CN=signals` |
| Subject alternative name | `urn:ovok:signals:<environment>` |
| Usage | Client authentication only |
| Issuer | Ovok's CA: `environment.caCertificate` in `GET /v1/signals/certs`, or **Download Ovok's CA** in the Console under Signals › Settings |

To accept deliveries from Signals only:

1. Ask for a client certificate on your webhook endpoint and verify it against Ovok's CA.
2. Accept only the subject alternative name `urn:ovok:signals:<environment>`. Your project's own client certificates chain to the same CA, so the CA alone is not enough.
3. Keep [verifying the signature](/signals/standalone/verify-webhooks). The certificate proves who sent the delivery; the signature proves its body.

Signals' certificate is renewed every year with the same name and CA, so pin those rather than its fingerprint.

```ts title="webhook-receiver.ts"
import { readFileSync } from 'node:fs';
import { createServer } from 'node:https';
import type { TLSSocket } from 'node:tls';

const signalsName = `URI:${process.env.SIGNALS_WEBHOOK_NAME}`;

createServer(
  {
    key: readFileSync('server.key'),
    cert: readFileSync('server.crt'),
    ca: readFileSync('ovok-signals-ca.pem'),
    requestCert: true,
    rejectUnauthorized: true,
  },
  (req, res) => {
    const sender = (req.socket as TLSSocket).getPeerCertificate();
    if (sender.subjectaltname !== signalsName) {
      res.writeHead(403).end();
      return;
    }
    handleSignedDelivery(req, res);
  },
).listen(443);
```

`handleSignedDelivery` is your signature check and handler from [Verify webhooks](/signals/standalone/verify-webhooks). Behind a load balancer that ends TLS, require the client certificate there and check the name in your app from the certificate it forwards.

## Rotate without downtime [#rotate-without-downtime]

Two certificates may be registered at once, so a rotation needs no gap.

1. Issue or register the new certificate.
2. Move your clients to it.
3. Remove the old one by its `sha256`. Calls presenting it are refused at once.

## See also [#see-also]

- [Signals settings](/signals/with-ovok/settings#signals_mtls_enabled)
- [Get started](/signals/standalone/get-started)
- [Signals standalone](/signals/standalone): app types, patient access and errors
