Skip to content

Commit f6531cd

Browse files
committed
Use NIP-AR as the webhook channel subscription source (#10097)
## Summary Channel subscriptions now come exclusively from NIP-AR artifacts on the community relay. The gateway reads the posting agent’s current rules before fan-out. Caller-selected deliveries resolve their destination directly from the payload. This removes the private subscription management endpoints, the feature flag, and the subscription table from the undeployed spike’s initial SQL and declarative schema. Use a fresh gateway database when testing this revision. The message outbox still persists signed events for retries. ### Related work Follows #10011, which introduced relay-backed channel subscriptions. ### Testing - All 80 gateway tests passed, including three PostgreSQL tests run against separate fresh databases. The schema test checks that the subscription table is absent. - Local end-to-end tests exercised a real relay and a remote signer with test identity and custody fixtures. Both routing modes produced one signed kind-9 post after a duplicate webhook and a forced retry. - Editing and deleting a live NIP-AR artifact changed which subsequent deliveries matched. The retired private subscription PUT returned HTTP 404. - Full local CI stopped at three parallel OAuth tests in `buzz-agent`. The pre-push run also failed one `buzz-dev-mcp` path test. Both full library suites passed serially (550 and 78 tests). The push reused those results and the successful pre-push lanes. Signed-off-by: Shu Hui <shu@squareup.com>
1 parent afbaa59 commit f6531cd

23 files changed

Lines changed: 465 additions & 1718 deletions

‎crates/buzz-webhook-gateway/README.md‎

Lines changed: 29 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ provider ──POST /webhooks/{integration}──▶ intake: Host check, HMAC, d
1414
forwarder: sign message, reply or edit, POST {scheme}://{community_host}/events
1515
```
1616

17-
Trusted relays manage integrations, secrets and subscriptions through the
17+
Trusted relays manage integrations and secrets through the
1818
management API on the private listener. Callers sign each request with NIP-98
1919
using a key listed in `BUZZ_WEBHOOK_RELAY_PUBKEYS`. In production the relay
2020
makes these calls; locally you make them yourself.
@@ -128,8 +128,10 @@ done
128128

129129
### 4. Create the gateway database and start the gateway
130130

131-
The gateway keeps its own database. Migrations run with the admin role from
132-
`.env`; the gateway runs as a separate role with a generated password.
131+
Use a fresh gateway database for this undeployed spike. The initial migration
132+
has changed, so a database initialized from the earlier spike has a different
133+
SQLx checksum. Migrations run with the admin role from `.env`. The gateway
134+
runs as a separate role with a generated password.
133135

134136
```bash
135137
ADMIN_URL=$(sed -n 's/^DATABASE_URL=//p' .env | sed 's#/[^/]*$#/buzz_gateway#')
@@ -164,9 +166,13 @@ CHANNEL=$(BUZZ_PRIVATE_KEY=$(cat $GW/owner.sk) $BUZZ --format json channels crea
164166
echo $CHANNEL
165167
```
166168

167-
Messages are signed by the gateway's key. The relay lets anyone in the
168-
community post to an open channel; for a private channel, add the gateway's
169-
public key as a member first.
169+
Add the posting key to the channel so the gateway discovers its subscription.
170+
171+
```bash
172+
AGENT=$(cat "$GW/gateway.pk")
173+
OWNER=$(cat "$GW/owner.sk")
174+
BUZZ_PRIVATE_KEY="$OWNER" "$BUZZ" channels add-member --channel "$CHANNEL" --pubkey "$AGENT" --role bot
175+
```
170176

171177
### 6. Create an integration, its secret and a subscription
172178

@@ -191,16 +197,15 @@ mgmt PUT /v1/integrations/$INTEGRATION "$(jq -nc --arg op $(uuidgen | tr A-Z a-z
191197
message_expr: "\"PR #\" + string(payload.number) + \" opened: \" + payload.pull_request.title"}')"
192198
mgmt PUT /v1/integrations/$INTEGRATION/secret \
193199
"{\"operation_id\":\"$(uuidgen | tr A-Z a-z)\",\"revision\":2,\"secret\":\"$(cat $GW/github.secret)\",\"grace_seconds\":0}"
194-
mgmt PUT /v1/integrations/$INTEGRATION/subscriptions/$(uuidgen | tr A-Z a-z) "$(jq -nc --arg c $CHANNEL '{
195-
revision: 1, channel_id: $c,
196-
filter: "event.type == \"pull_request.opened\""}')"
200+
BUZZ_PRIVATE_KEY="$OWNER" ./target/debug/examples/webhook_subscription \
201+
"$BUZZ_RELAY_URL" "$CHANNEL" "$AGENT" create 'event.type == "pull_request.opened"'
197202
```
198203

199204
The integration's `message_expr` and each subscription's `filter` are CEL
200205
over `event` (`provider` and `type`, for example `pull_request.opened`) and
201-
`payload` (the webhook body). Both are optional. Without a filter, every
202-
delivery matches. Every matching subscription posts the integration's message;
203-
without a message expression, it is `<provider>: <type>`.
206+
`payload` (the webhook body). Use `true` as the artifact filter to match every
207+
delivery. Each matching channel receives the integration's message. The default
208+
message is `<provider>: <type>`.
204209

205210
An integration also stores `delivery_mode` (`channel_subscriptions`, the
206211
default, or `caller_selects_channel`, which requires `channel_expr`),
@@ -301,12 +306,13 @@ docker exec buzz-postgres psql -U buzz -d buzz_gateway \
301306
-c "SELECT subscription_id, state, attempts, content, last_error FROM webhook_gateway_messages"
302307
```
303308

304-
## Channel-owned subscriptions (experimental)
309+
## Channel-owned subscriptions
305310

306-
Set `BUZZ_WEBHOOK_CHANNEL_SUBSCRIPTIONS=true` when starting the gateway to
307-
route integrations in `channel_subscriptions` mode using channel artifacts.
308-
The default uses gateway-managed subscriptions. A registered source agent reads
309-
its own channel subscriptions.
311+
In `channel_subscriptions` mode, the gateway syncs the current NIP-AR
312+
artifacts from the posting agent's channels. It caches their rules in memory
313+
and rebuilds the cache from the relay after a restart. A delivery waits for a
314+
ready snapshot before fan-out. Once a message is queued, its outbox row
315+
survives rule changes and gateway restarts.
310316

311317
The `webhook.subscription` artifact uses [NIP-AR](../../docs/nips/NIP-AR.md)
312318
kind 45010, the receiving channel as `h`, and the posting agent's lowercase
@@ -323,20 +329,13 @@ its record, including other community members in an open channel.
323329
- Run the relay with `BUZZ_BIND_ADDR=127.0.0.1:18090`,
324330
`RELAY_URL=ws://localhost:18090` and a free `BUZZ_HEALTH_PORT`
325331
such as 18080. Keep the relay in a separate terminal to restart it later.
326-
- Start the gateway with `BUZZ_WEBHOOK_RELAY_PORT=18090`,
327-
`BUZZ_WEBHOOK_CHANNEL_SUBSCRIPTIONS=true` and
332+
- Start the gateway with `BUZZ_WEBHOOK_RELAY_PORT=18090` and
328333
`RUST_LOG=buzz_webhook_gateway=debug`. Set
329334
`BUZZ_RELAY_URL=http://localhost:18090` for CLI commands.
330-
- Add the posting identity to the channel after creating it. Create the
331-
integration and secret, then use the artifact example below in place
332-
of the management API subscription call.
335+
- In step 6, create the integration and secret. Defer the artifact creation
336+
until the first webhook below has completed.
333337

334338
```bash
335-
AGENT=$(cat "$GW/gateway.pk")
336-
OWNER=$(cat "$GW/owner.sk")
337-
BUZZ_PRIVATE_KEY="$OWNER" "$BUZZ" channels add-member \
338-
--channel "$CHANNEL" --pubkey "$AGENT" --role bot
339-
340339
artifact() {
341340
BUZZ_PRIVATE_KEY="$OWNER" ./target/debug/examples/webhook_subscription \
342341
"$BUZZ_RELAY_URL" "$CHANNEL" "$AGENT" "$@"
@@ -403,11 +402,9 @@ its record, including other community members in an open channel.
403402
4. Stop the relay from its terminal and restart the same command with the
404403
same database and key. Keep the gateway running. After a new sync reports
405404
one rule, run `webhook closed after-relay-restart` and expect 1.
406-
5. Restart the gateway with the same keyring and
407-
`BUZZ_WEBHOOK_CHANNEL_SUBSCRIPTIONS=false`. Create the management API
408-
subscription from step 6 and send `webhook opened stored-matching`.
409-
Expect 1 for that request and 0 for `webhook closed stored-nonmatching`,
410-
even though the artifact still matches closed pull requests.
405+
5. Restart the gateway with the same keyring, then send
406+
`webhook closed after-gateway-restart`. Expect one message after the gateway
407+
rebuilds its subscriptions from the relay.
411408

412409
### Other providers
413410

‎crates/buzz-webhook-gateway/migrations/0001_webhook_gateway.sql‎

Lines changed: 0 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -63,19 +63,6 @@ CREATE INDEX webhook_gateway_deliveries_retention ON webhook_gateway_deliveries
6363
CREATE INDEX webhook_gateway_deliveries_pending_order ON webhook_gateway_deliveries (integration_id, received_at, delivery_id) WHERE state = 'queued';
6464
CREATE INDEX webhook_gateway_deliveries_routing_due ON webhook_gateway_deliveries (COALESCE(next_attempt_at, caller_due_at)) WHERE state = 'queued';
6565

66-
CREATE TABLE webhook_gateway_subscriptions (
67-
id UUID PRIMARY KEY,
68-
integration_id UUID NOT NULL,
69-
channel_id UUID NOT NULL,
70-
filter TEXT CHECK (filter IS NULL OR length(filter) BETWEEN 1 AND 4096),
71-
revision BIGINT NOT NULL CHECK (revision > 0),
72-
deleted_at TIMESTAMPTZ,
73-
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
74-
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
75-
);
76-
CREATE INDEX webhook_gateway_subscriptions_live ON webhook_gateway_subscriptions (integration_id) WHERE deleted_at IS NULL;
77-
CREATE INDEX webhook_gateway_subscriptions_tombstones ON webhook_gateway_subscriptions (deleted_at) WHERE deleted_at IS NOT NULL;
78-
7966
CREATE TABLE webhook_gateway_messages (
8067
integration_id UUID NOT NULL,
8168
delivery_id TEXT NOT NULL CHECK (length(delivery_id) BETWEEN 1 AND 256),
@@ -100,7 +87,6 @@ CREATE TABLE webhook_gateway_messages (
10087
PRIMARY KEY (integration_id, delivery_id, subscription_id)
10188
);
10289
CREATE INDEX webhook_gateway_messages_due ON webhook_gateway_messages (next_attempt_at) WHERE state = 'queued';
103-
CREATE INDEX webhook_gateway_messages_subscription ON webhook_gateway_messages (subscription_id) WHERE state = 'queued';
10490
CREATE INDEX webhook_gateway_messages_retention ON webhook_gateway_messages (completed_at) WHERE state <> 'queued';
10591
CREATE INDEX webhook_gateway_messages_group_pending ON webhook_gateway_messages (group_id, group_position) WHERE group_id IS NOT NULL AND state = 'queued';
10692
CREATE INDEX webhook_gateway_messages_routing_due ON webhook_gateway_messages (COALESCE(next_attempt_at, caller_due_at)) WHERE state = 'queued';

‎crates/buzz-webhook-gateway/schema/schema.sql‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,6 @@
1010
\i tables/public/webhook_gateway_integration_secrets.sql
1111
\i tables/public/webhook_gateway_applied_operations.sql
1212
\i tables/public/webhook_gateway_deliveries.sql
13-
\i tables/public/webhook_gateway_subscriptions.sql
1413
\i tables/public/webhook_gateway_messages.sql
1514
\i tables/public/webhook_gateway_message_groups.sql
1615
\i tables/public/webhook_gateway_user_proofs.sql

‎crates/buzz-webhook-gateway/schema/tables/public/webhook_gateway_messages.sql‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,6 @@ CREATE TABLE webhook_gateway_messages (
2323
PRIMARY KEY (integration_id, delivery_id, subscription_id)
2424
);
2525
CREATE INDEX webhook_gateway_messages_due ON webhook_gateway_messages (next_attempt_at) WHERE state = 'queued';
26-
CREATE INDEX webhook_gateway_messages_subscription ON webhook_gateway_messages (subscription_id) WHERE state = 'queued';
2726
CREATE INDEX webhook_gateway_messages_retention ON webhook_gateway_messages (completed_at) WHERE state <> 'queued';
2827
CREATE INDEX webhook_gateway_messages_group_pending ON webhook_gateway_messages (group_id, group_position) WHERE group_id IS NOT NULL AND state = 'queued';
2928
CREATE INDEX webhook_gateway_messages_routing_due ON webhook_gateway_messages (COALESCE(next_attempt_at, caller_due_at)) WHERE state = 'queued';

‎crates/buzz-webhook-gateway/schema/tables/public/webhook_gateway_subscriptions.sql‎

Lines changed: 0 additions & 12 deletions
This file was deleted.

‎crates/buzz-webhook-gateway/src/channel_subscriptions.rs‎

Lines changed: 81 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -185,8 +185,21 @@ impl ChannelSubscriptions {
185185
sessions: Arc::new(Mutex::new(HashMap::new())),
186186
}
187187
}
188+
}
189+
190+
#[async_trait::async_trait]
191+
pub(crate) trait SubscriptionSource: Send + Sync + 'static {
192+
async fn snapshot(
193+
&self,
194+
host: &str,
195+
integration: Uuid,
196+
bound_agent: Option<PublicKey>,
197+
) -> Result<Snapshot, SignerError>;
198+
}
188199

189-
pub(crate) async fn snapshot(
200+
#[async_trait::async_trait]
201+
impl SubscriptionSource for ChannelSubscriptions {
202+
async fn snapshot(
190203
&self,
191204
host: &str,
192205
integration: Uuid,
@@ -539,8 +552,75 @@ async fn read_snapshot(
539552
}
540553
}
541554

555+
#[cfg(test)]
556+
pub(crate) mod fixtures {
557+
use super::*;
558+
use nostr::{EventBuilder, Keys, Kind, Tag};
559+
560+
#[derive(Default)]
561+
pub(crate) struct TestSubscriptions(HashMap<Uuid, RuleSet>);
562+
563+
impl TestSubscriptions {
564+
pub(crate) async fn add(
565+
&mut self,
566+
integration: Uuid,
567+
agent: PublicKey,
568+
channel: Uuid,
569+
filter: &str,
570+
) -> Uuid {
571+
let rules = self.0.entry(integration).or_default();
572+
assert!(rules
573+
.apply(
574+
test_head(channel, agent, filter),
575+
&BTreeSet::from([channel]),
576+
agent
577+
)
578+
.await
579+
.unwrap());
580+
subscription_artifact::id(channel, agent)
581+
}
582+
}
583+
584+
#[async_trait::async_trait]
585+
impl SubscriptionSource for TestSubscriptions {
586+
async fn snapshot(
587+
&self,
588+
_: &str,
589+
integration: Uuid,
590+
_: Option<PublicKey>,
591+
) -> Result<Snapshot, SignerError> {
592+
let rules = Arc::new(
593+
self.0
594+
.get(&integration)
595+
.expect("unexpected relay subscription lookup")
596+
.clone(),
597+
);
598+
let (_, receiver) = watch::channel(Some(rules.clone()));
599+
Ok(Snapshot { rules, receiver })
600+
}
601+
}
602+
603+
pub(super) fn test_head(channel: Uuid, agent: PublicKey, filter: &str) -> Box<Event> {
604+
Box::new(
605+
EventBuilder::new(
606+
Kind::Custom(subscription_artifact::KIND),
607+
json!({"version": 1, "filter": filter}).to_string(),
608+
)
609+
.tags([
610+
Tag::parse(["d", &subscription_artifact::id(channel, agent).to_string()]).unwrap(),
611+
Tag::parse(["h", &channel.to_string()]).unwrap(),
612+
Tag::parse(["type", subscription_artifact::RECORD_TYPE]).unwrap(),
613+
Tag::parse(["p", &agent.to_hex()]).unwrap(),
614+
])
615+
.sign_with_keys(&Keys::generate())
616+
.unwrap(),
617+
)
618+
}
619+
}
620+
542621
#[cfg(test)]
543622
mod tests {
623+
use super::fixtures::test_head;
544624
use super::*;
545625
use crate::{fanout::BUDGET, filter::Delivery};
546626
use nostr::{EventBuilder, Keys, Kind, Tag};
@@ -622,23 +702,6 @@ mod tests {
622702
assert_eq!(rules.rules().count(), 0);
623703
}
624704

625-
fn test_head(channel: Uuid, agent: PublicKey, filter: &str) -> Box<Event> {
626-
Box::new(
627-
EventBuilder::new(
628-
Kind::Custom(subscription_artifact::KIND),
629-
json!({"version": 1, "filter": filter}).to_string(),
630-
)
631-
.tags([
632-
Tag::parse(["d", &subscription_artifact::id(channel, agent).to_string()]).unwrap(),
633-
Tag::parse(["h", &channel.to_string()]).unwrap(),
634-
Tag::parse(["type", subscription_artifact::RECORD_TYPE]).unwrap(),
635-
Tag::parse(["p", &agent.to_hex()]).unwrap(),
636-
])
637-
.sign_with_keys(&Keys::generate())
638-
.unwrap(),
639-
)
640-
}
641-
642705
#[tokio::test]
643706
async fn transient_compilation_failure_does_not_cache_the_head() {
644707
let agent = Keys::generate().public_key();

‎crates/buzz-webhook-gateway/src/config.rs‎

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,6 @@ pub struct Config {
3838
pub relay_pubkeys: Vec<PublicKey>,
3939
/// `https` in production; `http` only for local development.
4040
pub relay_scheme: RelayScheme,
41-
/// Use channel-owned relay artifacts for subscription fan-out.
42-
pub channel_subscriptions: bool,
4341
/// External management HTTPS origins mapped to trusted community relay hosts.
4442
pub management_origins: HashMap<String, String>,
4543
/// Scheme of the URL providers deliver to, reported as `delivery_url`.
@@ -191,14 +189,6 @@ impl Config {
191189
secret_keyring,
192190
relay_pubkeys,
193191
relay_scheme,
194-
channel_subscriptions: match env
195-
.get("BUZZ_WEBHOOK_CHANNEL_SUBSCRIPTIONS")
196-
.map(String::as_str)
197-
{
198-
None | Some("false") => false,
199-
Some("true") => true,
200-
Some(_) => return Err(ConfigError::Invalid("BUZZ_WEBHOOK_CHANNEL_SUBSCRIPTIONS")),
201-
},
202192
public_scheme,
203193
max_body_bytes: bounded_positive(env, "BUZZ_WEBHOOK_MAX_BODY_BYTES", 1 << 20, 16 << 20)?
204194
as usize,
@@ -329,7 +319,6 @@ mod tests {
329319
assert_eq!(c.listen_addr.port(), 8080);
330320
assert_eq!(c.private_addr.port(), 8081);
331321
assert_eq!(c.relay_scheme, RelayScheme::Https);
332-
assert!(!c.channel_subscriptions);
333322
assert_eq!(c.public_scheme, RelayScheme::Https);
334323
assert_eq!(c.max_body_bytes, 1 << 20);
335324
assert_eq!(c.timestamp_tolerance_seconds, 300);

0 commit comments

Comments
 (0)