Skip to content

Commit eac46e2

Browse files
klopez4212Terp
andcommitted
fix(relay): bind invite preview media to resolved community host
Co-authored-by: Terp <5856f6900e8e0a4e0ea1f4f8d2ee33e4753d2119bc122f94ecafc660b46c0511@buzz.block.builderlab.xyz> Signed-off-by: kenny lopez <[email protected]>
1 parent 1db6387 commit eac46e2

3 files changed

Lines changed: 126 additions & 46 deletions

File tree

‎crates/buzz-relay/src/invite_preview.rs‎

Lines changed: 83 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -7,27 +7,40 @@ use axum::{
77
use std::path::Path;
88
use url::Url;
99

10-
pub(crate) async fn response(index: &Path, relay_url: &str) -> Response {
10+
pub(crate) async fn response<R: crate::tenant::HostResolver>(
11+
index: &Path,
12+
relay_url: &str,
13+
resolver: &R,
14+
raw_host: &str,
15+
) -> Response {
1116
match tokio::fs::read_to_string(index).await {
12-
Ok(html) => Html(with_metadata(html, relay_url)).into_response(),
17+
Ok(html) => {
18+
let tenant = crate::tenant::bind_community(resolver, raw_host).await.ok();
19+
Html(with_metadata(html, relay_url, tenant.as_ref())).into_response()
20+
}
1321
Err(_) => StatusCode::INTERNAL_SERVER_ERROR.into_response(),
1422
}
1523
}
1624

17-
fn with_metadata(html: String, relay_url: &str) -> String {
18-
let Ok(mut origin) = Url::parse(relay_url) else {
25+
fn with_metadata(
26+
html: String,
27+
relay_url: &str,
28+
tenant: Option<&buzz_core::tenant::TenantContext>,
29+
) -> String {
30+
let Some(tenant) = tenant else {
31+
return html;
32+
};
33+
let Ok(relay) = Url::parse(relay_url) else {
1934
return html;
2035
};
21-
let scheme = match origin.scheme() {
36+
let scheme = match relay.scheme() {
2237
"wss" | "https" => "https",
2338
"ws" | "http" => "http",
2439
_ => return html,
2540
};
26-
if origin.set_scheme(scheme).is_err() || origin.host_str().is_none() {
27-
return html;
28-
}
29-
// Use the operator's canonical public origin, never the request Host or token.
30-
let origin = origin.origin().ascii_serialization();
41+
// The deployment URL supplies TLS posture only. The resolved request host
42+
// is authoritative; never advertise a neighboring community's seed host.
43+
let origin = format!("{scheme}://{}", tenant.host());
3144
let origin = origin
3245
.replace('&', "&amp;")
3346
.replace('"', "&quot;")
@@ -63,30 +76,68 @@ fn with_metadata(html: String, relay_url: &str) -> String {
6376
mod tests {
6477
use super::*;
6578

66-
#[test]
67-
fn canonical_public_media_without_credentials_or_paths() {
79+
struct Resolver;
80+
impl crate::tenant::HostResolver for Resolver {
81+
type Error = ();
82+
async fn resolve_host(
83+
&self,
84+
host: &str,
85+
) -> Result<Option<buzz_core::tenant::CommunityId>, ()> {
86+
match host {
87+
"alpha.example" | "beta.example:8443" => {
88+
Ok(Some(buzz_core::tenant::CommunityId::from_uuid(
89+
uuid::Uuid::from_u128(if host.starts_with("alpha") { 1 } else { 2 }),
90+
)))
91+
}
92+
"error.example" => Err(()),
93+
_ => Ok(None),
94+
}
95+
}
96+
}
97+
98+
#[tokio::test]
99+
async fn media_uses_only_resolved_request_host_and_fails_closed() {
68100
let document = "<html><head><title>Buzz</title></head><body>app</body></html>";
69-
for (relay, expected, secure) in [
70-
("wss://example.org/relay", "https://example.org", true),
71-
(
72-
"https://user:[email protected]:8443/path?secret=x#fragment",
73-
"https://example.org:8443",
74-
true,
75-
),
76-
("ws://localhost:8080", "http://localhost:8080", false),
101+
let dir = tempfile::tempdir().unwrap();
102+
let index = dir.path().join("index.html");
103+
std::fs::write(&index, document).unwrap();
104+
for relay in [
105+
"wss://seed.example/relay",
106+
"https://user:[email protected]/path?secret=x",
107+
"ws://localhost:3000",
77108
] {
78-
let html = with_metadata(document.into(), relay);
79-
assert!(html.contains(&format!(
80-
"content=\"{expected}/assets/invite-preview/buzz-invite-loop-v1.mp4\""
81-
)));
82-
assert!(html.contains("buzz-invite-poster-v1.png"));
83-
assert_eq!(html.contains("og:video:secure_url"), secure);
84-
assert!(!html.contains("password"));
85-
assert!(!html.contains("secret"));
86-
assert!(html.ends_with("</head><body>app</body></html>"));
87-
}
88-
for invalid in ["invalid", "file:///tmp/test", "javascript:alert(1)"] {
89-
assert_eq!(with_metadata(document.into(), invalid), document);
109+
for host in [
110+
"ALPHA.example",
111+
"beta.example:8443",
112+
"unknown.example",
113+
"error.example",
114+
"",
115+
] {
116+
let response = response(&index, relay, &Resolver, host).await;
117+
let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
118+
.await
119+
.unwrap();
120+
let html = std::str::from_utf8(&bytes).unwrap();
121+
if host == "ALPHA.example" || host == "beta.example:8443" {
122+
let scheme = if relay.starts_with("ws://") {
123+
"http"
124+
} else {
125+
"https"
126+
};
127+
let origin = format!("{scheme}://{}", host.to_lowercase());
128+
for file in ["buzz-invite-loop-v1.mp4", "buzz-invite-poster-v1.png"] {
129+
assert!(html.contains(&format!(
130+
"content=\"{origin}/assets/invite-preview/{file}\""
131+
)));
132+
}
133+
assert_eq!(html.contains("og:video:secure_url"), scheme == "https");
134+
assert!(!html.contains("seed.example"));
135+
assert!(!html.contains("password"));
136+
assert!(!html.contains("secret"));
137+
} else {
138+
assert_eq!(html, document);
139+
}
140+
}
90141
}
91142
}
92143
}

‎crates/buzz-relay/src/router.rs‎

Lines changed: 38 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,11 @@ pub fn build_router(state: Arc<AppState>) -> Router {
620620
return Ok(crate::invite_preview::response(
621621
&index,
622622
&state.config.relay_url,
623+
state.as_ref(),
624+
req.headers()
625+
.get(axum::http::header::HOST)
626+
.and_then(|host| host.to_str().ok())
627+
.unwrap_or(""),
623628
)
624629
.await);
625630
}
@@ -2163,6 +2168,15 @@ mod tests {
21632168
std::fs::write(media_dir.join(name), bytes).unwrap();
21642169
}
21652170
let state = spa_state(admin_dir.path(), web_dir.path()).await;
2171+
for (host, id) in [("alpha.example", 1), ("beta.example", 2)] {
2172+
state.tenant_host_cache.insert(
2173+
host.into(),
2174+
(
2175+
buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::from_u128(id)),
2176+
std::time::Instant::now(),
2177+
),
2178+
);
2179+
}
21662180
// Also exercise the production router over a real HTTP connection.
21672181
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
21682182
let address = listener.local_addr().unwrap();
@@ -2178,6 +2192,7 @@ mod tests {
21782192
let client = reqwest::Client::builder().no_proxy().build().unwrap();
21792193
let fetched = client
21802194
.get(format!("http://{address}/invite/unused-token"))
2195+
.header("host", "alpha.example")
21812196
.send()
21822197
.await
21832198
.unwrap();
@@ -2194,17 +2209,29 @@ mod tests {
21942209
assert_eq!(fetched.status(), StatusCode::PARTIAL_CONTENT);
21952210
assert_eq!(fetched.bytes().await.unwrap().len(), 32);
21962211
server.abort();
2197-
let response =
2198-
spa_response(state.clone(), "untrusted.example", "/invite/unused-token").await;
2199-
assert_eq!(response.status(), StatusCode::OK);
2200-
let html = axum::body::to_bytes(response.into_body(), usize::MAX)
2201-
.await
2202-
.unwrap();
2203-
let html = std::str::from_utf8(&html).unwrap();
2204-
assert!(html.contains("og:video"));
2205-
assert!(html.contains("og:image"));
2206-
assert!(!html.contains("untrusted.example"));
2207-
assert!(!html.contains("unused-token"));
2212+
for host in ["alpha.example", "beta.example", ""] {
2213+
let response = spa_response(state.clone(), host, "/invite/unused-token").await;
2214+
assert_eq!(response.status(), StatusCode::OK);
2215+
let html = axum::body::to_bytes(response.into_body(), usize::MAX)
2216+
.await
2217+
.unwrap();
2218+
let html = std::str::from_utf8(&html).unwrap();
2219+
if host.is_empty() {
2220+
assert!(!html.contains("og:video"));
2221+
assert!(!html.contains("og:image"));
2222+
continue;
2223+
}
2224+
assert!(html.contains(&format!("http://{host}/assets/invite-preview/")));
2225+
assert!(!html.contains(if host == "alpha.example" {
2226+
"beta.example"
2227+
} else {
2228+
"alpha.example"
2229+
}));
2230+
assert!(html.contains("og:video"));
2231+
assert!(html.contains("og:image"));
2232+
assert!(!html.contains("untrusted.example"));
2233+
assert!(!html.contains("unused-token"));
2234+
}
22082235
for path in ["/repos", "/invite/"] {
22092236
let response = spa_response(state.clone(), "public.example", path).await;
22102237
let body = axum::body::to_bytes(response.into_body(), usize::MAX)

‎previews/invite-video/README.md‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,11 @@ metadata to the initial HTML for `/invite/<code>` only. Previews are generic and
4141
do not validate or redeem the invite.
4242

4343
Deploy both the updated relay and its web bundle (the relay Docker image includes
44-
both). Set `RELAY_URL` to the publicly reachable canonical relay URL; its
45-
`wss`/`ws` scheme maps to `https`/`http` for the media URLs. The configured origin
46-
must serve the web bundle without authentication. Use HTTPS in production.
44+
both). The media host comes from the request's resolved community, matching the
45+
invite link's host. `RELAY_URL` supplies only the `wss`/`ws` TLS posture, mapped to
46+
`https`/`http`. Unmapped hosts or lookup failures receive no preview metadata.
47+
Each community host must serve the web bundle without authentication. Use HTTPS
48+
in production.
4749

4850
After deployment, inspect an invite response with `curl` for `og:video` and
4951
`og:image`, then fetch both referenced URLs and check that they return MP4/PNG

0 commit comments

Comments
 (0)