Kest

Search

Search the documentation

HTTP

Webhooks

Send signed events to your customers' servers, and verify the ones you receive.

A webhook is an HTTP request your server sends to somebody else's server when something happens ("order 7 was paid"). The receiver gives you a URL, you POST a small JSON document to it. Two problems make this harder than it sounds:

  1. The receiver must know the request really came from you. Anyone can POST to a public URL. So every request is signed with a secret that only you and the receiver know.
  2. Networks fail. The receiver may be down for ten minutes. So you retry with growing waits, and give every message an id so the receiver can ignore a duplicate.

Kest does both for sending, and checks the signature for receiving.

Sending webhooks to your customers

1. Create a sender and register it

WebhookSender is a plain class. Register it once so any service can inject it:

@Module
class WebhooksModule {
    companion object {
        fun forRoot() = DynamicModule.create(WebhooksModule::class) {
            provide(WebhookSender(WebhookSenderOptions().apply {
                maxAttempts = 6                                   // the first try plus five retries
                timeout = Duration.ofSeconds(10)                  // give up on one request after 10 s
            }))
        }
    }
}
 
Kest.run<AppModule> { import(WebhooksModule.forRoot()) }

2. Let a customer subscribe

A subscription is a URL, a secret and the events the customer wants. In a real application you store these in your database (the sender keeps them in memory) and call subscribe for each one when the application starts:

val sub = sender.subscribe(
    url = "https://customer.example/hooks/kest",
    secret = "whsec_8f3a...",                 // generate a long random value, show it to the customer ONCE
    "order.*", "invoice.paid",               // event names; "order.*" matches order.created, order.paid ...; no names means everything
)

3. Publish an event

@Injectable
class CheckoutService(private val sender: WebhookSender, private val orders: OrderRepository) {
    fun pay(orderId: String) {
        val order = orders.markPaid(orderId)
        val results = sender.publish("order.paid", mapOf("id" to order.id, "total" to order.total))
        // results: one Delivery per matching subscription, with every attempt (status code, error, milliseconds)
    }
}

The body the customer receives:

{ "id": "evt_9c1e...", "type": "order.paid", "created": 1794400000, "data": { "id": "7", "total": 4200 } }

and these headers:

HeaderMeaning
webhook-ididentifies the message; the same on every retry, so the receiver can drop duplicates
webhook-timestampseconds since 1970 when this attempt was signed
webhook-signaturev1= + HMAC-SHA256 of id.timestamp.body with the subscription's secret
webhook-eventthe event name

How delivery behaves

The receiver answersKest does
200 to 299success, stop
408, 425, 429 or 5xx, or no answerwait (5 s, 30 s, 5 min, 30 min, 2 h) and try again, up to maxAttempts
any other 4xx (400, 401, 404, 410...)stop: the receiver said no, retrying will not change that

Change the waits with backoff. Private addresses (localhost, 10.x, 192.168.x, link-local) are refused by default, so a customer cannot make your server call your internal network (this attack is called SSRF); switch it off with blockPrivateNetworks = false only in tests. Redirects are not followed.

Make it survive a crash

publish sends from the calling thread, and if your process dies midway the rest of the retries are lost. For important events, write them to the transactional outbox inside the same database transaction as your change, and let its handler call deliver:

// when paying: part of the same transaction as markPaid
outbox.publish("webhook.order.paid", mapOf("id" to order.id))
 
// at startup
OutboxModule.forRoot {
    store = SqlOutboxStore(datastore)
    on("webhook.order.paid") { m ->
        sender.subscriptions().filter { it.wants("order.paid") }.forEach { s ->
            val d = sender.deliver(s, "order.paid", m.payload, messageId = m.id)      // same message id on every retry of the outbox too
            if (!d.success) error("delivery to ${s.url} failed")                       // the outbox retries later and finally parks it as dead
        }
    }
}

Receiving webhooks

When another service (GitHub, Stripe, a partner, another Kest app) calls you, check the signature before you trust the request. The check needs the exact bytes that were signed, so it runs on the raw body, before any JSON parsing.

@Controller("/hooks")
@UseGuards(GithubGuard::class)
class HooksController {
    @Post("/github") fun github(@Body payload: Map<String, Any?>): String = "ok"
}
 
@Injectable class GithubGuard : Guard by WebhookGuard(System.getenv("GITHUB_WEBHOOK_SECRET"))

WebhookVerifier understands three formats and picks by header:

SenderHeaders it checks
Kest and other Standard Webhooks senderswebhook-id, webhook-timestamp, webhook-signature
GitHubx-hub-signature-256: sha256=...
Stripestripe-signature: t=...,v1=...
val verifier = WebhookVerifier(listOf(newSecret, oldSecret), toleranceSeconds = 300)
try { verifier.verify(request) } catch (e: WebhookVerificationException) { throw UnauthorizedException(e.message) }
  • Rotation: pass the new and the old secret; either one is accepted, so you can change a secret without dropping events.
  • Replay protection: a request whose timestamp is more than toleranceSeconds (5 minutes by default) away from now is refused, so a captured request cannot be replayed next week.
  • Constant-time comparison is used, so the signature cannot be guessed byte by byte.
  • Be idempotent. The same webhook-id may arrive twice (a retry after your server answered slowly). Store the ids you processed, or use idempotency keys.
  • Answer fast (2xx within a few seconds) and do the real work in a queue.

Testing

Point a subscription at a TestServer, or use a tiny local HTTP server, and set blockPrivateNetworks = false and sleeper = {} so retries do not wait:

val sender = WebhookSender(WebhookSenderOptions().apply { blockPrivateNetworks = false; sleeper = { } })
sender.subscribe("http://localhost:${receiver.port}/hook", "secret")
val delivery = sender.publish("order.paid", mapOf("id" to 1)).single()
assertTrue(delivery.success); assertEquals(1, delivery.attempts.size)

Read more