> For the complete documentation index, see [llms.txt](https://docs.channex.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.channex.io/api-v.1-documentation/webhook-collection/hmac-signing.md). Agents can also search and read this documentation through its [MCP server](https://docs.channex.io/~gitbook/mcp).

# HMAC Signing

## Signing Keys

Manage the HMAC secrets used to [sign outgoing webhooks](#webhook-security). Each signing key belongs to a billing account and has one or more **versions** — each version holds a secret. At most one version is the **current** one; a second, **pending** version may exist during a [rotation](#key-rotation).

Secrets are generated server-side. The full secret value is returned **only once** — by the create and `generate` endpoints — so store it the moment you receive it. Everywhere else a version's `secret` is **masked** to `...` plus its last 6 characters (e.g. `...a1b2c3`) — the same label Channex sends in the `x-hmac-keys-256` header, so you can tell which secret signed a request.

### Access policy

| Operation                                          | Who can call it                                             |
| -------------------------------------------------- | ----------------------------------------------------------- |
| List signing keys / List options                   | Any user with a membership in the requested billing account |
| Get / Create / Update / Delete / Generate / Rotate | Owners of the key's (or target) billing account             |

### How it works

When signing is enabled on a webhook, Channex adds three headers to every outgoing request:

| Header                 | Description                                                                                                                             |
| ---------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |
| `x-hmac-timestamp`     | Unix epoch (seconds) used when signing.                                                                                                 |
| `x-hmac-signature-256` | Comma-separated lowercase-hex HMAC-SHA256 signatures. **1 or 2** signatures (current first, pending second — see "Key Rotation" below). |
| `x-hmac-keys-256`      | Key labels `...{last6}` in the same order as the signatures. Lets you identify which secret was used.                                   |

The signature is computed as:

```
signature = lowercase_hex( HMAC_SHA256( secret, "<timestamp>.<raw_request_body>" ) )
```

The string being signed is **`{timestamp}.{raw_body}`** — note the literal `.` between them. `raw_body` is the **exact bytes** of the request body, before any JSON parsing or re-serialization.

{% hint style="danger" %}
**Always validate the signature against the raw request body** — the bytes you read off the wire, **before** any JSON parser, body re-serializer, or framework middleware touches it.

JSON parsers can re-order keys, normalize whitespace, change number representation, or escape Unicode differently. Any of these changes the byte content, and the signature will fail. The signature is computed over the **literal payload string** Channex POSTs, so you must compare against that exact string.

Common pitfalls:

* **Node.js (Express):** use `express.raw({ type: 'application/json' })` and read `req.body` as a `Buffer`. Do **not** use `express.json()` before verification.
* **Python (Flask):** use `request.get_data()` (raw bytes) before any `request.get_json()` call.
* **Ruby (Rack):** read `request.body.read` (and `request.body.rewind` afterwards if downstream middleware needs it).
* **Cloudflare Workers / AWS Lambda / API Gateway:** check the platform docs — some normalize JSON automatically. You may need to disable body parsing or use the raw-payload field.
  {% endhint %}

## Verifying a Signature

Your endpoint holds **one secret at any given time**. Build the signed string `{timestamp}.{raw_body}`, HMAC it with that secret, lowercase-hex it, and compare to the signature(s) in `x-hmac-signature-256`. Channex normally sends one signature; during a [key rotation](#key-rotation) it temporarily sends two — accept the request if **any** of them matches the secret you hold.

Always use a constant-time comparison (e.g. `crypto.timingSafeEqual` in Node, `hmac.compare_digest` in Python) to defend against timing attacks. Reject requests whose `x-hmac-timestamp` is too far from the current time (300 s is a common tolerance) to defend against replay attacks.

### Node.js (Express)

```js
import crypto from 'node:crypto';
import express from 'express';

const app = express();
app.use(express.raw({ type: 'application/json' })); // keep req.body as Buffer

const SECRET = 'YOUR_SECRET';
const MAX_SKEW_SECONDS = 300;

function verify(req) {
  const ts = req.get('x-hmac-timestamp');
  const sigsHeader = req.get('x-hmac-signature-256') || '';
  if (!ts || Math.abs(Date.now() / 1000 - Number(ts)) > MAX_SKEW_SECONDS) return false;

  const raw = req.body; // Buffer
  const hmac = crypto.createHmac('sha256', SECRET);
  hmac.update(`${ts}.`);
  hmac.update(raw); // append raw bytes — don't re-encode
  const expected = hmac.digest('hex');

  // Header carries 1 signature normally, or 2 during a key rotation overlap.
  // Accept the request if any of them matches the secret we hold.
  return sigsHeader.split(',').some((sig) => {
    const a = Buffer.from(sig, 'hex');
    const b = Buffer.from(expected, 'hex');
    return a.length === b.length && crypto.timingSafeEqual(a, b);
  });
}

app.post('/webhook', (req, res) => {
  if (!verify(req)) return res.status(401).send('invalid signature');
  const payload = JSON.parse(req.body.toString('utf8'));
  // ... process payload
  res.sendStatus(200);
});
```

### Python (Flask)

```python
import hmac, hashlib, time
from flask import Flask, request, abort

app = Flask(__name__)
SECRET = b"YOUR_SECRET"
MAX_SKEW_SECONDS = 300

@app.post("/webhook")
def webhook():
    ts = request.headers.get("x-hmac-timestamp", "")
    sigs_header = request.headers.get("x-hmac-signature-256", "")
    raw = request.get_data()  # raw bytes BEFORE any JSON parsing

    if not ts or abs(time.time() - int(ts)) > MAX_SKEW_SECONDS:
        abort(401)

    signed = ts.encode() + b"." + raw
    expected = hmac.new(SECRET, signed, hashlib.sha256).hexdigest()

    # Header carries 1 signature normally, or 2 during a key rotation overlap.
    # Accept the request if any of them matches the secret we hold.
    if not any(hmac.compare_digest(expected, s) for s in sigs_header.split(",")):
        abort(401)

    payload = request.get_json()  # safe to parse now
    # ... process payload
    return ("", 200)
```

### Ruby (Rack / Sinatra)

```ruby
require 'openssl'
require 'rack/utils'

SECRET = 'YOUR_SECRET'
MAX_SKEW_SECONDS = 300

post '/webhook' do
  ts = request.env['HTTP_X_HMAC_TIMESTAMP']
  sigs_header = request.env['HTTP_X_HMAC_SIGNATURE_256'].to_s
  request.body.rewind
  raw = request.body.read

  halt 401 if ts.nil? || (Time.now.to_i - ts.to_i).abs > MAX_SKEW_SECONDS

  signed = "#{ts}.#{raw}"
  expected = OpenSSL::HMAC.hexdigest('sha256', SECRET, signed)

  # Header carries 1 signature normally, or 2 during a key rotation overlap.
  # Accept the request if any of them matches the secret we hold.
  unless sigs_header.split(',').any? { |sig| Rack::Utils.secure_compare(expected, sig) }
    halt 401
  end

  # ... process payload
end
```

## Enabling Signing on a Webhook

Signing is managed through the **Signing Keys API**. The high-level flow:

{% stepper %}
{% step %}

### **Create a signing key**

[Create Signing Key API](https://docs.channex.io/api-v.1-documentation/webhook-collection/create-signing-key-api.md)\
\
The response contains `data.attributes.secret` — the full secret. **Copy it now**; it cannot be retrieved later.
{% endstep %}

{% step %}

### **Configure a webhook to sign with it**

[Update Webhook API](https://docs.channex.io/api-v.1-documentation/webhook-collection/update-webhook-api.md)\
\
Set `is_signed: true` and `signing_key_id` when creating or updating the webhook.<br>

`signing_key_id` is **required** whenever `is_signed` is `true` — the request is refused with `422` otherwise. The key must belong to a billing account you have a membership in (any role); a key you cannot reach, or one that was deleted, is reported as `signing_key_id does not exist`. Webhook responses expose `is_signed` and `signing_key_id` as attributes, and the key itself (with masked versions) under the `signing_key` relationship.\
\
When `is_signed` is `false` (the default), Channex sends the request **without** the `x-hmac-*` headers — your endpoint should fall back to whichever shared-secret / IP-allowlist mechanism you've configured.
{% endstep %}

{% step %}

### **Inspecting Signed Deliveries**

[Test Webhook API](https://docs.channex.io/api-v.1-documentation/webhook-collection/test-webhook-api.md)\
\
Trigger Webhook Test and check incoming Headers.
{% endstep %}
{% endstepper %}

## Key Rotation

Each of your endpoints holds **a single secret** at any time. The two-signature overlap that Channex emits during rotation exists so you can swap that one secret on each endpoint at your own pace — without any window where requests fail to verify.

The flow:

{% stepper %}
{% step %}

### **Generate a new (pending) version of the key**

[Generate Secret Version API](https://docs.channex.io/api-v.1-documentation/webhook-collection/generate-secret-version-api.md)

The response includes the new secret **once** — store it. From this moment, Channex signs every outgoing request with **both** the current and the new pending key (you'll see two values in `x-hmac-signature-256` / `x-hmac-keys-256`).
{% endstep %}

{% step %}

### **Swap the secret on each endpoint**

One at a time, from the old one to the new one. Each endpoint still holds a single secret throughout — because Channex includes both signatures during this window, a request verifies whether the endpoint has already been updated or not.
{% endstep %}

{% step %}

### **Rotate once every endpoint is on the new secret**

[Rotate a Signing Key API](https://docs.channex.io/api-v.1-documentation/webhook-collection/rotate-a-signing-key-api.md)

The pending version becomes current; the previous version is removed. Channex now signs only with the new secret. Your endpoints keep using the secret they already hold — no further change needed on your side. Rotating a key that has no pending version is refused with `422`.
{% endstep %}
{% endstepper %}

A key has **at most one current + one pending** version at any time.

{% hint style="danger" %}
**Do not call `generate` again while a pending version exists** — it replaces the pending. If you have already swapped any endpoint to the previously-pending secret, that endpoint will fail verification from the next request onward: Channex will sign with `current` + the newly-pending key, and neither matches the secret the endpoint switched to.

If you need to abort a partial rotation, deploy the old key first to all updated systems, then start a fresh `generate` cycle.
{% endhint %}
