# Webhook security

## Webhook security

Your webhook endpoint is a public URL. Anyone who finds it can send it a request that looks like a Pluggy notification, and a request that really came from Pluggy could, in principle, be read or altered on its way to you. No single check covers all of that, so combine the layers below. Each section says what the layer protects against and what it leaves open.

1. [Serve the endpoint over HTTPS and answer fast](#1-https-and-fast-2xx)
2. [Allow only Pluggy's source IPs](#2-allow-only-pluggys-source-ips)
3. [Require an authentication header](#3-require-an-authentication-header)
4. [Verify the signature](#4-verify-the-signature)
5. [Validate the payload and re-fetch the data](#5-validate-the-payload-and-re-fetch-the-data)

The [checklist](#checklist) and the [summary table](#summary) at the end put them side by side.

## 1. HTTPS and fast 2xx

Pluggy only delivers to public HTTPS URLs (see the [URL requirements](/docs/reference/webhooks#url-requirements)), so the request and its body are encrypted in transit.

Answer with a `2xx` as soon as you have accepted the request, and do the processing afterwards. A handler that takes longer than 10 seconds is counted as a failure and retried, and some error statuses are never retried at all. The rules are in [Handling notifications](/docs/developer-tools/webhooks-ref#handling-notifications); the short version for security is:

- Reject a request that fails one of the checks below with `401`. It is not retried, which is what you want for a request that is not from Pluggy.
- Return `5xx` when the problem is on your side and temporary, so the notification comes back.

**Protects against:** reading or modifying the request on the network.
**Does not protect against:** anyone on the internet sending their own request to your URL. HTTPS proves who *you* are, not who the caller is.

## 2. Allow only Pluggy's source IPs

Webhooks leave Pluggy from a published set of addresses. Allow them in your firewall, load balancer or handler and drop everything else. The list lives in one place, so it is always current: the "Whitelisting Pluggy's IPs" note in [Responding to notifications](/docs/developer-tools/webhooks-ref#responding-to-notifications).

**Protects against:** requests from arbitrary hosts on the internet.
**Does not protect against:** a request that passes through an allowed network path but carries a forged or altered body. An IP address tells you which network a request came from, not who wrote it or whether the body is the one Pluggy sent. Keep it as a coarse filter in front of the checks below, never as the only one.

## 3. Require an authentication header

When you create a webhook with [`POST /webhooks`](/docs/reference/webhooks#webhook-resource), you can give it a `headers` object. Put a long random secret there, for example in `Authorization`, and have your endpoint answer `401` to any request that does not carry it. See [Webhook headers](/docs/developer-tools/webhooks-ref#webhook-headers).

```json
{
  "url": "https://hooks.example.com/pluggy",
  "event": "all",
  "headers": {
    "Authorization": "Bearer <a long random value>"
  }
}
```

A `webhookUrl` set on an Item or a Connect Token does not send custom headers, so do not require one on that URL. The [signature](#4-verify-the-signature) covers those deliveries too.

**Protects against:** requests from anyone who does not know the secret.
**Does not protect against:** a leaked value. The header is the same on every request, so anyone who sees one delivery — in a proxy log, an error report, a debugging tool — can replay it or attach it to a body of their own. It also says nothing about whether the body was changed.

## 4. Verify the signature

The signature is the only layer that proves a notification was sent by Pluggy **and** that its body was not altered. It is optional and set up per application.

### Turn it on

In the Dashboard, open your application and, in **Webhooks**, choose **Generate signing secret**. Only the team **Owner** can generate, regenerate or remove it.

The secret is `whsec_` followed by 64 hexadecimal characters. It is shown **once**: store it as a secret in your webhook receiver's configuration before closing the dialog.

From then on, every webhook delivery for that application carries a signature header — whether it goes to a webhook created with `POST /webhooks` or to a `webhookUrl` set on an Item or a Connect Token:

```
X-Pluggy-Signature: t=1795000000,v1=5f2b…
```

| Part | Meaning |
| --- | --- |
| `t` | Unix timestamp, in seconds, of this delivery attempt. Every retry is signed again with a fresh `t`. |
| `v1` | Lowercase hex HMAC-SHA256 of the string `<t>.<raw request body>`, using the full secret (including the `whsec_` prefix) as the key, encoded as UTF-8. |

`X-Pluggy-Signature` is set by Pluggy. A header with that name in your webhook's `headers` does not set or override it.

### Verify every request

1. Read the **raw body** exactly as it arrived, before any JSON parsing. Parsing and re-serialising changes the bytes, and the signature will not match.
2. Parse `t` and `v1` from `X-Pluggy-Signature`. Reject the request if the header is missing or malformed.
3. Reject the request if `t` is more than **5 minutes** away from your clock. An old signature is still a valid signature, so this tolerance is what stops a captured request from being replayed later.
4. Compute HMAC-SHA256 of `<t>.<raw body>` with your secret and compare it to `v1` with a **constant-time** comparison.
5. Answer `401` if nothing matches. Only then parse the JSON.

The helpers below take a **list** of secrets, so the same code accepts the old and the new secret during a [rotation](#rotating-the-secret).

<CodeGroup>
<CodeTab title="Node.js">

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

const TOLERANCE_SECONDS = 5 * 60;

// rawBody: the request body as a Buffer, before any JSON parsing.
// header:  the value of X-Pluggy-Signature.
// secrets: the signing secrets you currently accept, e.g. [current, previous].
export function verifyPluggySignature(rawBody, header, secrets) {
  const parts = new Map(
    String(header ?? "")
      .split(",")
      .map((part) => {
        const i = part.indexOf("=");
        return [part.slice(0, i).trim(), part.slice(i + 1).trim()];
      }),
  );

  const t = parts.get("t");
  const received = parts.get("v1");
  // The header is untrusted input: reject anything that is not a plain decimal
  // timestamp and a 64-character hex digest.
  if (!t || !received || !/^[0-9]{1,12}$/.test(t) || !/^[0-9a-f]{64}$/.test(received)) return false;

  // Anti-replay: reject a signature more than 5 minutes old.
  if (Math.abs(Math.floor(Date.now() / 1000) - Number(t)) > TOLERANCE_SECONDS) return false;

  const receivedBytes = Buffer.from(received, "utf8");
  return secrets.some((secret) => {
    const expected = createHmac("sha256", secret)
      .update(`${t}.`)
      .update(rawBody)
      .digest("hex");
    const expectedBytes = Buffer.from(expected, "utf8");
    return (
      expectedBytes.length === receivedBytes.length &&
      timingSafeEqual(expectedBytes, receivedBytes)
    );
  });
}
```

Wired into an Express app, keeping the raw body:

```js
import express from "express";

const app = express();

const SECRETS = [process.env.PLUGGY_WEBHOOK_SECRET, process.env.PLUGGY_WEBHOOK_SECRET_PREVIOUS].filter(Boolean);

app.post("/pluggy/webhooks", express.raw({ type: "application/json" }), (req, res) => {
  if (!verifyPluggySignature(req.body, req.get("X-Pluggy-Signature"), SECRETS)) {
    return res.status(401).end();
  }

  const event = JSON.parse(req.body.toString("utf8"));
  enqueue(event); // de-duplicate on event.eventId, then process
  res.status(200).end();
});
```

</CodeTab>
<CodeTab title="Python">

```python
import hashlib
import hmac
import re
import time

TOLERANCE_SECONDS = 5 * 60
TIMESTAMP = re.compile(r"[0-9]{1,12}\Z")
DIGEST = re.compile(r"[0-9a-f]{64}\Z")


def verify_pluggy_signature(raw_body, header, secrets):
    """raw_body: the request body as bytes, before any JSON parsing.
    header: the value of X-Pluggy-Signature.
    secrets: the signing secrets you currently accept, e.g. [current, previous]."""
    parts = {}
    for part in (header or "").split(","):
        key, sep, value = part.partition("=")
        if sep:
            parts[key.strip()] = value.strip()

    t = parts.get("t")
    received = parts.get("v1")
    # The header is untrusted input: anything that is not a plain decimal
    # timestamp and a 64-character hex digest is rejected, never parsed.
    if not t or not received or not TIMESTAMP.match(t) or not DIGEST.match(received):
        return False

    # Anti-replay: reject a signature more than 5 minutes old.
    if abs(int(time.time()) - int(t)) > TOLERANCE_SECONDS:
        return False

    signed = t.encode("utf-8") + b"." + raw_body
    for secret in secrets:
        expected = hmac.new(secret.encode("utf-8"), signed, hashlib.sha256).hexdigest()
        if hmac.compare_digest(expected, received):
            return True
    return False
```

Wired into a Flask app, keeping the raw body:

```python
import json
import os

from flask import Flask, request

app = Flask(__name__)

SECRETS = [s for s in (os.environ.get("PLUGGY_WEBHOOK_SECRET"), os.environ.get("PLUGGY_WEBHOOK_SECRET_PREVIOUS")) if s]


@app.post("/pluggy/webhooks")
def pluggy_webhook():
    raw = request.get_data()  # the bytes Pluggy signed
    if not verify_pluggy_signature(raw, request.headers.get("X-Pluggy-Signature"), SECRETS):
        return "", 401

    event = json.loads(raw)
    enqueue(event)  # de-duplicate on event["eventId"], then process
    return "", 200
```

</CodeTab>
</CodeGroup>

To check your implementation against a delivery you captured: HMAC-SHA256 of `t + "." + rawBody` with your secret, in lowercase hex, must equal `v1` character for character.

### Rotating the secret

**Regenerate** in the Dashboard issues a new secret and replaces the old one **immediately**: Pluggy does not sign with both, and your receiver cannot know the new value before it exists. Notifications sent between the moment you regenerate and the moment your receiver has the new secret will fail verification. Plan for that window instead of losing them:

1. **Before regenerating**, make your receiver answer a signature failure with `503` instead of `401`. A `401` is [never retried](/docs/developer-tools/webhooks-ref#responses-we-do-not-retry); a `503` is, so a notification that arrives during the window comes back later instead of being dropped.
2. Regenerate the secret and copy the new value.
3. Deploy it to your receiver **next to** the old one, so it accepts either (the helpers above take a list). Notifications rejected in the window are retried and now verify.
4. Keep accepting the old secret for a while. Deliveries that were already queued for a retry before you regenerated are still signed with it, for a few hours.
5. Remove the old secret from your receiver and go back to answering `401`.

Retries follow the normal [schedule](/docs/developer-tools/webhooks-ref#retry-schedule), so a notification from the window arrives late. If you skip step 1, or the window outlasts the retries, the notifications rejected in it are not delivered again on their own: resend them from the Dashboard, or re-fetch the affected resources from the API.

A manual resend from the Dashboard is signed with the secret the event had when it was first sent. Resending an event from before a rotation therefore produces a signature that only the previous secret verifies.

**Remove** in the Dashboard makes webhooks go out unsigned again. If your receiver requires the signature, it will reject them — stop requiring it first.

<Callout variant="warning" title="A rejected notification is not retried">
Outside a rotation, answer `401` when a signature does not verify: a `401` is not retried, which is what you want for a request that is not from Pluggy. The same rule means a real notification rejected because your receiver did not have the right secret yet is not delivered again on its own. Follow the steps above when you rotate.
</Callout>

**Protects against:** forged requests and bodies altered in transit or by an intermediary, from anyone who does not have the secret; replays older than 5 minutes.
**Does not protect against:** a leaked signing secret — regenerate it if that happens. A replay inside the 5-minute window — de-duplicate on `eventId` (next section). And it does not make the payload a source of truth: the notification is still only a hint.

## 5. Validate the payload and re-fetch the data

Even a verified notification only tells you *that* something happened. Treat it as a hint and let the API tell you what is true:

- **Check `clientId`.** It is the application the webhook belongs to. Ignore any notification whose `clientId` is not one of yours.
- **Re-fetch before you act.** Read the resource with your own API key — for example `GET /items/{id}` for an `item/*` event, as described in [Responding to notifications](/docs/developer-tools/webhooks-ref#responding-to-notifications) — and act on what the API returns, not on the payload.
- **Make the handler idempotent.** Use `eventId` as the key: the same `eventId` arriving twice is the same event, so the second one is a no-op that still answers `2xx`. Retries and manual resends repeat an event; duplicates are normal.
- **Ignore what you do not expect.** An `event` type you do not handle, or a payload missing the fields you need, gets a `2xx` and no action.

**Protects against:** acting on a forged, stale, duplicated or out-of-order notification, and acting on another account's data.
**Does not protect against:** forged requests reaching your endpoint — that is what layers 2 to 4 are for. Re-fetching limits the damage of a forged notification to an extra API call.

## Checklist

- The endpoint is HTTPS and answers `2xx` within 10 seconds, processing afterwards.
- Requests from outside [Pluggy's IPs](/docs/developer-tools/webhooks-ref#responding-to-notifications) are dropped.
- Webhooks created with `POST /webhooks` carry a secret in `headers`, and requests without it get `401`.
- The application has a signing secret, and every request is verified over the raw body, with a constant-time comparison and a 5-minute tolerance on `t`.
- The receiver accepts a list of signing secrets, and during a [rotation](#rotating-the-secret) it answers `503` instead of `401` to a failed signature: the new secret cannot be deployed before it exists, and only a retried notification survives that window.
- `clientId` is checked, the resource is re-fetched with your own API key, and `eventId` makes processing idempotent.
- Secrets live in your secret store, never in source control or logs.

## Summary

| Measure | Protects against | Does not protect against |
| --- | --- | --- |
| HTTPS endpoint | Reading or modifying the request on the network | Anyone sending their own request to your URL |
| Source IP allowlist | Requests from arbitrary hosts | Forged or altered bodies; says nothing about integrity |
| Authentication header | Requests from callers without the secret | Replay or reuse of a leaked header; altered bodies. Not sent to a `webhookUrl` on an Item or Connect Token |
| Signature (HMAC) | Forged requests and altered bodies; replays older than 5 minutes | A leaked signing secret; replays inside the 5-minute window |
| Validate and re-fetch | Acting on forged, stale, duplicated or foreign notifications | Requests reaching your endpoint in the first place |