Skip to content

Commit 781d395

Browse files
authored
feat(push): support configurable HTTP(S) delivery URLs (#7877)
The relay can use a configurable HTTP(S) gateway delivery URL and signs the same URL it sends. The gateway verifies NIP-98 against the received request URL, including authority, port, path and query. App Attest, scoped grants, replay checks and delivery quotas are unchanged. Forwarding proxies must preserve Host and supply the original request scheme through X-Forwarded-Proto. The NIP relay-delivery wording now defines the configured HTTP(S) URL as the signed URL and labels the public URL as an example. <!-- buzz-review-completed --> --------- Signed-off-by: Tom Brow <[email protected]>
1 parent 02c6309 commit 781d395

17 files changed

Lines changed: 530 additions & 159 deletions

File tree

‎.env.example‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -75,7 +75,7 @@ RELAY_URL=ws://localhost:3000
7575
# BUZZ_WEB_DIR=./web/dist
7676

7777
# NIP-PL mobile push is an explicit deployment opt-in. A gateway URL alone
78-
# never enables it. When enabled, the exact HTTPS delivery URL is required.
78+
# never enables it. When enabled, the exact HTTP(S) delivery URL is required.
7979
BUZZ_PUSH_ENABLED=false
8080
BUZZ_PUSH_GATEWAY_DELIVERY_URL=https://push.buzz.xyz/v1/deliveries/apns
8181

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

Lines changed: 19 additions & 90 deletions
Original file line numberDiff line numberDiff line change
@@ -38,8 +38,6 @@ pub struct KeyConfig {
3838
pub struct Config {
3939
pub bind_addr: SocketAddr,
4040
pub health_addr: SocketAddr,
41-
/// External gateway origin, delivery URL, and registered transcript audiences.
42-
pub gateway_urls: GatewayUrls,
4341
pub max_grant_lifetime_seconds: i64,
4442
pub max_installation_lifetime_seconds: i64,
4543
pub endpoint_quota_window_seconds: i64,
@@ -55,53 +53,18 @@ pub struct Config {
5553
pub token_keys: Vec<KeyConfig>,
5654
}
5755

58-
/// Gateway transport URLs and registered NIP-PL v1 transcript audiences.
59-
#[derive(Debug, Clone)]
60-
pub struct GatewayUrls {
61-
/// External HTTPS origin serving the gateway.
62-
pub origin: url::Url,
63-
/// Exact NIP-98 delivery endpoint used by relays.
64-
pub delivery: url::Url,
65-
/// App Attest audience for installation enrollment.
66-
pub enroll_audience: String,
67-
/// App Attest audience for relay delegation.
68-
pub delegate_audience: String,
69-
/// App Attest audience for endpoint rotation.
70-
pub rotate_endpoint_audience: String,
71-
/// App Attest audience for delegation revocation.
72-
pub revoke_delegation_audience: String,
73-
/// App Attest audience for installation revocation.
74-
pub revoke_installation_audience: String,
75-
}
56+
// Registered NIP-PL v1 App Attest audiences are protocol constants, not routing URLs.
57+
/// Fixed NIP-PL v1 App Attest audience for installation enrollment.
58+
pub const ENROLL_AUDIENCE: &str = "https://push.buzz.xyz/v1/installations";
59+
/// Fixed NIP-PL v1 App Attest audience for creating a delegation.
60+
pub const DELEGATE_AUDIENCE: &str = "https://push.buzz.xyz/v1/delegations";
61+
/// Fixed NIP-PL v1 App Attest audience for rotating an installation endpoint.
62+
pub const ROTATE_ENDPOINT_AUDIENCE: &str = "https://push.buzz.xyz/v1/installations/endpoint";
63+
/// Fixed NIP-PL v1 App Attest audience for revoking a delegation.
64+
pub const REVOKE_DELEGATION_AUDIENCE: &str = "https://push.buzz.xyz/v1/delegations/revoke";
65+
/// Fixed NIP-PL v1 App Attest audience for revoking an installation.
66+
pub const REVOKE_INSTALLATION_AUDIENCE: &str = "https://push.buzz.xyz/v1/installations/revoke";
7667

77-
impl GatewayUrls {
78-
pub(crate) fn from_origin(origin: url::Url) -> Result<Self, ConfigError> {
79-
let derive = |path: &str| {
80-
origin
81-
.join(path)
82-
.map_err(|_| ConfigError::Invalid("BUZZ_PUSH_GATEWAY_ORIGIN"))
83-
};
84-
let delivery = derive("v1/deliveries/apns")?;
85-
// NIP-PL v1 registers these exact audience strings. The configurable
86-
// origin controls transport only; changing transcript bytes requires
87-
// a separately versioned protocol profile.
88-
let enroll_audience = "https://push.buzz.xyz/v1/installations".to_owned();
89-
let delegate_audience = "https://push.buzz.xyz/v1/delegations".to_owned();
90-
let rotate_endpoint_audience = "https://push.buzz.xyz/v1/installations/endpoint".to_owned();
91-
let revoke_delegation_audience = "https://push.buzz.xyz/v1/delegations/revoke".to_owned();
92-
let revoke_installation_audience =
93-
"https://push.buzz.xyz/v1/installations/revoke".to_owned();
94-
Ok(Self {
95-
origin,
96-
delivery,
97-
enroll_audience,
98-
delegate_audience,
99-
rotate_endpoint_audience,
100-
revoke_delegation_audience,
101-
revoke_installation_audience,
102-
})
103-
}
104-
}
10568
#[derive(Debug, Error)]
10669
pub enum ConfigError {
10770
#[error("missing required environment variable {0}")]
@@ -203,21 +166,6 @@ impl Config {
203166
}) {
204167
return Err(ConfigError::Invalid("BUZZ_PUSH_TOKEN_KEYS"));
205168
}
206-
let gateway_origin = req(e, "BUZZ_PUSH_GATEWAY_ORIGIN")?
207-
.parse::<url::Url>()
208-
.map_err(|_| ConfigError::Invalid("BUZZ_PUSH_GATEWAY_ORIGIN"))?;
209-
if gateway_origin.scheme() != "https"
210-
|| gateway_origin.host().is_none()
211-
|| gateway_origin.port().is_some()
212-
|| gateway_origin.path() != "/"
213-
|| gateway_origin.query().is_some()
214-
|| gateway_origin.fragment().is_some()
215-
|| !gateway_origin.username().is_empty()
216-
|| gateway_origin.password().is_some()
217-
{
218-
return Err(ConfigError::Invalid("BUZZ_PUSH_GATEWAY_ORIGIN"));
219-
}
220-
let gateway_urls = GatewayUrls::from_origin(gateway_origin)?;
221169
let max_grant_lifetime_seconds = req(e, "BUZZ_PUSH_MAX_GRANT_LIFETIME_SECONDS")?
222170
.parse::<i64>()
223171
.ok()
@@ -263,7 +211,6 @@ impl Config {
263211
Ok(Self {
264212
bind_addr,
265213
health_addr,
266-
gateway_urls,
267214
max_grant_lifetime_seconds,
268215
max_installation_lifetime_seconds,
269216
endpoint_quota_window_seconds,
@@ -339,10 +286,6 @@ mod tests {
339286
STANDARD.encode([4; 32])
340287
),
341288
),
342-
(
343-
"BUZZ_PUSH_GATEWAY_ORIGIN".into(),
344-
"https://push.example".into(),
345-
),
346289
(
347290
"BUZZ_PUSH_MAX_GRANT_LIFETIME_SECONDS".into(),
348291
"2592000".into(),
@@ -399,31 +342,21 @@ mod tests {
399342
}
400343

401344
#[test]
402-
fn gateway_transport_uses_configured_origin_and_transcript_audiences_stay_registered() {
403-
let config = Config::from_map(&base()).unwrap();
404-
assert_eq!(config.gateway_urls.origin.as_str(), "https://push.example/");
405-
assert_eq!(
406-
config.gateway_urls.delivery.as_str(),
407-
"https://push.example/v1/deliveries/apns"
408-
);
409-
assert_eq!(
410-
config.gateway_urls.enroll_audience,
411-
"https://push.buzz.xyz/v1/installations"
412-
);
413-
assert_eq!(
414-
config.gateway_urls.delegate_audience,
415-
"https://push.buzz.xyz/v1/delegations"
416-
);
345+
fn startup_needs_no_origin_and_transcript_audiences_stay_registered() {
346+
assert!(!base().contains_key("BUZZ_PUSH_GATEWAY_ORIGIN"));
347+
Config::from_map(&base()).unwrap();
348+
assert_eq!(ENROLL_AUDIENCE, "https://push.buzz.xyz/v1/installations");
349+
assert_eq!(DELEGATE_AUDIENCE, "https://push.buzz.xyz/v1/delegations");
417350
assert_eq!(
418-
config.gateway_urls.rotate_endpoint_audience,
351+
ROTATE_ENDPOINT_AUDIENCE,
419352
"https://push.buzz.xyz/v1/installations/endpoint"
420353
);
421354
assert_eq!(
422-
config.gateway_urls.revoke_delegation_audience,
355+
REVOKE_DELEGATION_AUDIENCE,
423356
"https://push.buzz.xyz/v1/delegations/revoke"
424357
);
425358
assert_eq!(
426-
config.gateway_urls.revoke_installation_audience,
359+
REVOKE_INSTALLATION_AUDIENCE,
427360
"https://push.buzz.xyz/v1/installations/revoke"
428361
);
429362
}
@@ -441,10 +374,6 @@ mod tests {
441374
#[test]
442375
fn malformed_security_configuration_fails_startup() {
443376
for (key, value) in [
444-
("BUZZ_PUSH_GATEWAY_ORIGIN", "http://push.example"),
445-
("BUZZ_PUSH_GATEWAY_ORIGIN", "https://push.example/path"),
446-
("BUZZ_PUSH_GATEWAY_ORIGIN", "https://push.example?token=x"),
447-
("BUZZ_PUSH_GATEWAY_ORIGIN", "https://[email protected]"),
448377
("BUZZ_PUSH_DOGFOOD_APP_ATTEST_APP_ID", ""),
449378
("BUZZ_PUSH_DOGFOOD_APNS_ENVIRONMENT", "staging"),
450379
("BUZZ_PUSH_MAX_GRANT_LIFETIME_SECONDS", "0"),

‎crates/buzz-push-gateway/src/http.rs‎

Lines changed: 60 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,17 @@ use crate::{
55
authority::{
66
AuthorityError, AuthorityStore, Challenge, Delegation, DeliveryDisposition, NewInstallation,
77
},
8-
config::GatewayUrls,
8+
config::{
9+
DELEGATE_AUDIENCE, ENROLL_AUDIENCE, REVOKE_DELEGATION_AUDIENCE,
10+
REVOKE_INSTALLATION_AUDIENCE, ROTATE_ENDPOINT_AUDIENCE,
11+
},
912
grant::GrantKeyring,
1013
model::*,
1114
token::TokenKeyring,
1215
};
1316
use axum::{
1417
body::Bytes,
15-
extract::State,
18+
extract::{OriginalUri, State},
1619
http::{HeaderMap, StatusCode},
1720
response::{IntoResponse, Response},
1821
routing::{get, post},
@@ -21,7 +24,7 @@ use axum::{
2124
use base64::{engine::general_purpose::STANDARD, Engine as _};
2225
use nostr::{
2326
nips::nip98::{verify_auth_header, HttpMethod},
24-
Event, JsonUtil, Timestamp,
27+
Event, JsonUtil, TagKind, TagStandard, Timestamp,
2528
};
2629
use std::{
2730
sync::{
@@ -47,8 +50,6 @@ pub struct AppState {
4750
/// Server-owned dogfood application identity and APNs transport. The wire
4851
/// profile selector is fixed and App Attest verifies the configured app ID.
4952
pub profile: Arc<ProfileRuntime>,
50-
/// Security-sensitive endpoints and audiences derived from one gateway origin.
51-
pub gateway_urls: Arc<GatewayUrls>,
5253
pub max_grant_lifetime_seconds: i64,
5354
pub max_installation_lifetime_seconds: i64,
5455
pub endpoint_quota_window_seconds: i64,
@@ -71,14 +72,46 @@ fn valid_relay_pubkey(v: &str) -> bool {
7172
&& v.bytes()
7273
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
7374
}
74-
fn auth_event_id(header: &str) -> Option<String> {
75+
pub(crate) const DELIVERY_PATH: &str = "/v1/deliveries/apns";
76+
77+
// Keep preliminary decoding bounded to the pinned nostr verifier's limits.
78+
fn delivery_auth(header: &str, body: &[u8]) -> Option<(String, String)> {
7579
let (prefix, encoded) = header.split_once(' ')?;
76-
if prefix != "Nostr" {
80+
const MAX_EVENT_BYTES: usize = 64 * 1024;
81+
const MAX_ENCODED_BYTES: usize = MAX_EVENT_BYTES.div_ceil(3) * 4;
82+
if prefix != "Nostr" || encoded.len() > MAX_ENCODED_BYTES {
7783
return None;
7884
}
79-
Event::from_json(STANDARD.decode(encoded).ok()?)
80-
.ok()
81-
.map(|e| e.id.to_hex())
85+
let decoded = STANDARD.decode(encoded).ok()?;
86+
if decoded.len() > MAX_EVENT_BYTES {
87+
return None;
88+
}
89+
let event = Event::from_json(decoded).ok()?;
90+
let signed_url = match event.tags.find_standardized(TagKind::u())? {
91+
TagStandard::AbsoluteURL(url) => url,
92+
_ => return None,
93+
};
94+
if !matches!(signed_url.scheme(), "http" | "https")
95+
|| signed_url.path() != DELIVERY_PATH
96+
|| signed_url.query().is_some()
97+
|| signed_url.fragment().is_some()
98+
|| !signed_url.username().is_empty()
99+
|| signed_url.password().is_some()
100+
{
101+
return None;
102+
}
103+
// This delivery profile binds method and path, not request origin. Passing
104+
// the validated signed URL retains the library's kind, method, timestamp,
105+
// body hash, event ID and signature checks without reconstructing a URL.
106+
let relay = verify_auth_header(
107+
header,
108+
signed_url,
109+
HttpMethod::POST,
110+
Timestamp::now(),
111+
Some(body),
112+
)
113+
.ok()?;
114+
Some((event.id.to_hex(), relay.to_hex()))
82115
}
83116

84117
fn decode_challenge(value: &str) -> Option<[u8; 32]> {
@@ -192,7 +225,7 @@ async fn enroll(State(s): State<AppState>, body: Bytes) -> Response {
192225
};
193226
let t = EnrollTranscript {
194227
v: r.v,
195-
audience: &s.gateway_urls.enroll_audience,
228+
audience: ENROLL_AUDIENCE,
196229
challenge_id: r.challenge_id,
197230
challenge: &r.challenge,
198231
key_id: &r.key_id,
@@ -366,7 +399,7 @@ async fn delegate(State(s): State<AppState>, body: Bytes) -> Response {
366399
}
367400
let t = DelegateTranscript {
368401
v: r.v,
369-
audience: &s.gateway_urls.delegate_audience,
402+
audience: DELEGATE_AUDIENCE,
370403
challenge_id: r.challenge_id,
371404
challenge: &r.challenge,
372405
installation_handle: r.installation_handle,
@@ -463,7 +496,7 @@ async fn rotate_endpoint(State(s): State<AppState>, body: Bytes) -> Response {
463496
};
464497
let t = RotateTranscript {
465498
v: r.v,
466-
audience: &s.gateway_urls.rotate_endpoint_audience,
499+
audience: ROTATE_ENDPOINT_AUDIENCE,
467500
challenge_id: r.challenge_id,
468501
challenge: &r.challenge,
469502
installation_handle: r.installation_handle,
@@ -526,7 +559,7 @@ async fn revoke_delegation(State(s): State<AppState>, body: Bytes) -> Response {
526559
}
527560
let t = RevokeDelegationTranscript {
528561
v: r.v,
529-
audience: &s.gateway_urls.revoke_delegation_audience,
562+
audience: REVOKE_DELEGATION_AUDIENCE,
530563
challenge_id: r.challenge_id,
531564
challenge: &r.challenge,
532565
installation_handle: r.installation_handle,
@@ -581,7 +614,7 @@ async fn revoke_installation(State(s): State<AppState>, body: Bytes) -> Response
581614
}
582615
let t = RevokeInstallationTranscript {
583616
v: r.v,
584-
audience: &s.gateway_urls.revoke_installation_audience,
617+
audience: REVOKE_INSTALLATION_AUDIENCE,
585618
challenge_id: r.challenge_id,
586619
challenge: &r.challenge,
587620
installation_handle: r.installation_handle,
@@ -618,7 +651,12 @@ async fn revoke_installation(State(s): State<AppState>, body: Bytes) -> Response
618651
}
619652
}
620653

621-
async fn deliver(State(s): State<AppState>, headers: HeaderMap, body: Bytes) -> Response {
654+
async fn deliver(
655+
State(s): State<AppState>,
656+
OriginalUri(uri): OriginalUri,
657+
headers: HeaderMap,
658+
body: Bytes,
659+
) -> Response {
622660
let r: DeliveryRequest = match crate::strict_json::from_slice(&body) {
623661
Ok(x) => x,
624662
Err(_) => return error(StatusCode::BAD_REQUEST, "invalid_request"),
@@ -633,20 +671,13 @@ async fn deliver(State(s): State<AppState>, headers: HeaderMap, body: Bytes) ->
633671
Some(x) => x,
634672
None => return error(StatusCode::UNAUTHORIZED, "invalid_auth"),
635673
};
636-
let event_id = match auth_event_id(auth) {
637-
Some(x) => x,
674+
if uri.query().is_some() {
675+
return error(StatusCode::UNAUTHORIZED, "invalid_auth");
676+
}
677+
let (event_id, relay) = match delivery_auth(auth, &body) {
678+
Some(auth) => auth,
638679
None => return error(StatusCode::UNAUTHORIZED, "invalid_auth"),
639680
};
640-
let relay = match verify_auth_header(
641-
auth,
642-
&s.gateway_urls.delivery,
643-
HttpMethod::POST,
644-
Timestamp::now(),
645-
Some(&body),
646-
) {
647-
Ok(x) => x.to_hex(),
648-
Err(_) => return error(StatusCode::UNAUTHORIZED, "invalid_auth"),
649-
};
650681
let grant = match s.grant_keyring.open(&r.endpoint_grant) {
651682
Ok(x) => x,
652683
Err(_) => return error(StatusCode::NOT_FOUND, "invalid_grant"),
@@ -828,7 +859,7 @@ pub fn router_with_metrics(
828859
.route("/v1/delegations/revoke", post(revoke_delegation))
829860
.route("/v1/installations/endpoint", post(rotate_endpoint))
830861
.route("/v1/installations/revoke", post(revoke_installation))
831-
.route("/v1/deliveries/apns", post(deliver))
862+
.route(DELIVERY_PATH, post(deliver))
832863
.layer(RequestBodyLimitLayer::new(MAX_REQUEST_BYTES));
833864
let public = Router::new()
834865
.merge(enrollment)
@@ -906,9 +937,6 @@ mod request_limit_tests {
906937
app_attest: Arc::new(app_attest),
907938
transport: Arc::new(NeverTransport),
908939
}),
909-
gateway_urls: Arc::new(
910-
GatewayUrls::from_origin("https://push.example".parse().unwrap()).unwrap(),
911-
),
912940
max_grant_lifetime_seconds: 86_400,
913941
max_installation_lifetime_seconds: 86_400,
914942
endpoint_quota_window_seconds: 60,

0 commit comments

Comments
 (0)