Repository navigation
webhook-gateway: apply the per-channel transform - #10093
Draft
cloud-on-prem wants to merge 24 commits into
Draft
cloud-on-prem wants to merge 24 commits into
cloud-on-prem wants to merge 24 commits into
Conversation
Config, Postgres store with first migration and declarative schema, health and metrics routers, and the binary entrypoint. No request handling yet; provider intake, management API and relay forwarding follow in later changes. Signed-off-by: Bill Gao <bgao@squareup.com> Signed-off-by: Shu Hui <shu@squareup.com>
Adds the private management API relays use to provision webhook
integrations on the ingress gateway, and the secret custody behind it.
- `PUT /v1/integrations/{id}`, `PUT …/secret`, `POST …/enable|disable`,
`GET /v1/operations/{id}`, authenticated with NIP-98 against a
configured relay pubkey allowlist.
- Every mutation carries a caller-chosen `operation_id` and target
`revision`, so relays can retry blindly: replays return the stored
response, stale revisions get 409 with the current state.
- Provider secrets are sealed with an AES-GCM keyring (rotatable,
self-describing ciphertext) and a secret rotation keeps the previous
value valid for a grace window.
Stacked on `wh-ingress-gw-spike`. Draft until the stack is exercised end
to end.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
Signed-off-by: Bill Gao <bgao@squareup.com>
Signed-off-by: Shu Hui <shu@squareup.com>
…line (#9928) Adds the public intake path `POST /webhooks/{integration_id}` with the GitHub adapter, plus the deliveries timeline on the management API. - Intake verifies the provider signature against every active secret, dedupes on the provider's delivery id, and stores the raw body as a `queued` delivery. Body size, timestamp skew and per-integration rate are bounded by config. - Provider adapters are a small trait (`verify`, `retained_headers`); GitHub implements `X-Hub-Signature-256` and derives `event.action` types. - `GET /v1/integrations/{id}/deliveries` pages the timeline by cursor, state and time, so a relay can show delivery status without touching payloads. Stacked on `ingress-gateway/management-api`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Bill Gao <bgao@squareup.com> Signed-off-by: Shu Hui <shu@squareup.com>
Adds the forwarder that turns queued deliveries into kind 20701 webhook-call events and posts them to the integration's community relay. - Deliveries are claimed with a lease (`FOR UPDATE SKIP LOCKED`) and signed with the gateway key; `created_at` is the receive time so every retry produces the same event id and the relay can dedupe. - Relay responses map to accepted, rejected or retry; retries back off 1s → 30m up to a configurable max age, after which the row is marked failed. Accepted rows drop the payload. - Relay submission goes over NIP-98 signed `POST /events`, with bounded response reads and a transport timeout. The relay-side admission of kind 20701 is a separate PR; until it lands, forwards to a real relay show up as rejected in the timeline. Stacked on `ingress-gateway/intake`. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Bill Gao <bgao@squareup.com> Signed-off-by: Shu Hui <shu@squareup.com>
Adds the PagerDuty v3 webhook adapter. - `X-PagerDuty-Signature` may list several `v1=<hex>` HMAC-SHA256 signatures during a provider-side rotation; any entry matching any active secret verifies. - Delivery id, event type and timestamp come from the body's `event` object. - The HMAC-any-secret and event-type checks move into the providers module so GitHub and later adapters share them. Targets `wh-ingress-gw-spike` directly now that #9929 is merged. Replaces #9930, which GitHub closed when its base branch was deleted. First adapter intended for an end-to-end spike. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Bill Gao <bgao@squareup.com> Signed-off-by: Shu Hui <shu@squareup.com>
…et rotation Address review feedback on the management API from #9927: - An applied operation now stores a fingerprint of the request (integration, revision, mutation kind and non-secret fields). Replaying an operation_id with a different request returns 409 operation_conflict instead of the old receipt, and a concurrent reuse on another integration that loses the primary-key race maps to the same 409 rather than a 503. - Secret rotation loads only secrets that still verify, retires the active ones with a single UPDATE, and the retention reaper now deletes retired secrets whose grace expired before the cutoff. - GET /v1/integrations/{id} reads the integration and its verifying secrets in one statement so a concurrent rotation cannot pair one revision with another's secret state. Signed-off-by: Bill Gao <bgao@squareup.com> Signed-off-by: Shu Hui <shu@squareup.com>
The relay should not have to know the gateway's webhook path convention to tell an admin where to point a provider. Every integration response, including idempotent replays and operation lookups, now carries delivery_url built from BUZZ_INGRESS_PUBLIC_SCHEME and the community host. Signed-off-by: Bill Gao <bgao@squareup.com> (cherry picked from commit 12cbb625ede0b42a77c1b1951f12fe20ba8597fa) Signed-off-by: Bill Gao <bgao@squareup.com>
### Why?
The design changed: webhook subscriptions and fan-out now belong to the
ingress gateway instead of the relay. The gateway owns subscription
configuration in its own database and sends each match to the community
relay as an ordinary kind-9 channel message.
### Summary
- New NIP-98 management API for channel subscriptions (`PUT`/`GET`,
`POST …/delete`, list), stored in `ingress_gateway_subscriptions`.
Writes are idempotent by revision; deletion leaves a tombstone and
cancels unsent messages. At most 50 per integration.
- CEL filter (bool) and message template (string) per subscription, in
the gateway's `filter` module, checked when the subscription is written.
- Fan-out stores one message per matching subscription in
`ingress_gateway_messages` and settles the delivery in the same
transaction, only if the subscriptions it evaluated are still the live
ones. The forwarder sends kind-9 messages from that outbox instead of
kind-20701 events.
- Each message is signed with a per-row tag and a timestamp from its
first claim. A retry is a relay duplicate; once that timestamp nears the
relay's ±15-minute window, the forwarder checks the relay for the
earlier send before re-signing.
- `MessageSigner` interface picks the identity that authors each message
and signs its NIP-98 request. The placeholder signs with the gateway key
and carries a **TODO**: the relay rejects these messages until a
per-community member identity exists.
- An integration's community host is now immutable, and the delivery
timeline reports per-delivery message counts.
- `store.rs` split into `store/{mod,memory,subscriptions}.rs`.
🤖 Generated with [Claude Code](https://claude.com/claude-code)
---------
Signed-off-by: Shu Hui <shu@squareup.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
### Why? So anyone can run the ingress gateway locally and send a webhook through it end to end, without needing someone to walk them through the setup. ### Summary - `crates/buzz-ingress-gateway/README.md`: what the gateway does, a step-by-step local run (relay, gateway, management calls, a signed GitHub webhook, checking the result), PagerDuty notes, current limits, and cleanup. - `examples/dev_nip98.rs`: a small dev helper that generates keys and signs the NIP-98 headers the management API requires. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Signed-off-by: Shu Hui <shu@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Renames the crate, binary, BUZZ_WEBHOOK_* configuration, metrics, Postgres tables and migration files. The secret-envelope AAD prefix is unchanged so existing ciphertexts keep decrypting. Signed-off-by: Bill Gao <bgao@squareup.com>
Nothing is deployed yet, so no stored secret has to keep decrypting under the old prefix. Signed-off-by: Bill Gao <bgao@squareup.com>
### Why? The webhook gateway design puts each webhook's configuration on the integration, owned by one channel: how deliveries find their channels, what message they post, its card data, and the key that groups related deliveries. Until now the only rendering setting, the message template, sat on each subscription. Subscribers could post different text for one webhook, and the other fields had nowhere to live. This change gives the integration a single config, so the routing, card and threading work that follows has a fixed place to read it from. ### Summary - `webhook_gateway_integrations` gains `delivery_mode`, `channel_expr`, `message_expr`, `message_data_expr` and `group_key_expr`; `webhook_gateway_subscriptions` loses `message_template`. - The integration `PUT` accepts and returns these fields, checks every expression when it's written, and includes the whole config in the operation fingerprint. The subscription `PUT` now accepts only a filter. - Fan-out renders the integration's `message_expr` once per delivery for every matching subscription. The other fields are stored and checked but not yet used in delivery. - The columns are added to migrations `0001` and `0003` directly, since the gateway schema isn't deployed anywhere yet. - Management tests moved to `management/tests.rs`, and the README covers the new fields. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: Shu Hui <shu@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
) ## Summary Add `update_message_and_reply_in_thread` as a webhook integration's `group_key_action`. The first delivery for a group creates the original channel message. Each subsequent delivery updates that message and posts the same rendered text as a reply, so the channel shows the latest state and the thread keeps a history of updates. After the relay accepts an edit, the gateway records the pending reply in the same outbox row. A worker can resume the reply after a restart, and later deliveries in the group wait their turn. Apply the gateway migrations and upgrade all workers before selecting the new action. ### Related issue Builds on #9997. ### Testing - Gateway tests passed, including the PostgreSQL store test for retrying a reply after a lost acknowledgement. Gateway formatting and Clippy passed. - Applied the migrations to a populated gateway database and verified that both existing actions and the new action were accepted. - Sent three grouped deliveries through a local gateway to a real relay. The relay stored one original message, two edits and two thread replies. Replaying the last webhook produced no extra event. - The repository-wide `just ci` run reported three failures in the `buzz-agent` Databricks OAuth tests. All 16 tests in that module passed on a serial rerun. - A second pre-push run passed the agent suite and failed one relay logging test, `composition_log_does_not_leak_issuer_url`. The complete relay binary suite passed on a serial rerun (31 passed, 1 ignored). All other pre-push checks passed, as did the desktop and web builds. The final draft push reused those check results on the same commit. --------- Signed-off-by: Shu Hui <shu@squareup.com> Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
…10012) ## Summary Allow a user to configure an individually owned webhook integration with a signed `PUT /v1/integrations/{id}`. The public route is enabled by mapping external HTTPS origins to trusted community relay hosts. It verifies the NIP-98 request, claims the proof in PostgreSQL to prevent reuse across gateway replicas, and reads the agent’s current signed kind-0 profile to verify NIP-OA ownership. The gateway saves the source-agent binding, settings, and encrypted provider secret atomically. A fresh proof can retry the same operation. Registrations keep their original delivery mode, and a user cannot take over a relay-created registration. Apply gateway migration 0002 before enabling the route. ### Related issue Follows #9997 and #10009 on the webhook gateway spike. ### Testing - All 67 gateway tests passed, including the PostgreSQL tests against a scratch database. The public route tests used signed requests and a relay fixture to exercise ownership, replay across gateway instances, registration conflicts, and delivery-mode changes. - Gateway Clippy, formatting and diff checks passed. - The repository-wide `just ci` run reported three Databricks OAuth failures in `buzz-agent`, also seen in #10009. All 16 tests in that module passed on a serial rerun on this commit. - All pre-push checks passed on this commit with serialized Rust tests, including the complete Rust, desktop and mobile pre-push suites. Signed-off-by: Shu Hui <shu@squareup.com>
) ## Caller-selected routing For a verified delivery in `caller_selects_channel` mode, evaluate the saved CEL `channel_expr` once. A non-nil channel UUID queues one message. A missing or invalid destination fails the delivery. Each queued message retains the bound source-agent public key. Before recovery or submission, the worker verifies that the selected signer has that key. Registrations without a bound agent fail closed. The current sender supports local validation with a configured source-agent key. Hosted per-agent signing remains a separate integration. ## Gateway schema The initial gateway migration creates the delivery and message tables with the caller-selected scheduling columns, source-agent key, pending-message constraint, and due indexes. The checked-in declarative schema describes the same tables. For local testing after an earlier spike build applied migration 0001, use a fresh gateway database because the migration checksum has changed. ## Verification - Gateway tests and Clippy passed. PostgreSQL tests exercised the production workers, compared the migrated queue tables with the declarative schema, and checked the previous worker claim and cancellation predicates. - Against a local gateway and relay, a signed GitHub webhook produced one signed kind-9 event in the selected private channel. Duplicate delivery produced no second event. A malformed target recorded a failed delivery. The smoke test seeded the agent binding in a disposable gateway database. - For a manual check, use a bound agent with permission to post, configure `channel_expr = payload.destination_channel_id` and `message_expr = payload.message`, then send the same signed GitHub delivery twice with one delivery ID. Verify one message in the target channel. Send a fresh delivery ID with an invalid target and verify a failed timeline entry. --------- Signed-off-by: Shu Hui <shu@squareup.com>
## Registration contract An individually owned source-agent signs a kind-0 profile with the integration marker and the owner's valid NIP-OA attestation. The owner sets the delivery mode in the NIP-98-authenticated registration request. A legacy profile mode tag no longer constrains the request. The gateway still rejects an attempt to change the saved mode, including at a newer revision. ## Verification The gateway package tests passed. The public PUT also passed against a disposable PostgreSQL database using the production HTTP router, signed HTTP proofs and a relay profile lookup fixture. The tests cover a marker-only profile, a conflicting legacy mode tag, missing or invalid ownership, retry, and attempted mode change. For a manual check, register a marker-only owned agent, retry the same body with a fresh HTTP proof, then send a higher revision for a different mode. The first two requests should return the same registration; the last should return HTTP 409 with `delivery_mode_immutable`. The full local `just ci` run passed with `RUST_TEST_THREADS=1`. All 69 gateway tests passed, including three PostgreSQL tests run on disposable databases. --------- Signed-off-by: Shu Hui <shu@squareup.com>
…0011) ## What A default-off spike: a receiving channel stores its own webhook subscription rule on the relay, and the gateway keeps a live copy of every rule and uses it at fan-out. - **The rule** is a NIP-AR channel artifact (kind 45010, type `webhook.subscription`), one per receiving channel and posting identity. Its content is `{"version":1,"filter":"<CEL>","transform":"<CEL>"}`; the transform is optional. - **The gateway**, with `BUZZ_WEBHOOK_CHANNEL_SUBSCRIPTIONS=true`, opens one authenticated WebSocket per posting identity and community, syncs that identity's rules, applies live changes, and resyncs after a reconnect or a membership change. - **Fan-out** uses those rules for integrations in channel-subscription mode. No relay code, migration or schema changes. The relay already stores, permissions and syncs this kind of record. ## With the setting off (the default) Nothing changes. No socket, task or relay read is started, and fan-out reads the gateway's stored subscriptions as before. The stored subscription table and its management routes are untouched. ## Things to know before turning it on - **It replaces, not merges.** For integrations in channel-subscription mode, relay rules replace the stored subscriptions. Caller-selects-channel integrations keep the existing path. Use the same value on every worker that shares an outbox. - **Anyone who can post in a channel can write its rule.** Restricting this to channel admins is left to the final config path. - **The transform is compiled and cached but not applied.** A rule with an invalid transform is skipped. - **One signing key.** Discovery uses the gateway's existing signing key, and that identity must be a member of the channel, including open channels. There is no federated-identity support on the socket. - **Edit cutoff.** A delivery that has finished evaluation when an edit arrives is still enqueued under the old rule. Messages already queued are not recalled by an edit, a removal, or a change of the setting. - **Resync cost.** A membership change, or the 15-minute refresh, triggers a full resync for that identity. Rules are unavailable during a reconnect, so affected deliveries are deferred and retried. Sustained membership churn can drive up to about four reconnects per second per active identity. - **Limits.** An identity with 1,000 or more channel memberships fails every sync (logged as an error; no paging). A connection unused for 30 minutes closes and reopens on the next delivery. - **`BUZZ_WEBHOOK_RELAY_PORT`** is a new optional setting for local plain-HTTP runs. When set, it also applies to the gateway's existing HTTP calls to the relay. ## Commits 1. The feature. 2. Fixes from review: a transient rule-compile failure now fails the sync and retries instead of settling a delivery with no messages; a live rule change invalidates the cached rules before recompiling; idle connections close; reconnect waits are jittered and only reset after a healthy period. 3. Follow-up: idle close and lookup share one lock; a repeated rule head leaves the cache untouched; a deliberate resync reconnects at the minimum wait. 4. Merges of this base branch (owner-signed integration configuration, then caller-selected channel routing). Caller-selected deliveries keep their direct path and never load stored subscriptions or relay rules; relay rules apply only to integrations in channel-subscription mode. 5. The owner-signed profile read uses the shared relay origin, so `BUZZ_WEBHOOK_RELAY_PORT` applies there too. 6. From review: install the ring crypto provider at startup. ring and aws-lc-rs are both compiled in, so the first `wss://` sync panicked. A test builds a TLS client config after startup and fails without the install. ## Verification At the current head (after both merges): - `cargo fmt --check`, `cargo clippy -p buzz-webhook-gateway --all-targets -- -D warnings`, `cargo test -p buzz-webhook-gateway`: pass. The three Postgres-gated tests also pass against a disposable Postgres. - Agent review of the merges and the follow-up: no blockers. - Agent-run against an isolated local relay and gateway with the setting on: - a saved rule delivers a matching webhook and skips a non-matching one; - editing the rule flips which webhook posts; - deleting the rule stops delivery; - removing the posting identity from the channel stops delivery, and re-adding it restores it. Human-tested at the head before the second merge, with the setting on, watching the channel in the desktop dev app: the same sequence (match, non-match, edit, delete, remove and re-add the posting identity) behaved as expected. At the pre-merge feature head, agents also checked: setting off (stored subscriptions deliver and skip as before); a webhook sent during a burst of membership changes is delivered in about two seconds; restarting only the relay (the gateway reconnects with growing waits and delivery resumes); an invalid rule is skipped and logged while a valid rule in another channel still delivers. Not exercised live: a `wss://` sync end to end (the local relay is plain `ws://`; the panic is covered by the new test), caller-selected routing with the setting on (it needs an owner registration; covered by this branch's tests and by review), and `BUZZ_WEBHOOK_RELAY_PORT` on the owner-signed profile read (verified in source). ## How to try it The gateway README has the headless walkthrough, including channel-subscription mode. `examples/webhook_subscription.rs` saves, updates and deletes a rule. buzz-review-completed --------- Signed-off-by: Prem Pillai <prem@squareup.com>
## Summary Use the registered source-agent as the author for both subscription and caller-selected webhook delivery. The signing target carries the agent pubkey and the forwarder checks the signer's key before publication. The spike uses person-attested registrations and ordinary kind 9 messages. The binding table can identify its owner by a person pubkey or a channel UUID. The person registration handler can update only a person-owned binding. Channel enrolment, authorization by channel admins and rich-card tags remain future work. ## Verification - Ran the gateway tests and Clippy with all targets. - Exercised both routing modes on disposable PostgreSQL databases. The subscription test rejects the owner's signing key, publishes using the agent key, and uses a seeded channel binding to verify the management and delivery paths. - Sent a signed webhook twice through the gateway to a local relay and read one kind 9 channel post with the expected agent pubkey and text. This used a fixture key and a seeded registration binding. The schema edit is in the spike's existing table definition and its matching declarative schema. Signed-off-by: Shu Hui <shu@squareup.com>
## Summary A registered webhook integration can now publish as its source agent while its private key stays with an operator-configured signing service. The gateway verifies the returned event and authenticates to the relay over WebSocket for publication, profile lookup, and channel subscription reads. Remote sessions support NIP-FI assertions and NIP-42 challenges. The gateway commits the signed event in the `signed_event` column on the existing `webhook_gateway_messages` row before publishing. A lost acknowledgement can then be retried with the same event ID. The existing local-key configuration continues to work. ### Related issue Follows #10055 on the webhook ingress spike. ### Testing - All 88 gateway, WebSocket client, and PostgreSQL tests passed. Targeted Clippy and formatting passed. - Ran the gateway against PostgreSQL, a real local relay, and the remote signing implementation with test identity fixtures. In both caller-selected and subscription-based routing, the owner registered the agent, duplicate webhook deliveries produced one plain kind 9 channel post, and the owner read back its signature and event ID. - Forced a failure after the signed event was saved. The gateway retried delivery with one message-signing call. A separate test dropped the relay acknowledgement and checked that the retry sent the identical event with fresh admission. - Staging workload authentication and hosted assertion issuance still need a staging test. - On the updated commit, the local pre-push run passed its gateway, relay, and desktop checks. Unrelated agent OAuth tests timed out in parallel. All 550 agent tests passed on a serial rerun. --------- Signed-off-by: Shu Hui <shu@squareup.com>
Signed-off-by: Bill Gao <bgao@squareup.com>
…eation Signed-off-by: Bill Gao <bgao@squareup.com>
Signed-off-by: Bill Gao <bgao@squareup.com>
The admin-token config tests took NIP_FI_ENV_LOCK (via env_guards) and then the tracing dispatch lock, while the audio shadow tests hold the tracing lock and then reach NIP_FI_ENV_LOCK through Config::for_test(). Running the lib suite in one process could deadlock on that pair. Acquire the tracing lock first in both tests so every path uses the same order. Signed-off-by: Bill Gao <bgao@squareup.com>
A channel's subscription rule can carry a transform next to its filter. It was compiled and cached but never run. It now renders the message text for that channel in place of the integration's message expression. The transform reads event and payload and must return a string. Grouping and message data stay the integration's. A transform that fails for one delivery fails that channel's message only. Generated with AI Signed-off-by: Prem Pillai <prem@squareup.com>
shu-hui-cash
force-pushed
the
wh-ingress-gw-spike
branch
from
December 2, 2026 02:57
07478e8 to
f6531cd
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
A channel's webhook subscription rule can carry an optional
transformnext to itsfilter. Until now the gateway compiled and cached it but never ran it. This applies it: the transform renders the message text for that channel, in place of the integration's message expression.Only relay-backed channel rules have a transform, so this only takes effect with
BUZZ_WEBHOOK_CHANNEL_SUBSCRIPTIONS=true. Stored subscriptions and caller-selects-channel integrations are unchanged.Design choices, open to change
This is a draft to react to. Each of these is a small change to reverse.
eventandpayload, the same variables as every other webhook expression. It does not see the integration's rendered message.Verification
Agent-run:
cargo fmt --check,cargo clippy -p buzz-webhook-gateway --all-targets -- -D warnings,cargo test -p buzz-webhook-gateway: pass (80 passed, 3 ignored that need a scratch Postgres).New test: three channels match one delivery. The one without a transform gets the integration's text, the one with a transform gets its own text, and the one whose transform fails gets a failed message; data and grouping are unchanged on the first two. The test fails when the transform is not applied.
Against a local relay and gateway with channel subscriptions on, one channel, one integration:
Not yet tested by a human.