Skip to content

Commit 3e677c9

Browse files
npub1qyvc0c5kl4gqv2fd97fsk46tu378sqgy35vc83rvgfwne90sel7s0ed67dTyler Longwell
andcommitted
fix(media,git): tenant-bound Blossom server-domain; no publish on denied push
Two pre-merge blockers found by the PR #1321 merge-gate exercise, both multi-tenant correctness bugs under the confirmed "many tenant-hosts per relay" topology. Media — non-primary tenant upload (conformance row 52): The Blossom `server`-tag check validated against a single process-global `server_domain` derived from RELAY_URL, so only the primary host accepted stock-CLI (`buzz upload file`) uploads; every other tenant 401'd with `server mismatch`. Validate instead against the per-request bound tenant host (`TenantContext::host()`), normalized through the shared `normalize_host` rule so a `server` tag and the bound host agree across case, trailing dot, default ports, and an optional URL scheme/path. The upload extractor now binds the tenant before auth verification (binding only reads the Host header, so the pre-body auth-rejection guarantee is preserved). Removes the now-dead `MediaConfig.server_domain` field, its RELAY_URL derivation, its three config tests, and the dead `BUZZ_MEDIA_SERVER_DOMAIN` env line in the Helm chart. Git — denied push published a 30618: `run_git_at` swallowed git's non-zero exit, so `finalize_push` ran the CAS publish and emitted a relay-signed kind:30618 ref-state event even when the pre-receive hook declined — falsely attributing the ref state to the denied pusher and breaking "rejected push -> no published state". Carry the receive-pack exit status on `PackOutput.ok` and short-circuit `finalize_push` on a non-zero exit: skip the CAS publish and the derived 30618, returning git's in-band rejection verbatim so the client still prints the decline. Adds a regression unit test for the normalized tenant-host server-tag match. Co-authored-by: Tyler Longwell <[email protected]> Signed-off-by: Tyler Longwell <[email protected]>
1 parent 666cfe4 commit 3e677c9

8 files changed

Lines changed: 174 additions & 105 deletions

File tree

‎crates/buzz-media/src/auth.rs‎

Lines changed: 97 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -89,18 +89,32 @@ pub fn verify_blossom_auth_event(
8989
return Err(MediaError::TimestampOutOfWindow);
9090
}
9191

92-
// 6. Server tag enforcement (BUD-11 §5): if server tags present, our domain must appear.
93-
// Fail closed: if server_domain is unconfigured, reject tokens that carry server tags
94-
// rather than silently accepting them.
92+
// 6. Server tag enforcement (BUD-11 §5): if server tags present, our host must appear.
93+
//
94+
// `server_domain` is the host this request was bound to — the per-request
95+
// tenant host (`TenantContext::host()`), NOT a single process-global domain.
96+
// A relay process serves many tenant hosts; validating against one global
97+
// host would 401 every non-primary tenant's server-tagged client (the stock
98+
// CLI always tags its configured relay host). Comparison is done under the
99+
// shared [`normalize_host`] rule so a tag and the bound host agree by
100+
// construction across case, trailing dot, default ports, and an optional
101+
// URL scheme/path — exactly as every other host seam resolves tenants.
102+
//
103+
// Fail closed: if the bound host is unknown, reject tokens that carry server
104+
// tags rather than silently accepting them.
95105
if !server_tags.is_empty() {
96106
match server_domain {
97107
Some(domain) => {
98-
if !server_tags.contains(&domain) {
108+
let want = normalize_server_host(domain);
109+
let matches = server_tags
110+
.iter()
111+
.any(|tag| normalize_server_host(tag) == want);
112+
if !matches {
99113
return Err(MediaError::ServerMismatch);
100114
}
101115
}
102116
None => {
103-
// Server tags present but we don't know our own domain — reject.
117+
// Server tags present but we don't know our own host — reject.
104118
return Err(MediaError::ServerMismatch);
105119
}
106120
}
@@ -109,6 +123,22 @@ pub fn verify_blossom_auth_event(
109123
Ok(())
110124
}
111125

126+
/// Normalize a Blossom `server` tag value (or a bound tenant host) into the
127+
/// canonical host form used as the community lookup key.
128+
///
129+
/// A `server` tag may be a bare authority (`relay.example:3100`, what the stock
130+
/// CLI emits) or a full URL (`https://relay.example/`). We strip an optional
131+
/// scheme and path down to the authority, then apply the one shared
132+
/// [`buzz_core::tenant::normalize_host`] rule so the comparison agrees with how
133+
/// the WS/HTTP/git doors resolve tenants.
134+
fn normalize_server_host(value: &str) -> String {
135+
let authority = match value.split_once("://") {
136+
Some((_scheme, rest)) => rest.split('/').next().unwrap_or(rest),
137+
None => value.split('/').next().unwrap_or(value),
138+
};
139+
buzz_core::tenant::normalize_host(authority)
140+
}
141+
112142
/// Verify a kind:24242 Blossom upload auth event, including the x tag hash check.
113143
///
114144
/// Calls [`verify_blossom_auth_event`] first, then verifies that at least one
@@ -264,6 +294,68 @@ mod tests {
264294
assert!(verify_blossom_upload_auth(&event, &sha256, Some("any.domain.com"), 600).is_ok());
265295
}
266296

297+
/// A `server` tag is matched against the *bound tenant host* under the
298+
/// shared `normalize_host` rule, so equivalent host spellings agree — the
299+
/// stock CLI's bare `host:port`, an explicit default port, a trailing dot,
300+
/// mixed case, and a full URL all match the same bound host. This is the
301+
/// regression guard for the multi-tenant media blocker: a non-primary
302+
/// tenant must accept its own server-tagged client.
303+
#[test]
304+
fn test_server_tag_normalized_against_bound_host() {
305+
let keys = Keys::generate();
306+
let sha256 = "a".repeat(64);
307+
let now = Timestamp::now().as_secs();
308+
let exp_str = (now + 300).to_string();
309+
let build = |server: &str| {
310+
let tags = vec![
311+
Tag::parse(["t", "upload"]).unwrap(),
312+
Tag::parse(["x", &sha256]).unwrap(),
313+
Tag::parse(["expiration", &exp_str]).unwrap(),
314+
Tag::parse(["server", server]).unwrap(),
315+
];
316+
EventBuilder::new(Kind::from(24242), "Upload scoped")
317+
.tags(tags)
318+
.sign_with_keys(&keys)
319+
.unwrap()
320+
};
321+
322+
// Non-primary tenant host with explicit non-default port (the live
323+
// repro: tenant B on 127.0.0.1:3100). Stock CLI tags `host:port`.
324+
assert!(verify_blossom_upload_auth(
325+
&build("127.0.0.1:3100"),
326+
&sha256,
327+
Some("127.0.0.1:3100"),
328+
600
329+
)
330+
.is_ok());
331+
332+
// Equivalence under normalize_host: explicit default port, trailing
333+
// dot, mixed case, and a full URL all collapse to the bound host.
334+
for tag in [
335+
"Relay.Example:443",
336+
"relay.example.",
337+
"RELAY.EXAMPLE",
338+
"https://relay.example/",
339+
] {
340+
assert!(
341+
verify_blossom_upload_auth(&build(tag), &sha256, Some("relay.example"), 600)
342+
.is_ok(),
343+
"server tag {tag:?} should match bound host relay.example"
344+
);
345+
}
346+
347+
// A different tenant host still fails closed.
348+
assert!(matches!(
349+
verify_blossom_upload_auth(
350+
&build("127.0.0.1:3100"),
351+
&sha256,
352+
Some("127.0.0.1:3200"),
353+
600
354+
),
355+
Err(MediaError::ServerMismatch)
356+
));
357+
}
358+
267359
#[test]
268360
fn test_empty_content_rejected() {
269361
let keys = Keys::generate();

‎crates/buzz-media/src/config.rs‎

Lines changed: 0 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,6 @@ pub struct MediaConfig {
3131
pub max_file_bytes: u64,
3232
/// Public base URL for media URLs in BlobDescriptor (must include `/media` path).
3333
pub public_base_url: String,
34-
/// Server authority for BUD-11 server tag validation.
35-
/// Format: `host` for default ports, `host:port` for non-default ports.
36-
/// Examples: "buzz.example.com", "localhost:3000", "relay.example.com:8080".
37-
/// If None, auth events carrying `server` tags are rejected (fail-closed).
38-
/// Must match the authority the desktop signer derives from the relay URL.
39-
pub server_domain: Option<String>,
4034
}
4135

4236
impl MediaConfig {

‎crates/buzz-media/src/upload.rs‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,15 @@ where
4949
let auth = auth_event.clone();
5050
let bytes = body.clone();
5151
let cfg = config.clone();
52+
// Validate the Blossom `server` tag against the host this request was bound
53+
// to (the per-request tenant), not a process-global domain — a relay serves
54+
// many tenant hosts.
55+
let bound_host = ctx.host().to_string();
5256
let (mime, sha256, ext) = tokio::task::spawn_blocking(move || -> Result<_, MediaError> {
5357
let (mime, ext) = validate(&bytes, &cfg)?;
5458
let sha256 = hex::encode(Sha256::digest(&bytes));
5559
// Buffered uploads (image + file): 10-minute auth window is plenty.
56-
verify_blossom_upload_auth(&auth, &sha256, cfg.server_domain.as_deref(), 600)?;
60+
verify_blossom_upload_auth(&auth, &sha256, Some(bound_host.as_str()), 600)?;
5761
Ok((mime, sha256, ext))
5862
})
5963
.await
@@ -326,10 +330,12 @@ pub async fn process_video_upload(
326330
// --- 3. Verify Blossom auth: x tag must match computed SHA-256 ---
327331
let auth = auth_event.clone();
328332
let sha256_for_auth = sha256_hex.clone();
329-
let server_domain = config.server_domain.clone();
333+
// Validate the Blossom `server` tag against the bound tenant host (not a
334+
// process-global domain) — a relay serves many tenant hosts.
335+
let bound_host = ctx.host().to_string();
330336
tokio::task::spawn_blocking(move || {
331337
// Videos: 1-hour window — large uploads on slow connections need headroom.
332-
verify_blossom_upload_auth(&auth, &sha256_for_auth, server_domain.as_deref(), 3600)
338+
verify_blossom_upload_auth(&auth, &sha256_for_auth, Some(bound_host.as_str()), 3600)
333339
})
334340
.await
335341
.map_err(|_| MediaError::Internal)??;
@@ -460,7 +466,6 @@ mod tests {
460466
max_video_bytes: 524_288_000,
461467
max_file_bytes: 104_857_600,
462468
public_base_url: "https://media.example.com".to_string(),
463-
server_domain: None,
464469
}
465470
}
466471

‎crates/buzz-media/src/validation.rs‎

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -421,7 +421,6 @@ mod tests {
421421
max_video_bytes: 524_288_000,
422422
max_file_bytes: 104_857_600,
423423
public_base_url: String::new(),
424-
server_domain: None,
425424
}
426425
}
427426

‎crates/buzz-relay/src/api/git/transport.rs‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -790,6 +790,15 @@ pub async fn receive_pack(
790790
/// [`finalize_push`] has decided to build a `Response` from these bytes.
791791
pub(crate) struct PackOutput {
792792
pub stdout: Vec<u8>,
793+
/// Whether the `git receive-pack`/`upload-pack` subprocess exited 0.
794+
///
795+
/// A non-zero exit on `receive-pack` means git aborted the ref updates —
796+
/// most importantly a **pre-receive hook decline** (authorization denied).
797+
/// `finalize_push` must treat `false` as "push did not happen": skip the
798+
/// CAS publish and the derived kind:30618 so a rejected push leaves **no
799+
/// published state**. The buffered stdout still carries git's in-band
800+
/// report-status so the client prints the rejection.
801+
pub ok: bool,
793802
}
794803

795804
/// Spawn a `git --stateless-rpc <service>` subprocess against the given
@@ -867,10 +876,13 @@ async fn run_git_at(
867876
let stderr = String::from_utf8_lossy(&output.stderr);
868877
warn!(stderr = %stderr, service = %service, "git subprocess exited with error");
869878
// Still return output — git protocol errors are communicated in-band.
879+
// The non-zero exit is carried on `PackOutput.ok` so the push fence in
880+
// `finalize_push` can refuse to publish on a hook decline (see below).
870881
}
871882

872883
Ok(PackOutput {
873884
stdout: output.stdout,
885+
ok: output.status.success(),
874886
})
875887
}
876888

@@ -1052,6 +1064,32 @@ pub(crate) struct PushContext {
10521064
/// constructor of a push 2xx, so the seam is structural (not by
10531065
/// convention).
10541066
async fn finalize_push(state: &Arc<AppState>, ctx: PushContext) -> Response {
1067+
// The push fence, part 0 — **a rejected push publishes nothing.**
1068+
//
1069+
// `git receive-pack` exits non-zero when the pre-receive hook declines
1070+
// (authorization denied) or git itself aborts the ref updates. In that
1071+
// case the workspace refs were NOT advanced, so there is no committed
1072+
// state to publish: we must skip the CAS pointer write AND the derived
1073+
// kind:30618 ref-state event. Otherwise a denied push would emit a
1074+
// relay-signed, fanned-out 30618 falsely attributing the ref state to the
1075+
// *denied* pusher (`actor = ctx.pusher`), breaking the invariant
1076+
// "rejected push → no published state".
1077+
//
1078+
// git's in-band report-status (already buffered in `ctx.pack.stdout`)
1079+
// still streams back so the client prints `! [remote rejected]` / the
1080+
// hook's decline message; only the publish side effects are suppressed.
1081+
if !ctx.pack.ok {
1082+
warn!(
1083+
owner = %ctx.owner,
1084+
repo = %ctx.repo_id,
1085+
"receive-pack exited non-zero (e.g. pre-receive hook decline); \
1086+
skipping CAS publish and kind:30618 — no state published"
1087+
);
1088+
let response = build_git_response("receive-pack", ctx.pack);
1089+
drop(ctx.repo_handle);
1090+
return response;
1091+
}
1092+
10551093
// Step 7 (CAS). The PushContext binds `parent_state` (observed at
10561094
// hydrate) to the CAS predicate here — no re-reading of the pointer
10571095
// between hydrate and CAS.

‎crates/buzz-relay/src/api/media.rs‎

Lines changed: 30 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -48,19 +48,41 @@ impl FromRequestParts<Arc<AppState>> for AuthenticatedUpload {
4848
) -> Result<Self, Self::Rejection> {
4949
let headers = &parts.headers;
5050

51-
// 1. Extract and validate Blossom auth event
51+
// 1. Row zero: bind this upload to its community from the request host,
52+
// identical to the WS door in `router.rs` and the bridge door in
53+
// `bridge.rs`. Fail-closed: an unmapped host or lookup failure is a
54+
// generic `NotFound` (404) — never a default tenant, never echoing the
55+
// host, so an unauthenticated caller cannot probe which communities
56+
// exist on this deployment.
57+
//
58+
// This MUST run before scope resolution so the API-token lookup is
59+
// keyed on (community_id, token_hash) — see Gap 2 / row-44 conformance
60+
// obligation. Resolving scopes without a tenant in hand would query
61+
// api_tokens by hash alone, defeating the cross-community fence.
62+
//
63+
// It also runs before Blossom auth verification (step 2) so the
64+
// `server`-tag check validates against the *bound tenant host*, not a
65+
// process-global domain — a relay process serves many tenant hosts, and
66+
// the stock CLI tags its own configured relay host (conformance row 52).
67+
// Binding only reads the Host header — no request body is buffered — so
68+
// doing it first preserves the pre-body auth-rejection guarantee.
69+
let raw_host = headers
70+
.get(header::HOST)
71+
.and_then(|v| v.to_str().ok())
72+
.unwrap_or("");
73+
let tenant = crate::tenant::bind_community(&state.db, raw_host)
74+
.await
75+
.map_err(|_| MediaError::NotFound)?;
76+
77+
// 2. Extract and validate Blossom auth event against the bound host.
5278
let auth_event = extract_blossom_auth(headers)?;
5379
// Use the permissive window (3600s) here because we don't know the
5480
// content type yet. The upload functions re-verify with the correct
5581
// per-type window (600s for images, 3600s for video) after the body
5682
// has been consumed and the SHA-256 computed.
57-
buzz_media::auth::verify_blossom_auth_event(
58-
&auth_event,
59-
state.config.media.server_domain.as_deref(),
60-
3600,
61-
)?;
83+
buzz_media::auth::verify_blossom_auth_event(&auth_event, Some(tenant.host()), 3600)?;
6284

63-
// 2. Require X-SHA-256 header (BUD-11: mandatory for PUT /upload)
85+
// 3. Require X-SHA-256 header (BUD-11: mandatory for PUT /upload)
6486
let claimed_hash = headers
6587
.get("x-sha-256")
6688
.and_then(|v| v.to_str().ok())
@@ -75,7 +97,7 @@ impl FromRequestParts<Arc<AppState>> for AuthenticatedUpload {
7597
return Err(MediaError::HashMismatch);
7698
}
7799

78-
// 3. Validate X-SHA-256 matches at least one x tag in the auth event
100+
// 4. Validate X-SHA-256 matches at least one x tag in the auth event
79101
let has_matching_x = auth_event
80102
.tags
81103
.iter()
@@ -84,25 +106,6 @@ impl FromRequestParts<Arc<AppState>> for AuthenticatedUpload {
84106
return Err(MediaError::HashMismatch);
85107
}
86108

87-
// 4. Row zero: bind this upload to its community from the request host,
88-
// identical to the WS door in `router.rs` and the bridge door in
89-
// `bridge.rs`. Fail-closed: an unmapped host or lookup failure is a
90-
// generic `NotFound` (404) — never a default tenant, never echoing the
91-
// host, so an unauthenticated caller cannot probe which communities
92-
// exist on this deployment.
93-
//
94-
// This MUST run before scope resolution so the API-token lookup is
95-
// keyed on (community_id, token_hash) — see Gap 2 / row-44 conformance
96-
// obligation. Resolving scopes without a tenant in hand would query
97-
// api_tokens by hash alone, defeating the cross-community fence.
98-
let raw_host = headers
99-
.get(header::HOST)
100-
.and_then(|v| v.to_str().ok())
101-
.unwrap_or("");
102-
let tenant = crate::tenant::bind_community(&state.db, raw_host)
103-
.await
104-
.map_err(|_| MediaError::NotFound)?;
105-
106109
// 5. Resolve scopes (API token or dev mode), scoped to the bound tenant.
107110
let scopes = resolve_upload_scopes(headers, state, &tenant, &auth_event.pubkey).await?;
108111
buzz_auth::require_scope(&scopes, Scope::FilesWrite)

0 commit comments

Comments
 (0)