Skip to content

Commit a952534

Browse files
committed
fix(media): address copilot review — fail-closed h-tag, test literals, ACL logging
- error.rs: add InvalidTag variant -> 400 Bad Request for malformed h tag - upload.rs: extract_channel_id now Result<Option<Uuid>, MediaError>, fails on any present-but-invalid h (missing value, parse fail, nil, multiple conflicting UUIDs) instead of silently downgrading to unbound. Updated 3 call sites (process_upload, process_file_upload, process_video_upload) to propagate with ?. Fixes P0 data-leak where typo h would over-share as relay-gated. - upload.rs: fix 2 test BlobMeta literals (test_build_descriptor_* ) to include channel_id: None — cargo test now builds (was E0063). - media.rs: enforce_media_channel_acl now logs before collapsing to 404: debug for expected ChannelNotFound/not-member, warn + buzz_media_channel_acl_db_errors_total counter for DB errors. Keeps wire 404 for anti-probing. Addresses Copilot feedback on PR 5185 (4 comments). cargo check --tests and cargo test -p buzz-media (108 passed) ok. Signed-off-by: Mert Cetin <[email protected]>
1 parent 8805e2a commit a952534

3 files changed

Lines changed: 79 additions & 14 deletions

File tree

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

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,8 @@ pub enum MediaError {
1818
InvalidImage,
1919
#[error("media contains metadata or a non-canonical metadata channel")]
2020
MetadataForbidden,
21+
#[error("invalid tag value for {0}")]
22+
InvalidTag(&'static str),
2123
#[error("invalid signature")]
2224
InvalidSignature,
2325
#[error("invalid auth event kind")]
@@ -151,6 +153,7 @@ impl IntoResponse for MediaError {
151153
| Self::InvalidVideo
152154
| Self::InvalidImage
153155
| Self::MetadataForbidden => (StatusCode::UNPROCESSABLE_ENTITY, self.to_string()),
156+
Self::InvalidTag(_) => (StatusCode::BAD_REQUEST, self.to_string()),
154157
Self::Io(_) | Self::StorageError(_) | Self::Internal => {
155158
tracing::error!(error = %self, "media storage error");
156159
(StatusCode::INTERNAL_SERVER_ERROR, "internal error".into())

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

Lines changed: 36 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,21 +23,44 @@ use crate::validation::{
2323
/// event, the sidecar is bound to that channel and subsequent `GET`/`HEAD`
2424
/// requests require channel membership for private channels. `None` means
2525
/// unbound (legacy / avatar / open-channel) — relay membership alone suffices.
26-
/// Malformed UUIDs are ignored rather than failing the upload.
27-
fn extract_channel_id(auth_event: &nostr::Event) -> Option<uuid::Uuid> {
26+
/// If an `h` tag is present but malformed (missing value, not a UUID, nil
27+
/// UUID, or multiple conflicting values), the upload fails with
28+
/// `InvalidTag("h")` (400) rather than silently downgrading to unbound.
29+
fn extract_channel_id(
30+
auth_event: &nostr::Event,
31+
) -> Result<Option<uuid::Uuid>, crate::error::MediaError> {
2832
let h_tag = nostr::SingleLetterTag::lowercase(nostr::Alphabet::H);
33+
let mut found: Option<uuid::Uuid> = None;
34+
let mut saw_h = false;
2935
for tag in auth_event.tags.iter() {
3036
if tag.kind() == nostr::TagKind::SingleLetter(h_tag) {
31-
if let Some(val) = tag.content() {
32-
if let Ok(id) = uuid::Uuid::parse_str(val) {
33-
if !id.is_nil() {
34-
return Some(id);
35-
}
37+
saw_h = true;
38+
let val = tag
39+
.content()
40+
.ok_or(crate::error::MediaError::InvalidTag("h"))?;
41+
let id = uuid::Uuid::parse_str(val)
42+
.map_err(|_| crate::error::MediaError::InvalidTag("h"))?;
43+
if id.is_nil() {
44+
return Err(crate::error::MediaError::InvalidTag("h"));
45+
}
46+
if let Some(existing) = found {
47+
if existing != id {
48+
// Multiple h tags with different UUIDs — ambiguous binding.
49+
return Err(crate::error::MediaError::InvalidTag("h"));
3650
}
51+
// Duplicate same UUID — idempotent, keep first.
52+
} else {
53+
found = Some(id);
3754
}
3855
}
3956
}
40-
None
57+
if saw_h && found.is_none() {
58+
// This branch is reachable only if an h tag existed but was
59+
// considered invalid via the checks above — already returned Err.
60+
// Kept for exhaustiveness.
61+
return Err(crate::error::MediaError::InvalidTag("h"));
62+
}
63+
Ok(found)
4164
}
4265

4366
/// Shared buffered-upload pipeline for the image and generic-file paths.
@@ -235,7 +258,7 @@ pub async fn process_upload(
235258
body: Bytes,
236259
attribution: Option<UploadAttribution>,
237260
) -> Result<BlobDescriptor, MediaError> {
238-
let channel_id = extract_channel_id(auth_event);
261+
let channel_id = extract_channel_id(auth_event)?;
239262
process_buffered_upload(
240263
BufferedUploadInput {
241264
storage,
@@ -281,7 +304,7 @@ pub async fn process_file_upload(
281304
body: Bytes,
282305
attribution: Option<UploadAttribution>,
283306
) -> Result<BlobDescriptor, MediaError> {
284-
let channel_id = extract_channel_id(auth_event);
307+
let channel_id = extract_channel_id(auth_event)?;
285308
process_buffered_upload(
286309
BufferedUploadInput {
287310
storage,
@@ -331,7 +354,7 @@ pub async fn process_video_upload(
331354
content_length: Option<u64>,
332355
attribution: Option<UploadAttribution>,
333356
) -> Result<BlobDescriptor, MediaError> {
334-
let channel_id = extract_channel_id(auth_event);
357+
let channel_id = extract_channel_id(auth_event)?;
335358
// --- 1. Stream body to temp file, compute SHA-256 incrementally ---
336359
let tmp = tempfile::NamedTempFile::new().map_err(|e| MediaError::Io(e.to_string()))?;
337360
let tmp_path = tmp.path().to_path_buf();
@@ -631,6 +654,7 @@ mod tests {
631654
size: 5_000_000,
632655
uploaded_at: 1700000000,
633656
duration_secs: Some(29.5),
657+
channel_id: None,
634658
};
635659

636660
let desc = build_descriptor(
@@ -689,6 +713,7 @@ mod tests {
689713
size: 100_000,
690714
uploaded_at: 1700000000,
691715
duration_secs: None,
716+
channel_id: None,
692717
};
693718

694719
let desc = build_descriptor(

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

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -534,20 +534,57 @@ async fn enforce_media_channel_acl(
534534
};
535535
// Look up channel to determine visibility. If the channel is missing,
536536
// deleted, or lookup fails, fail closed as NotFound to avoid leaking
537-
// existence of a private blob.
537+
// existence of a private blob. Log at debug level for expected
538+
// ChannelNotFound vs warn for DB transport errors to aid incident debugging
539+
// without changing the wire 404.
538540
let channel = state
539541
.db
540542
.get_channel(tenant.community(), channel_id)
541543
.await
542-
.map_err(|_| MediaError::NotFound)?;
544+
.map_err(|e| {
545+
// Distinguish expected missing-channel (debug, high volume if channel deleted)
546+
// from transport errors (warn, needs ops attention). We do not inspect
547+
// error string for probing — just log and keep 404.
548+
if e.to_string().contains("ChannelNotFound") || e.to_string().contains("not found") {
549+
tracing::debug!(
550+
community = %tenant.community(),
551+
channel_id = %channel_id,
552+
error = %e,
553+
"media channel ACL: get_channel failed; returning NotFound"
554+
);
555+
} else {
556+
tracing::warn!(
557+
community = %tenant.community(),
558+
channel_id = %channel_id,
559+
error = %e,
560+
"media channel ACL: get_channel DB error; returning NotFound"
561+
);
562+
metrics::counter!("buzz_media_channel_acl_db_errors_total").increment(1);
563+
}
564+
MediaError::NotFound
565+
})?;
543566
if channel.visibility != "private" {
544567
return Ok(());
545568
}
546569
let is_member = state
547570
.is_member_cached(tenant.community(), channel_id, pubkey)
548571
.await
549-
.map_err(|_| MediaError::NotFound)?;
572+
.map_err(|e| {
573+
tracing::warn!(
574+
community = %tenant.community(),
575+
channel_id = %channel_id,
576+
error = %e,
577+
"media channel ACL: is_member_cached failed; returning NotFound"
578+
);
579+
metrics::counter!("buzz_media_channel_acl_db_errors_total").increment(1);
580+
MediaError::NotFound
581+
})?;
550582
if !is_member {
583+
tracing::debug!(
584+
community = %tenant.community(),
585+
channel_id = %channel_id,
586+
"media channel ACL: not a member, returning NotFound"
587+
);
551588
return Err(MediaError::NotFound);
552589
}
553590
Ok(())

0 commit comments

Comments
 (0)