Skip to content

Commit 5df4caf

Browse files
Duncanwpfleger96
andcommitted
fix(media): close strictness bypass at X-SHA-256 and upload_blob error boundaries
Three call sites in the upload path bypassed the MediaDenial strictness split via From<MediaError> for MediaDenial, which hardcodes Permissive: 1. ok_or(MissingTag("x-sha-256")) — replaced with ok_or_else using media_denial(e, strictness). 2. HashMismatch.into() × 2 (malformed + unmatched x tag) — replaced with media_denial(HashMismatch, strictness). 3. upload_blob returned Result<_, MediaError>, so post-body failures hit MediaError::into_response() directly. Fix: add strictness: BlossomStrictness to AuthenticatedUpload, derived in the extractor; change upload_blob to return Result<_, MediaDenial>; apply media_denial through both the outer (protect-layer) and inner (async body) error stacks. Non-Blossom errors (I/O, fencing, concurrency) fall through to the legacy shape in both modes as the wrapper already guarantees. Add 4 response-shape tests (Strict 403 + Permissive 401 for each of MissingTag("x-sha-256") and HashMismatch), pinning status, content-type, body bytes, and WWW-Authenticate absence. Co-authored-by: Will Pfleger <[email protected]> Signed-off-by: Will Pfleger <[email protected]>
1 parent be879b5 commit 5df4caf

1 file changed

Lines changed: 129 additions & 8 deletions

File tree

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

Lines changed: 129 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,10 @@ pub(crate) struct AuthenticatedUpload {
4242
/// door in `bridge.rs`. Server-resolved, never client-supplied.
4343
tenant: TenantContext,
4444
route_mode: UploadRouteMode,
45+
/// NIP-FI strictness derived at extraction time. Carried to the handler so
46+
/// post-body auth failures (hash-binding, x-tag mismatches) produce the same
47+
/// mode-aware denial shape as pre-body failures.
48+
strictness: BlossomStrictness,
4549
_upload_permit: UploadPermit,
4650
}
4751

@@ -247,15 +251,15 @@ impl FromRequestParts<Arc<AppState>> for AuthenticatedUpload {
247251
let claimed_hash = headers
248252
.get("x-sha-256")
249253
.and_then(|v| v.to_str().ok())
250-
.ok_or(MediaError::MissingTag("x-sha-256"))?;
254+
.ok_or_else(|| media_denial(MediaError::MissingTag("x-sha-256"), strictness))?;
251255

252256
// Validate format: exactly 64 lowercase hex characters
253257
if claimed_hash.len() != 64
254258
|| !claimed_hash
255259
.chars()
256260
.all(|c| matches!(c, '0'..='9' | 'a'..='f'))
257261
{
258-
return Err(MediaError::HashMismatch.into());
262+
return Err(media_denial(MediaError::HashMismatch, strictness));
259263
}
260264

261265
// 4. Validate X-SHA-256 matches at least one x tag in the auth event
@@ -264,7 +268,7 @@ impl FromRequestParts<Arc<AppState>> for AuthenticatedUpload {
264268
.iter()
265269
.any(|tag| tag.kind().to_string() == "x" && (tag.content() == Some(claimed_hash)));
266270
if !has_matching_x {
267-
return Err(MediaError::HashMismatch.into());
271+
return Err(media_denial(MediaError::HashMismatch, strictness));
268272
}
269273

270274
// 5. Relay membership gate (NIP-43). Blossom auth proves the signer
@@ -301,6 +305,7 @@ impl FromRequestParts<Arc<AppState>> for AuthenticatedUpload {
301305
auth_event,
302306
tenant,
303307
route_mode,
308+
strictness,
304309
_upload_permit: upload_permit,
305310
})
306311
}
@@ -389,13 +394,15 @@ pub async fn upload_blob(
389394
auth: AuthenticatedUpload,
390395
headers: HeaderMap,
391396
body: axum::body::Body,
392-
) -> Result<Json<BlobDescriptor>, MediaError> {
397+
) -> Result<Json<BlobDescriptor>, MediaDenial> {
398+
let strictness = auth.strictness;
393399
let attribution = upload_attribution(&state, &auth, &headers).await;
394400

395401
let serving_write =
396402
buzz_deletion::acquire_serving_write(&state.db, auth.tenant.community(), "media_upload")
397403
.await
398-
.map_err(serving_write_error)?;
404+
.map_err(serving_write_error)
405+
.map_err(MediaDenial::from)?;
399406

400407
if auth.route_mode == UploadRouteMode::LegacyMedia {
401408
metrics::counter!("buzz_media_legacy_upload_route_total").increment(1);
@@ -416,13 +423,19 @@ pub async fn upload_blob(
416423
sniff.extend_from_slice(&chunk[..chunk.len().min(needed)]);
417424
replay_chunks.push(chunk);
418425
}
419-
Some(Err(error)) => return Err(MediaError::Io(error.to_string())),
426+
Some(Err(error)) => {
427+
return Err(media_denial(MediaError::Io(error.to_string()), strictness))
428+
}
420429
None => break,
421430
}
422431
}
423432
let replay = futures_util::stream::iter(replay_chunks.into_iter().map(Ok)).chain(source);
424433

425-
serving_write.verify().await.map_err(serving_lease_lost)?;
434+
serving_write
435+
.verify()
436+
.await
437+
.map_err(serving_lease_lost)
438+
.map_err(MediaDenial::from)?;
426439

427440
let mut descriptor = serving_write
428441
.protect(async {
@@ -501,7 +514,15 @@ pub async fn upload_blob(
501514
Err(_) => MediaError::Internal,
502515
}
503516
}
504-
})??;
517+
})
518+
// The outer anyhow→MediaError map above captures lease-loss and
519+
// protect-layer failures. Apply media_denial so Strict produces
520+
// byte-exact NIP-FI responses for those errors.
521+
.map_err(|e| media_denial(e, strictness))?
522+
// The inner Result captures failures from the async body (process_*,
523+
// hash mismatches). Wrap through media_denial so post-body auth errors
524+
// get the same NIP-FI shape as pre-body ones.
525+
.map_err(|e| media_denial(e, strictness))?;
505526

506527
rewrite_descriptor_urls_for_tenant(
507528
&mut descriptor,
@@ -1272,6 +1293,106 @@ mod tests {
12721293
}
12731294
}
12741295

1296+
// ── Extractor hash-check denial sites (sites 1+2 per Paul's spot-check) ──
1297+
// These pins cover the missing-X-SHA-256 header (MissingTag) and the
1298+
// malformed/unmatched hash (HashMismatch) cases that previously bypassed
1299+
// the strictness split via `From<MediaError> for MediaDenial` (Permissive).
1300+
1301+
#[tokio::test]
1302+
async fn strict_missing_x_sha256_header_produces_nip_fi_403() {
1303+
let denial = MediaDenial(
1304+
MediaError::MissingTag("x-sha-256"),
1305+
BlossomStrictness::Strict,
1306+
);
1307+
let resp = denial.into_response();
1308+
assert_eq!(
1309+
resp.status(),
1310+
StatusCode::FORBIDDEN,
1311+
"missing x-sha-256 header must be 403 in Strict mode"
1312+
);
1313+
let ct = resp
1314+
.headers()
1315+
.get("content-type")
1316+
.and_then(|v| v.to_str().ok())
1317+
.unwrap_or("");
1318+
assert!(
1319+
ct.contains("text/plain"),
1320+
"expected text/plain CT, got: {ct}"
1321+
);
1322+
assert!(
1323+
resp.headers().get("www-authenticate").is_none(),
1324+
"403 must not have WWW-Authenticate"
1325+
);
1326+
let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
1327+
assert_eq!(body.as_ref(), b"evidence rejected\n");
1328+
}
1329+
1330+
#[tokio::test]
1331+
async fn strict_hash_mismatch_produces_nip_fi_403() {
1332+
let denial = MediaDenial(MediaError::HashMismatch, BlossomStrictness::Strict);
1333+
let resp = denial.into_response();
1334+
assert_eq!(
1335+
resp.status(),
1336+
StatusCode::FORBIDDEN,
1337+
"hash mismatch must be 403 in Strict mode"
1338+
);
1339+
let ct = resp
1340+
.headers()
1341+
.get("content-type")
1342+
.and_then(|v| v.to_str().ok())
1343+
.unwrap_or("");
1344+
assert!(ct.contains("text/plain"), "expected text/plain, got: {ct}");
1345+
let body = to_bytes(resp.into_body(), usize::MAX).await.unwrap();
1346+
assert_eq!(body.as_ref(), b"evidence rejected\n");
1347+
}
1348+
1349+
#[tokio::test]
1350+
async fn permissive_missing_x_sha256_header_keeps_legacy_json_401() {
1351+
let denial = MediaDenial(
1352+
MediaError::MissingTag("x-sha-256"),
1353+
BlossomStrictness::Permissive,
1354+
);
1355+
let resp = denial.into_response();
1356+
assert_eq!(
1357+
resp.status(),
1358+
StatusCode::UNAUTHORIZED,
1359+
"Permissive must keep legacy 401 for MissingTag"
1360+
);
1361+
let ct = resp
1362+
.headers()
1363+
.get("content-type")
1364+
.and_then(|v| v.to_str().ok())
1365+
.unwrap_or("");
1366+
assert!(
1367+
ct.contains("application/json"),
1368+
"Permissive must keep JSON CT, got: {ct}"
1369+
);
1370+
assert!(
1371+
resp.headers().get("www-authenticate").is_none(),
1372+
"Permissive must not add WWW-Authenticate"
1373+
);
1374+
}
1375+
1376+
#[tokio::test]
1377+
async fn permissive_hash_mismatch_keeps_legacy_json_401() {
1378+
let denial = MediaDenial(MediaError::HashMismatch, BlossomStrictness::Permissive);
1379+
let resp = denial.into_response();
1380+
assert_eq!(
1381+
resp.status(),
1382+
StatusCode::UNAUTHORIZED,
1383+
"Permissive must keep legacy 401 for HashMismatch"
1384+
);
1385+
let ct = resp
1386+
.headers()
1387+
.get("content-type")
1388+
.and_then(|v| v.to_str().ok())
1389+
.unwrap_or("");
1390+
assert!(
1391+
ct.contains("application/json"),
1392+
"Permissive must keep JSON CT, got: {ct}"
1393+
);
1394+
}
1395+
12751396
#[test]
12761397
fn serving_write_error_taxonomy_separates_fence_from_backend_failure() {
12771398
let fenced = anyhow::Error::from(buzz_db::DbError::AccessDenied("fenced".to_string()));

0 commit comments

Comments
 (0)