Human approval webhooks for AI agents: why the webhook never carries the permission

Polling, long-polling or webhooks for agent approvals, why a decision event must never be the permission, and how to check Standard Webhooks signatures, drop duplicates and survive retries.

· 10 min read

An agent that asks a person before acting has to hear the answer somehow. For a script, waiting on an open connection is fine. For a serverless function, a queue worker or an n8n flow, a webhook is the natural fit: the agent asks, stops, and an event wakes it when the person has decided. This explains the trade-offs between polling, long-polling and webhooks, why the event must never be what permits the action, and how to receive it safely, with code in TypeScript and Python.

The short version: verify the signature, drop duplicates, then read the request with the agent’s key and act only when it says allowed: true. The event tells you when to look, never whether to act.

Polling, long-polling or a webhook

An agent asks a person before a risky action, then has to learn the answer. There are three ways to hear it.

Polling
The agent reads the request every few seconds until it is decided. Simple, and it works from behind any firewall. The cost is wasted calls, an answer that arrives up to one interval late, and a process that stays alive the whole time.
Long-polling
The agent reads the request and the server holds the call open until the request is decided or a time limit passes. In VariantGate that limit is wait_seconds, at most 30 seconds per call, and the SDKs' waiting helpers call again until it is decided or their time is up. The answer comes at once, with few calls and still no public address. A process still has to wait.
Webhook
Nothing waits. The agent asks and stops. When the request is decided, the server sends an event to an address of yours, and that wakes whatever carries on. It needs a public https endpoint that checks signatures, drops duplicates and copes with retries.

Long-polling suits an agent that is already running and expects an answer within minutes: a script, a coding agent, a worker that can afford to hold a connection. Webhooks suit work that should not wait at all: a serverless function that is billed while it runs, a queue consumer, an n8n flow, or a workflow engine that can sleep until something wakes it. A request in VariantGate can wait up to seven days for a person. No function should stay alive for that.

You can use both. A webhook that never arrives, because your endpoint was down for longer than the retries last, should not leave work stuck forever. A slow sweep that reads the requests you are still waiting on, say every few minutes, catches what the webhook missed. Webhooks are part of Pro and up. Asking and reading requests, waiting included, work on every plan.

The webhook is a notification, never a permission

The tempting design is to put the decision in the event: the receiver sees approved and runs the action. That makes the event a permission slip, and an event is a poor one. Four things go wrong.

  • Things change after the event. A person approves a refund. Then someone sees the agent misbehaving and presses the emergency stop. An event sent before the stop cannot know about it. In VariantGate nothing is allowed while the workspace or the agent’s key is paused, whatever was approved, and an owner can revoke a key at once.
  • Events arrive late, twice, or out of order. A retry can land hours after the decision. The same event can arrive twice. A retried request.waiting can arrive after the request.approved that followed it.
  • Events can be replayed. Anyone who captured a signed message can send it again. The signature still checks out; only the timestamp limits how long that works.
  • Events can be forged. A signing secret sits in environment variables, n8n credentials and CI settings. If it leaks, anyone can sign a message saying approved. If that message were a permission, the leaked secret would be as good as an approval.

Here is the first point in practice. Your endpoint is down when a request is approved, and the retries carry the event past an emergency stop:

09:31
The request is approved. request.approved is sent, and your endpoint fails to answer.
09:32, 09:37
Two retries fail too.
09:40
A person pauses every agent in the workspace.
10:07
The fourth attempt arrives, correctly signed. Its status still says approved.
Then
The receiver reads the request. allowed is false and paused is true. Nothing happens.

So the receiver treats an event as a reason to look. It reads the request with the agent’s own key, with GET /v1/requests/{id}, and acts only when that answer says allowed: true. A forged or replayed event then costs one read that returns the truth. An agent key can only read requests it asked itself, so a forged event naming another agent’s request gets nowhere either.

VariantGate’s payload has no allowed field, on purpose. It does carry status, which says what happened at the moment the event was made. That is useful for routing and logging. It is not permission to act.

{
  "id": "0196f1a2-7c4e-7d10-9a3b-2c5e8f1d4a60",
  "type": "request.approved",
  "timestamp": "2026-11-16T09:31:12.408113Z",
  "workspace_id": "0196f19c-1b2a-7e45-8d3c-6a7b9c0d1e2f",
  "data": {
    "request_id": "0196f1a0-55d2-7a11-b3e4-9f8e7d6c5b4a",
    "action": "payment.refund",
    "status": "approved",
    "approved_amount": "49.00",
    "…": "more fields, and never one called allowed"
  }
}

The Standard Webhooks spec describes a related choice. A thin payload carries only identifiers, so receivers must query the data they need. VariantGate’s events carry more than that, for routing and logging, but the decision to act still comes from the read. The field list for each event is on the webhooks page.

Verifying a Standard Webhooks signature

The re-read decides whether to act. The signature decides whether to bother reading, and keeps strangers from filling your queue. VariantGate signs the way the Standard Webhooks spec describes, so any library for it works too. Each message has three headers:

  • webhook-id: the event’s id, the same on every attempt.
  • webhook-timestamp: when this attempt was signed, in whole Unix seconds. It changes with each retry.
  • webhook-signature: v1, and the base64 of the signature. The header may hold several, separated by spaces, so a secret can be rotated; one match is enough.

To check a message:

  1. Keep the body exactly as it arrived. Parsing the JSON and printing it again changes the bytes, and the signature no longer matches.
  2. Take the bytes after whsec_ in the secret, decoded from base64, as the key.
  3. Compute HMAC-SHA256 over {id}.{timestamp}.{body}: the id, the timestamp and the raw body joined by full stops.
  4. Compare it with each v1 signature in constant time. An ordinary string comparison stops at the first wrong byte, and the time it takes tells an attacker how much of a guess was right. The spec warns that this can turn a receiver into a signing oracle.
  5. Refuse a timestamp too far from now. The spec asks for a tolerance without naming one. VariantGate’s helpers allow five minutes either way, which is enough for clock drift and short enough that a captured message soon stops working.
  6. Answer with a 2xx within 10 seconds, and do the real work on a queue. A slow answer counts as a failure and the event is sent again.

verifyWebhook in @variantgate/agent/webhook and verify_webhook in the variantgate Python package do all of this and return the event, or throw WebhookVerificationError. The TypeScript one uses Web Crypto’s verify, so it runs on Node 20 and later, Deno, Bun and edge runtimes. The Python one compares with hmac.compare_digest. Both take the tolerance as an option: toleranceSeconds in TypeScript, tolerance in Python. The webhooks page has the same check written by hand in Node and Python.

Duplicates, order and retries

Webhook senders retry until they get a 2xx, so a receiver must expect the same event more than once. VariantGate tries again after 1 minute, 5 minutes, 30 minutes, 2 hours and 8 hours: six attempts over about ten and a half hours, then it gives up. A 3xx counts as a failure, because redirects are not followed. The spec’s example schedule runs for days; this one is shorter, which is one more reason for the sweep.

  • Drop events you have handled. Store each webhook-id with a unique constraint and answer 2xx to a repeat without doing anything. Keep the ids for longer than the retry window, a day or more: a retry has a fresh timestamp, so the timestamp check lets it through.
  • Never infer state from order. Go by the request’s status in the re-read, not by which event came last.
  • Make the action itself idempotent. Dropping duplicate events is not enough. A request.outcome event names the same request as the approval, and a crash can run a job twice. Key the action on the request id, so it happens once however often the worker runs.
  • Expect silence. When the last retry fails, the event is gone. Settings shows the last 50 deliveries of each webhook and what your side answered.

Why the sender refuses private addresses

A webhook address is a URL the customer chooses and the server then calls. Without care, that is server-side request forgery: an address such as http://169.254.169.254/ or https://localhost:5432/ makes the sender a proxy into its own network. The Standard Webhooks spec says webhook systems are especially exposed to this. The OWASP cheat sheet names webhooks as the case where an allow list cannot work, so the sender must check that every address is public, connect only to the address it checked, and not follow redirects.

VariantGate does that:

  • Only https, on the standard port, with no user name or password, and a host name rather than an IP address. Names such as localhost or .internal are refused.
  • Each time it sends, it looks the name up and refuses it if any address it leads to is private, loopback, link-local, the cloud metadata address, or otherwise not on the public internet, in IPv4 and IPv6.
  • It connects only to the addresses it checked. A second lookup between checking and connecting is how DNS rebinding gets round such checks, and there is none.

For the receiver, that means:

  • A public host name on port 443, with every address it resolves to on the public internet. A name that also resolves to a private address is refused.
  • The final address, not one that redirects to it. A trailing slash that your framework redirects is enough to fail.
  • For a receiver inside a private network, such as a self-hosted n8n, expose only the webhook path through a public reverse proxy. On a laptop, use a tunnel that gives it a public https name.

End to end: an agent that waits without waiting

A serverless agent handles a refund. It asks, stops, and carries on when a person has decided, in three pieces:

  1. The agent asks, keeps the request’s id, and ends.
  2. A receiver checks the event, drops duplicates, queues the request id, and answers at once.
  3. A worker reads the request with the agent’s key and acts only on allowed: true.

1. Ask, and end

import { ApprovalClient } from "@variantgate/agent";

const approvals = new ApprovalClient({
  agent: "billing-bot",
  apiUrl: process.env.VARIANTGATE_API_URL ?? "https://api.variantgate.com",
  key: process.env.VARIANTGATE_KEY ?? "",
});

// In the serverless function: ask, remember the id, and end.
const asked = await approvals.ask({
  action: "payment.refund",
  amount: "49.00",
  currency: "EUR",
  details: { order_id: "1182" },
  summary: "Refund €49.00 to ana@example.com for order 1182",
});
await jobs.save({ order: "1182", requestId: asked.id });

If an allow rule decides it on the spot, the answer already says so, and a request.approved event is still sent. Letting the worker handle both cases keeps one path.

2. Receive

import { verifyWebhook, WebhookVerificationError } from "@variantgate/agent/webhook";

export async function POST(request: Request) {
  const body = await request.text(); // the raw body, before any JSON parsing
  let event;
  try {
    event = await verifyWebhook(process.env.VARIANTGATE_WEBHOOK_SECRET ?? "", request.headers, body);
  } catch (error) {
    if (error instanceof WebhookVerificationError) {
      return new Response("bad signature", { status: 400 });
    }
    throw error;
  }
  // Queue first, then remember the id: a crash in between gives a
  // duplicate job, which the worker survives, never a lost one.
  if (event.type === "request.approved" && !(await handled.has(event.id))) {
    await queue.send({ requestId: event.data.request_id });
    await handled.add(event.id);
  }
  return new Response(null, { status: 204 });
}

handled stands for any store with a unique key on the event id, such as a table in your database. Only request.approved starts work here. A denial, an expiry or a withdrawal could close the job on your side instead.

3. Read the request, then act

export async function resume(requestId: string) {
  const decision = await approvals.check(requestId); // with the agent's own key
  if (decision.paused) {
    throw new Error("paused: let the queue try again later");
  }
  if (!decision.allowed) {
    return; // denied, expired or withdrawn: nothing to do
  }
  if (decision.approved_summary !== decision.summary) {
    // A person approved other wording; this code can only do what it asked.
    await approvals.reportOutcome(requestId, "failed", "approved with changes");
    return;
  }
  const refund = await payments.refund({
    amount: decision.approved_amount, // what was approved, which may be less
    idempotencyKey: requestId, // one refund per request, however often this runs
  });
  await approvals.reportOutcome(requestId, refund.ok ? "succeeded" : "failed");
}

This is the step that makes the rest safe. check reads GET /v1/requests/{id} with the agent key. While the workspace or the agent’s key is paused, allowed is false and paused is true, so the job fails and the queue tries it again later, by which time an owner may have resumed. The refund uses approved_amount, because the person may have approved less than was asked; when they changed it, changed is true. The idempotency key stops a second refund if the job runs twice.

The same in Python

import os

from flask import Flask, request
from variantgate import WebhookVerificationError, verify_webhook

app = Flask(__name__)


@app.post("/variantgate")
def variantgate_webhook():
    try:
        event = verify_webhook(
            os.environ["VARIANTGATE_WEBHOOK_SECRET"],
            request.headers,
            request.get_data(),  # the raw body, before any JSON parsing
        )
    except WebhookVerificationError:
        return "", 400
    if event["type"] == "request.approved" and not handled.has(event["id"]):
        queue.send({"request_id": event["data"]["request_id"]})
        handled.add(event["id"])
    return "", 204
from variantgate import ApprovalClient

client = ApprovalClient("billing-bot")  # the key comes from VARIANTGATE_KEY


def resume(request_id: str) -> None:
    decision = client.check(request_id)
    if decision.get("paused"):
        raise RuntimeError("paused: let the queue try again later")
    if not decision["allowed"]:
        return  # denied, expired or withdrawn: nothing to do
    if decision["approved_summary"] != decision["summary"]:
        # A person approved other wording; this code can only do what it asked.
        client.report_outcome(request_id, "failed", "approved with changes")
        return
    refund = payments.refund(
        amount=decision["approved_amount"],
        idempotency_key=request_id,
    )
    client.report_outcome(request_id, "succeeded" if refund.ok else "failed")

The webhook’s signing secret and the agent key are different secrets, and they can live in different places. The receiver needs only the signing secret. The worker that acts needs the agent key, which can ask and read that agent’s requests but can never decide one.

Checklist

  • The receiver checks the signature on the raw body.
  • It refuses a timestamp more than a few minutes from now.
  • It stores event ids for longer than the retry window.
  • It answers within 10 seconds and queues the work.
  • The worker reads the request with the agent key and acts only on allowed: true.
  • It does what was approved, using approved_summary and approved_amount.
  • The action is keyed on the request id.
  • A slow sweep catches anything the webhook missed.

The events, the full payload and the limits are on the webhooks page. The fields of the read are in Requests, and what a pause does is in emergency stop.

Sources

  1. Standard Webhooks. The specification's home page and its technical steering committee.
  2. Standard Webhooks specification: the headers, the signed content msg_id.timestamp.payload, v1 signatures and whsec_ secrets.
  3. Standard Webhooks specification: verifying signatures. Timestamp tolerance, constant-time comparison, webhook-id as an idempotency key.
  4. Standard Webhooks specification: retries, the example schedule, and 2xx as the only success.
  5. Standard Webhooks specification: server-side request forgery, and keeping webhooks out of internal networks.
  6. Standard Webhooks specification: thin and full payloads.
  7. OWASP: Server-Side Request Forgery Prevention Cheat Sheet. Webhooks as the case where only a block list works; DNS rebinding.
  8. Python documentation: hmac.compare_digest, a comparison that avoids timing analysis.