# Webhooks

How Ladon delivers alerts to your endpoint, how to check the signature, and how Ladon reacts to your answers. Ladon follows the [Standard Webhooks](https://www.standardwebhooks.com/) specification, so its libraries work out of the box.

## The request

Every message is a `POST` with a JSON body. The body is described in [Events and payloads](https://ladon.hackindex.io/docs/events.md).

| Header              | Value                                                                   |
| ------------------- | ----------------------------------------------------------------------- |
| `Content-Type`      | `application/json`                                                      |
| `User-Agent`        | `HackIndex-Webhooks/1.0 (+https://ladon.hackindex.io/docs/webhooks)`                                                  |
| `webhook-id`        | Unique id of this message. Retries of the same message keep the same id |
| `webhook-timestamp` | Unix time in seconds when the message was signed                        |
| `webhook-signature` | One or more signatures, separated by spaces, each starting with `v1,`   |

## Checking the signature

Your secret starts with `whsec_`. To check a message:

1. Take the part after `whsec_` and base64-decode it. That is the key.
2. Build the string `{webhook-id}.{webhook-timestamp}.{body}`, using the raw body exactly as received.
3. Compute an HMAC-SHA256 of that string with the key, and base64-encode the result.
4. Compare it, in constant time, with each signature in `webhook-signature` after removing `v1,`. One match is enough.
5. Refuse the message when `webhook-timestamp` is more than 5 minutes away from your clock. That stops replays.

### PHP

```php
function ladonSignatureIsValid(string $secret, string $id, string $timestamp, string $body, string $header): bool
{
    if (abs(time() - (int) $timestamp) > 300) {
        return false;
    }

    $key = base64_decode(substr($secret, strlen('whsec_')));
    $expected = base64_encode(hash_hmac('sha256', "{$id}.{$timestamp}.{$body}", $key, true));

    foreach (explode(' ', $header) as $signature) {
        if (str_starts_with($signature, 'v1,') && hash_equals($expected, substr($signature, 3))) {
            return true;
        }
    }

    return false;
}
```

### Node.js

```js
import { createHmac, timingSafeEqual } from 'node:crypto';

export function ladonSignatureIsValid(secret, id, timestamp, body, header) {
    if (Math.abs(Date.now() / 1000 - Number(timestamp)) > 300) {
        return false;
    }

    const key = Buffer.from(secret.replace(/^whsec_/, ''), 'base64');
    const expected = createHmac('sha256', key)
        .update(`${id}.${timestamp}.${body}`)
        .digest();

    return header.split(' ').some((signature) => {
        if (!signature.startsWith('v1,')) {
            return false;
        }

        const given = Buffer.from(signature.slice(3), 'base64');

        return (
            given.length === expected.length && timingSafeEqual(given, expected)
        );
    });
}
```

### Python

```python
import base64, hashlib, hmac, time

def ladon_signature_is_valid(secret: str, id: str, timestamp: str, body: bytes, header: str) -> bool:
    if abs(time.time() - int(timestamp)) > 300:
        return False

    key = base64.b64decode(secret.removeprefix("whsec_"))
    message = f"{id}.{timestamp}.".encode() + body
    expected = base64.b64encode(hmac.new(key, message, hashlib.sha256).digest()).decode()

    return any(
        signature.startswith("v1,") and hmac.compare_digest(expected, signature[3:])
        for signature in header.split(" ")
    )
```

### Go

```go
func LadonSignatureIsValid(secret, id, timestamp string, body []byte, header string) bool {
    sent, err := strconv.ParseInt(timestamp, 10, 64)
    if err != nil || math.Abs(float64(time.Now().Unix()-sent)) > 300 {
        return false
    }

    key, err := base64.StdEncoding.DecodeString(strings.TrimPrefix(secret, "whsec_"))
    if err != nil {
        return false
    }

    mac := hmac.New(sha256.New, key)
    mac.Write([]byte(id + "." + timestamp + "."))
    mac.Write(body)
    expected := base64.StdEncoding.EncodeToString(mac.Sum(nil))

    for _, signature := range strings.Split(header, " ") {
        if strings.HasPrefix(signature, "v1,") && hmac.Equal([]byte(expected), []byte(signature[3:])) {
            return true
        }
    }

    return false
}
```

Always check the signature over the raw body. Frameworks that parse and re-encode JSON change the bytes, and the signature no longer matches.

## Answering

- Answer with any `2xx` status within 15 seconds. Do the real work afterwards, for example on a queue.
- Use `webhook-id` to skip messages you already handled. A retry after a timeout can arrive while you are still processing the first attempt.
- Redirects are not followed. Point the channel at the final URL.
- Ladon reads at most 64 KB of your answer and keeps the first 512 bytes in the delivery log.

## Retries

When a delivery fails, Ladon tries again after 5 seconds, 5 minutes, 30 minutes, 2 hours, 5 hours, 10 hours, 14 hours, 20 hours and 24 hours, each with up to 10% random spread. That is about three days in total. A `Retry-After` header is followed, up to one hour.

| Error in the delivery log | Meaning                                                                          |
| ------------------------- | -------------------------------------------------------------------------------- |
| `non_2xx`                 | Your endpoint answered with another status than `2xx`                            |
| `redirect`                | Your endpoint answered with a redirect                                           |
| `timeout`                 | No complete answer within 15 seconds, or no connection within 5                  |
| `connect`                 | The connection was refused or dropped                                            |
| `tls`                     | The certificate is invalid, expired or for another host                          |
| `dns`                     | The host name does not resolve                                                   |
| `ssrf_blocked`            | The host name points to a private or reserved address. Ladon does not send there |
| `invalid_url`             | The URL itself is not allowed, for example not `https`                           |

`ssrf_blocked` and `invalid_url` are not retried, because only a new URL helps. A `410 Gone` switches the channel off right away. What else happens when deliveries keep failing is in [Channels](https://ladon.hackindex.io/docs/channels.md).

## Verifying your endpoint

When you add a webhook channel or change its URL, Ladon sends a message of type `endpoint.verify` with a random `data.challenge`. Answer within 10 seconds with a `2xx` status and this JSON body:

```json
{ "challenge": "the value of data.challenge" }
```

Until then the channel waits for verification and receives no alerts. You can retry the check from the channel page.

## Rotating the secret

Rotate the secret on the channel page when it may have leaked, or as a routine. The new secret is shown once. For 24 hours Ladon signs with both the old and the new secret, so `webhook-signature` contains two signatures. Deploy the new secret within that time.

## Network

Ladon only connects from its own servers. The outgoing IP addresses will be published here, so you can allow them in your firewall. Do not rely on them alone: always check the signature.
