Webhook-to-SSE gateway with hierarchical topic routing and signature verification
Files
.tangled
.codespellrc
.gitignore
.ko.yaml
.pre-commit-config.yaml
backend_memory.go
backend_redis_test.go
backend_redis.go
backend_test.go
backend.go
bearer_test.go
body_limit_test.go
broker_metrics_test.go
broker_test.go
broker.go
check-coverage
configuration_file_test.go
configuration_test.go
configuration_validate_test.go
configuration_validate.go
configuration.go
delivery_configuration_test.go
delivery_configuration.go
delivery_dead_letter_test.go
delivery_dispatcher_test.go
delivery_dispatcher.go
delivery_failure_test.go
delivery_http_test.go
delivery_http.go
delivery_memory.go
delivery_metrics_test.go
delivery_metrics.go
delivery_redis_test.go
delivery_redis.go
delivery_store_test.go
delivery_test.go
delivery_validate_test.go
delivery.go
event.go
filter_test.go
filter.go
go.mod
go.sum
keys.go
ko-build.sh
LICENSE
loq.toml
main.go
Makefile
metrics_test.go
metrics.go
payload_test.go
publish_headers_test.go
README.md
replicas_test.go
server_test.go
server.go
signature_test.go
signature.go
sse_metrics_test.go
sse_secret_test.go
sse_service_account_test.go
sse_test.go
tokenreview_test.go
tokenreview.go
verify_test.go
verify.go
webhook_metrics_test.go
wicket.yaml.example
README.md

wicket #

A webhook-to-SSE gateway. Receives webhook POSTs, delivers them to subscribers as Server-Sent Events.

How it works #

The entire HTTP API is two verbs on the same path:

POST  /<path>                              →  publish an event
GET   /<path>  Accept: text/event-stream   →  subscribe (SSE stream)

The path is an arbitrary topic name. Path separators create a hierarchy — subscribing to a prefix gets you all events underneath it:

GET /github.com/chrisguidry/docketeer  →  just docketeer events
GET /github.com/chrisguidry/           →  all chrisguidry repo events
GET /github.com/                       →  all GitHub events
GET /                                  →  everything

A POST to /github.com/chrisguidry/docketeer delivers to all four subscribers above.

Zero configuration by default #

wicket works out of the box with no configuration — any path accepts POSTs and SSE connections. A YAML configuration file layers in authentication only where needed:

paths:
  github.com/chrisguidry/docketeer:
    verify: hmac-sha256
    secret: "the-github-webhook-secret"
    signature_header: X-Hub-Signature-256
    subscribe_secret: "token-for-docketeer-subscribers"

Values support environment variable interpolation via $VAR or ${VAR} syntax, so secrets can come from the environment rather than being hardcoded:

paths:
  github.com/chrisguidry/docketeer:
    verify: hmac-sha256
    secret: "${WEBHOOK_SECRET}"
    signature_header: X-Hub-Signature-256
    subscribe_secret: "${SUBSCRIBE_TOKEN}"

A publisher that cannot sign its body, such as Alertmanager, can send a fixed token instead. The bearer method checks Authorization: Bearer <secret>, or the header that signature_header names. wicket removes the Authorization header from every event, and the headers that a path's verification read from that path's events: its signature_header, or the Signature, Signature-Input, and Content-Digest of rfc9421. Subscribers never receive a token or a signature they could replay:

paths:
  alertmanager:
    verify: bearer
    secret: "${ALERTMANAGER_TOKEN}"
    subscribe_secret: "${ALERTMANAGER_SUBSCRIBE_TOKEN}"

A publisher that signs with HTTP Message Signatures (RFC 9421) and Ed25519, such as transom, needs no shared secret. The rfc9421 method fetches the publisher's public keys from the JWKS at keys_url, and accepts a request whose signature covers its method, its URL, and a Content-Digest (RFC 9530) that matches its body, and whose created and expires parameters say it is fresh. A signature covers the URL the publisher posted to, so behind a proxy that changes the scheme or host, set base_url to the URL wicket is reached at:

paths:
  transom:
    verify: rfc9421
    keys_url: https://transom.example.com/.well-known/jwks.json
    base_url: https://wicket.example.com
  • Unconfigured paths accept POSTs without verification
  • Configured paths verify webhook signatures or tokens and reject invalid ones
  • Subscribe secrets require Authorization: Bearer <token> for SSE connections
  • A subscriber receives an event only if it sent the subscribe secret of the event's own path, which is the nearest secret at or above that path. A subscriber to a parent path receives the open events below it, and wicket withholds the protected ones and logs a withheld line for each
  • A POST body over -max-body-bytes, 5 MiB by default, gets a 413. A path that does not verify decodes and keeps whatever a stranger sends, so its cap is -max-unverified-body-bytes, 64 KiB by default. A body that does not arrive whole within 30 seconds gets a 400
  • A POST to a path with an empty, ., or .. segment gets a 400
  • The paths under wicket/ are for the events wicket publishes itself, so a POST to one gets a 403
  • wicket removes the Wicket-* headers from every event, because those are the headers it sets itself
  • Configuration is hot-reloaded on file change or SIGHUP

Subscribers in a Kubernetes cluster #

When wicket and a subscriber run as pods in the same Kubernetes cluster, the subscriber can prove who it is with its own ServiceAccount token, and no subscribe secret has to be made, stored, and handed to it. List the ServiceAccounts a path admits, as namespace/name:

paths:
  github.com/chrisguidry/docketeer:
    verify: hmac-sha256
    secret: "${WEBHOOK_SECRET}"
    signature_header: X-Hub-Signature-256
    subscribe_service_accounts:
      - agents/fixer
      - agents/reviewer

A path can have subscribe_secret, subscribe_service_accounts, or both. With both, a subscriber that sends the secret or the token of a listed ServiceAccount is admitted. Like a secret, the list protects the path and the paths below it, and the nearest protected path at or above an event's path is the one whose secret and list apply.

The subscriber sends its token as Authorization: Bearer <token>. wicket sends a bearer token that is not the path's secret to the API server's TokenReview API, and admits the subscriber when the review authenticates the token for wicket's audience and names a listed ServiceAccount. A connection is reviewed once, the first time it needs to be. A subscriber without a token, or with a token that the review refuses, gets the same 401 as a wrong secret. When wicket cannot reach the API server, it refuses a new subscription with a 503, and ends an open stream at the event it cannot check, so the subscriber reconnects with Last-Event-ID and replays it.

The subscriber mounts a projected token issued for wicket's audience, so a token it holds for any other service is useless to wicket, and a token it sends wicket is useless anywhere else:

spec:
  serviceAccountName: fixer
  containers:
    - name: fixer
      volumeMounts:
        - name: wicket-token
          mountPath: /var/run/secrets/wicket
          readOnly: true
  volumes:
    - name: wicket-token
      projected:
        sources:
          - serviceAccountToken:
              audience: wicket
              path: token

The kubelet rotates the token in that file, so the subscriber reads it again each time it connects.

The audience is wicket unless the top-level service_account_audience sets another:

service_account_audience: wicket.example.com

wicket calls https://kubernetes.default.svc with its own pod's ServiceAccount token and the cluster CA from /var/run/secrets/kubernetes.io/serviceaccount/. It reads them on the first review, and reads the token again on each review, because the kubelet rotates it. When no path lists ServiceAccounts, wicket makes no call and runs outside any cluster. wicket's ServiceAccount needs create on tokenreviews, which the ClusterRole system:auth-delegator grants:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: wicket-tokenreview
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects:
  - kind: ServiceAccount
    name: wicket
    namespace: wicket

Browser support #

CORS headers are sent on all responses, so browser apps can POST events and subscribe via EventSource. One limitation: the browser's EventSource API doesn't support custom headers, so browser clients can only subscribe to paths without a subscribe_secret. Protected paths are for server-to-server use.

Event format #

Every event is wrapped in an envelope and delivered as SSE:

id: 1761088172453-0
data: {"id":"1761088172453-0","timestamp":"...","path":"github.com/chrisguidry/docketeer","headers":{...},"payload":{...}}

An event's ID is its place in wicket's event log: the millisecond the log took the event, then a sequence number within that millisecond. Subscribers get events in the order of their IDs, and an event's timestamp is the time in its ID, so the timestamps are in the same order.

Replay #

A subscriber that reconnects with Last-Event-ID gets the events it missed from the log, which keeps the newest 1000 events by default. An ID the log no longer holds, or one that is not a log ID, replays the whole log. If wicket cannot read the log, it refuses the subscription with a 503, and the subscriber tries again with the same ID.

A subscriber that falls 64 events behind the live events is disconnected. When it reconnects with Last-Event-ID, it replays the rest, so it misses no event.

Replicas #

With -backend redis, every replica appends to one Redis stream and reads from it, so each replica delivers every event in one order, and a subscriber can resume on any replica. Without it, the log is in memory and belongs to one replica.

Delivery #

A path can also deliver its events: wicket POSTs each event it publishes to the HTTP targets that the path's deliver lists, and retries until a target takes the event or wicket gives it up. One webhook from a publisher that allows only one can reach several services this way, as well as the SSE subscribers:

paths:
  registry.example.com:
    verify: hmac-sha256
    secret: "${REGISTRY_SECRET}"
    signature_header: X-Webhook-Signature-256
    subscribe_secret: "${REGISTRY_SUBSCRIBE_TOKEN}"
    deliver:
      - name: flux
        url: http://webhook-receiver.flux-system.svc.cluster.local/hook/abc123
        filter: [payload.trigger:push]
        sign:
          header: X-Signature
          secret: "${FLUX_RECEIVER_TOKEN}"
        dead_letter: wicket/undelivered
  wicket/undelivered:
    subscribe_secret: "${REGISTRY_SUBSCRIBE_TOKEN}"
Field Default
name Required, and unique across the whole file: letters, digits, ., _, and -. It names the target's queue in Redis and labels its series.
url Required. An http or https URL.
filter Filters in the syntax of a subscription's ?filter=, all of which an event must match.
sign header and secret: wicket sets header to sha256=<hex HMAC-SHA256 of the body>.
headers Headers that wicket sets on each request, after every other header, so they win.
forward_headers Headers of the webhook that wicket passes on.
max_backoff 5m, or give_up_after if shorter The longest wait between two attempts, at most give_up_after.
give_up_after 24h How old an event can be and still be retried.
max_pending 1000 How many deliveries the target's queue holds.
max_pending_bytes 67108864 How many bytes of deliveries the target's queue holds, 64 MiB.
concurrency 2 How many requests each replica has in flight to the target.
dead_letter A path under wicket/ that receives each event wicket gives up.

A configuration that breaks a rule here does not load, and a reload of it keeps the configuration that last loaded. So does a verify without its secret or keys_url: an unset environment variable expands to an empty secret, which anyone can sign with.

What a target receives #

A target on a path receives an event when all of these hold:

  • The event's path is the target's path or below it, and wicket verified it. The root path "" cannot deliver, and a path that delivers must verify its POSTs.
  • The nearest path at or above the event's path that protects its subscriptions is the one that protects the target's path. A target on a parent path gets none of the events that a child with a subscribe secret or ServiceAccounts of its own withholds from the parent's subscribers.
  • The event matches the target's filter.

wicket checks these again before each attempt, against the configuration of that moment, and removes a delivery that no longer passes.

The body is the webhook's body, byte for byte. wicket sends the webhook's Content-Type, User-Agent: wicket/<version>, Wicket-Event-Id (the event's ID), Wicket-Path (the event's path), and Wicket-Delivery-Attempt (1 for the first attempt). Then it sets the headers that forward_headers names, then the sign header, then headers. It never passes on Authorization, Cookie, or any header that a path's verification reads. wicket refuses a POST that carries Wicket-Event-Id with a 400, because it is one of wicket's own deliveries that came back.

wicket follows no redirect, and gives each request 10 seconds. It reads at most 64 KiB of a response and uses only its status. It never logs a target's URL, which can hold a secret.

Retries #

Response Outcome
2xx delivered
5xx, 408, 429, no response, or no response in time retried after a backoff, or gave_up once the event is older than give_up_after
3xx, or any other 4xx rejected at once

The backoff after the nth failed attempt is 2^n seconds, at most max_backoff, less up to 20% at random so that retries spread out. A Retry-After that asks for longer is honored, up to max_backoff.

Dead letters #

wicket publishes each event it gives up or a target rejects to the target's dead_letter path, as an event whose payload says what happened:

{
  "target": "flux",
  "path": "registry.example.com/team",
  "outcome": "rejected",
  "status": 404,
  "attempts": 1,
  "event": {"id": "1761088172453-0", "path": "registry.example.com/team", "headers": {}, "payload": {}}
}

status is the HTTP status of the last attempt, or connect_failed or timeout when no response came. The dead-letter path must be under wicket/, where a POST gets a 403, so no publisher can forge a dead letter. Its subscribe protection must be the same as the target's path, so it has the same subscribers as the events in it. No target may receive a dead-letter path's events, so a dead letter is never delivered or given up again.

Guarantees #

Delivery is at least once. A replica that dies in the middle of a request leaves the delivery to another replica once its lease of 30 seconds runs out, and the target can receive the event twice. Use Wicket-Event-Id to tell the two apart. Deliveries are not in order: a retry waits while later events go out.

With -backend redis, every replica shares each target's queue, and a replica that stops lets its requests in flight finish for up to 15 seconds, then releases the rest for another replica to take at once. The queues live in Redis next to the event log, so a Redis that keeps nothing on disk loses the pending deliveries when it restarts. Run that Redis with maxmemory-policy noeviction: a queue's keys are the only ones wicket gives a TTL, so a volatile-* policy evicts them first. A target that leaves the configuration leaves its queue to expire an hour after its give_up_after passes without a write. With the memory backend, the queues belong to one replica and end with it.

Metrics #

With -metrics-address, wicket serves Prometheus metrics at /metrics, and /healthz for a probe of that address, on a listener of its own. Without it, wicket serves no metrics. The webhook address never serves /metrics, so a public webhook endpoint does not publish them:

wicket -configuration wicket.yaml -metrics-address :8081

Every path label is the nearest path in the configuration at or above the request's path, or (unconfigured) when no configured path is. A label taken from the request's own path would let anyone who can reach wicket add a series with each request. Each configured path's series, and each target's, start at zero when the configuration loads, so increase() sees a path's or a target's first failure.

Series Type Labels
wicket_build_info gauge version
wicket_webhooks_total counter path, outcome: published, verification_failed, invalid_json, misconfigured, publish_failed, too_large, loop, reserved, invalid_path, unreadable_body
wicket_publish_duration_seconds histogram
wicket_backend_errors_total counter operation: append, read, range
wicket_subscriptions gauge path
wicket_subscriptions_refused_total counter path, reason: unauthorized, review_unavailable, replay_unavailable
wicket_streams_closed_total counter reason: queue_full, review_unavailable
wicket_events_delivered_total counter path of the subscription
wicket_events_withheld_total counter path of the event
wicket_events_replayed_total counter
wicket_key_fetches_total counter outcome: success, failure
wicket_configuration_reloads_total counter outcome: success, failure
wicket_configuration_last_reload_successful gauge
wicket_deliveries_total counter path of the target, target, outcome: delivered, retried, gave_up, rejected, dropped, withheld
wicket_delivery_duration_seconds histogram target
wicket_delivery_pending gauge target
wicket_delivery_oldest_pending_age_seconds gauge target
  • misconfigured is a path whose verify names no method wicket has, which a configuration file cannot load with.
  • too_large is a POST whose body is over -max-body-bytes, or -max-unverified-body-bytes on a path that does not verify, which gets a 413. unreadable_body is a body that was cut short or did not arrive within 30 seconds, which gets a 400.
  • loop is a POST that carries Wicket-Event-Id, a delivery of wicket's that came back to it, which gets a 400. wicket reads _ as - and ignores case in the name. reserved is a POST to a path under wicket/, in any case, which gets a 403. invalid_path is a POST to a path with an empty, ., or .. segment, which gets a 400.
  • review_unavailable means wicket could not reach the API server for a TokenReview. replay_unavailable means it could not read the event log for a Last-Event-ID.
  • A stream closes for queue_full when its subscriber falls too far behind the live events. The subscriber reconnects and replays the rest.
  • dropped is an event that found its target's queue holding max_pending deliveries, or that would take it past max_pending_bytes. withheld is an event that a target wants but may not receive, when wicket publishes it or before an attempt.
  • wicket_delivery_pending is how many deliveries a target's queue holds, and wicket_delivery_oldest_pending_age_seconds how long ago the oldest of their events arrived. wicket reads both from the store, so every replica that shares a Redis reports the same value. Alert on max by (target) (...) of them, not on their sum.
  • wicket_configuration_reloads_total counts every load of the configuration file, the first one included. wicket_configuration_last_reload_successful is 0 while wicket serves an earlier configuration because the file no longer loads.

The Go runtime's and the process's own series are served as well.

On a cluster with the prometheus-operator, name the container port and scrape it with a PodMonitor:

# In the Deployment's container:
ports:
  - name: http
    containerPort: 8080
  - name: metrics
    containerPort: 8081
---
apiVersion: monitoring.coreos.com/v1
kind: PodMonitor
metadata:
  name: wicket
spec:
  selector:
    matchLabels:
      app: wicket
  podMetricsEndpoints:
    - port: metrics

Filtering #

Optional query params filter events on the subscribe side:

GET /github.com/chrisguidry/docketeer?filter=payload.ref:refs/heads/main

Simple dot-path equality matching. Multiple filters are AND'd.

Usage #

wicket                                                # listen on :8080, no configuration
wicket -address :9090                                 # custom listen address
wicket -configuration wicket.yaml                     # with webhook verification
wicket -buffer-size 5000                              # keep more events for replay
wicket -backend redis -redis-url redis://redis:6379   # share one log between replicas
wicket -metrics-address :8081                         # serve Prometheus metrics on a second port
wicket -max-body-bytes 1048576                        # refuse a verified POST body over 1 MiB with a 413

Building #

go build -o wicket .

Or with Docker:

docker build -t wicket .

Why the name "wicket"? #

A "wicket" is a small door or gate next to a larger one.