A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
fix(media-proxy): correct route errors and test the ip gate (#2495)
Hampus710a6f1c5d21
diff --git a/fluxer_media_proxy/src/bunny_ip_gate.rs b/fluxer_media_proxy/src/bunny_ip_gate.rsindex becfec425..5897defd1 100644--- a/fluxer_media_proxy/src/bunny_ip_gate.rs+++ b/fluxer_media_proxy/src/bunny_ip_gate.rs@@ -25,12 +25,12 @@ pub struct Allowlist {}impl Allowlist {- pub fn len(&self) -> usize {- self.ips.len()+ fn is_empty(&self) -> bool {+ self.ips.is_empty()}- pub fn is_empty(&self) -> bool {- self.ips.is_empty()+ fn len(&self) -> usize {+ self.ips.len()}pub fn contains(&self, ip: &IpAddr) -> bool {@@ -225,7 +225,9 @@ pub fn build_refresh_client() -> reqwest::Result<reqwest::Client> {mod tests {use super::*;use crate::test_fixtures::ADVERSARIAL_TEXT_INPUTS;+ use axum::{Router, middleware, routing::get};use std::net::{Ipv4Addr, Ipv6Addr};+ use tower::ServiceExt;fn ip4(a: u8, b: u8, c: u8, d: u8) -> IpAddr {IpAddr::V4(Ipv4Addr::new(a, b, c, d))@@ -413,4 +415,55 @@ mod tests {}}}++ #[tokio::test]+ async fn gate_after_successful_refresh_never_returns_503() {+ let gate = Arc::new(BunnyIpGate::new(reqwest::Client::new(), vec![]));+ gate.install_for_test(Allowlist::from_ips([ip4(89, 187, 188, 227)]));+ let app = Router::new()+ .route("/asset.png", get(|| async { "ok" }))+ .layer(middleware::from_fn_with_state(gate, gate_middleware));+ let allowed = app+ .clone()+ .oneshot(+ Request::builder()+ .uri("/asset.png")+ .extension(ConnectInfo(sock(ip4(89, 187, 188, 227))))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(StatusCode::OK, allowed.status());+ let foreign = app+ .oneshot(+ Request::builder()+ .uri("/asset.png")+ .extension(ConnectInfo(sock(ip4(1, 1, 1, 1))))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(StatusCode::FORBIDDEN, foreign.status());+ }++ #[tokio::test]+ async fn an_empty_allowlist_refuses_a_public_request() {+ let gate = Arc::new(BunnyIpGate::new(reqwest::Client::new(), vec![]));+ let app = Router::new()+ .route("/asset.png", get(|| async { "ok" }))+ .layer(middleware::from_fn_with_state(gate, gate_middleware));+ let refused = app+ .oneshot(+ Request::builder()+ .uri("/asset.png")+ .extension(ConnectInfo(sock(ip4(89, 187, 188, 227))))+ .body(Body::empty())+ .unwrap(),+ )+ .await+ .unwrap();+ assert_eq!(StatusCode::SERVICE_UNAVAILABLE, refused.status());+ }}diff --git a/fluxer_media_proxy/src/server/relay/tests.rs b/fluxer_media_proxy/src/server/relay/tests.rsindex de4185176..1f27e8709 100644--- a/fluxer_media_proxy/src/server/relay/tests.rs+++ b/fluxer_media_proxy/src/server/relay/tests.rs@@ -7,7 +7,7 @@ use crate::{config::Config,secret::SecretBytes,server::{- routes::relay::{relay_cors, relay_put},+ routes::relay::{relay_cors, relay_error, relay_put},state::AppState,},upload_relay::{@@ -16,7 +16,7 @@ use crate::{},};use axum::{- body::Body,+ body::{Body, to_bytes},extract::{Path, Query, State},http::{HeaderMap, HeaderValue, Method, Request, StatusCode, header},};@@ -278,6 +278,103 @@ fn relay_test_token(key: &str, relay_secret: &[u8]) -> String {.unwrap()}+#[test]+fn relay_capability_mismatches_are_forbidden() {+ for err in [+ RelayError::WrongBucket,+ RelayError::KeyMismatch,+ RelayError::MethodMismatch,+ RelayError::PartNumberMismatch,+ RelayError::UploadIdMismatch,+ ] {+ assert_eq!(+ StatusCode::FORBIDDEN,+ relay_error(err).status(),+ "{err} must answer 403"+ );+ }++ assert_eq!(+ StatusCode::BAD_REQUEST,+ relay_error(RelayError::BadQuery).status()+ );+ assert_eq!(+ StatusCode::UNAUTHORIZED,+ relay_error(RelayError::InvalidToken).status()+ );+ assert_eq!(+ StatusCode::INTERNAL_SERVER_ERROR,+ relay_error(RelayError::InternalError).status()+ );+}++#[tokio::test]+async fn relay_put_rejects_a_capability_issued_for_another_key() {+ let tmp = tempfile::tempdir().unwrap();+ let tmp_root = tmp.path().canonicalize().unwrap();+ let storage_root = tmp_root.join("storage");+ let spool_dir = tmp_root.join("spool");+ tokio::fs::create_dir_all(&spool_dir).await.unwrap();+ let relay_secret = [7u8; 32];+ let cfg = upload_relay_test_config(&storage_root, &spool_dir, &relay_secret);+ let token = relay_test_token("guild/a.bin", &relay_secret);+ let requested_key = "guild/b.bin";++ let response = relay_put(+ State(test_app_state(cfg)),+ Path(requested_key.to_owned()),+ Query(HashMap::from([("t".to_owned(), token)])),+ HeaderMap::new(),+ Request::builder()+ .method(Method::PUT)+ .body(Body::from(Bytes::from_static(b"not mine to write")))+ .unwrap(),+ )+ .await;++ assert_eq!(StatusCode::FORBIDDEN, response.status());+ assert!(+ response+ .headers()+ .contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN)+ );+ assert!(+ !tokio::fs::try_exists(storage_root.join("uploads").join(requested_key))+ .await+ .unwrap_or(false)+ );+}++#[tokio::test]+async fn relay_put_answers_500_when_the_spool_write_fails() {+ let tmp = tempfile::tempdir().unwrap();+ let tmp_root = tmp.path().canonicalize().unwrap();+ let storage_root = tmp_root.join("storage");+ let spool_dir = tmp_root.join("missing-spool");+ let relay_secret = [7u8; 32];+ let cfg = upload_relay_test_config(&storage_root, &spool_dir, &relay_secret);+ let key = "guild/unspoolable.bin";+ let token = relay_test_token(key, &relay_secret);+ let request = Request::builder()+ .method(Method::PUT)+ .body(Body::from(Bytes::from_static(b"unspoolable")))+ .unwrap();+ assert!(request.headers().get(header::CONTENT_LENGTH).is_none());++ let response = relay_put(+ State(test_app_state(cfg)),+ Path(key.to_owned()),+ Query(HashMap::from([("t".to_owned(), token)])),+ HeaderMap::new(),+ request,+ )+ .await;++ assert_eq!(StatusCode::INTERNAL_SERVER_ERROR, response.status());+ let body = to_bytes(response.into_body(), 64).await.unwrap();+ assert_eq!(b"Internal Server Error", body.as_ref());+}+fn content_length_headers(declared: u64) -> HeaderMap {let mut headers = HeaderMap::new();headers.insert(diff --git a/fluxer_media_proxy/src/server/routes/internal.rs b/fluxer_media_proxy/src/server/routes/internal.rsindex 8bc4484d2..c7c5f3215 100644--- a/fluxer_media_proxy/src/server/routes/internal.rs+++ b/fluxer_media_proxy/src/server/routes/internal.rs@@ -14,13 +14,12 @@ use crate::{response::{MediaResponse,error::{- canonical_reason_str, json_response, storage_error_response, text,- text_with_reason, text_with_source,+ canonical_reason_str, json_response, storage_error_response, text, text_with_source,},media_response,},state::AppState,- transform::execution::run_transform,+ transform::execution::{run_transform, transform_error_is_timeout},},};use axum::{@@ -158,7 +157,7 @@ pub(in crate::server) async fn thumbnail_handler(}let body = match read_limited_body(request).await {Ok(body) => body,- Err(status) => return text(status, "Bad Request"),+ Err(status) => return text(status, canonical_reason_str(status)),};let req: UploadFileRequest = match serde_json::from_slice(&body) {Ok(req) => req,@@ -194,10 +193,19 @@ pub(in crate::server) async fn thumbnail_handler(height: Some(512),format: OutputFormat::WebP,resize_mode: ResizeMode::Fit,+ deadline_ms: app.media.transforms().transform_deadline_ms(),..Default::default()};match run_transform(app.media.transforms(), object.data.clone(), options).await {Ok(media) => media,+ Err(err) if transform_error_is_timeout(&err) => {+ return text_with_source(+ StatusCode::GATEWAY_TIMEOUT,+ "Gateway Timeout",+ "image_thumbnail_timeout",+ err,+ );+ }Err(err) => {return text_with_source(StatusCode::BAD_REQUEST,@@ -227,7 +235,7 @@ pub(in crate::server) async fn frames_handler(}let body = match read_limited_body(request).await {Ok(body) => body,- Err(_) => return text(StatusCode::BAD_REQUEST, "Bad Request"),+ Err(status) => return text(status, canonical_reason_str(status)),};let req: FramesRequest = match serde_json::from_slice::<FramesRequest>(&body) {Ok(req) if req.version.is_none_or(|version| version == 2) => req,@@ -235,11 +243,11 @@ pub(in crate::server) async fn frames_handler(};let input = match req.into_metadata_request().into_media_input() {Ok(input) => input,- Err(failure) => return frames_input_failure(&failure),+ Err(failure) => return failure.into_response(),};let input = match load_media_input(&app, input, MediaInputLimit::INTERNAL_REQUEST).await {Ok(input) => input,- Err(failure) => return frames_input_failure(&failure),+ Err(failure) => return failure.into_response(),};match media_process::extract_video_thumbnail(&input.data,@@ -259,10 +267,6 @@ pub(in crate::server) async fn frames_handler(}}-fn frames_input_failure(failure: &MediaFailure) -> Response {- text_with_reason(StatusCode::BAD_REQUEST, "Bad Request", failure.code())-}-fn check_internal_auth(headers: &HeaderMap, secret: &str) -> bool {let Some(auth) = headers.get(header::AUTHORIZATION)@@ -302,6 +306,7 @@ mod tests {use crate::{config::Config, test_fixtures::synthetic_png};use axum::http::HeaderValue;use http_body_util::BodyExt as _;+ use tokio::sync::mpsc;fn test_app_state() -> Arc<AppState> {let cfg = Config::load_from_iter([("FLUXER_MEDIA_PROXY_SECRET_KEY", "secret")])@@ -325,6 +330,34 @@ mod tests {.expect("json request")}+ fn oversized_request() -> Request<Body> {+ Request::builder()+ .method(Method::POST)+ .body(Body::from(Bytes::from(vec![+ 0u8;+ constants::MAX_INTERNAL_REQUEST_BODY_BYTES+ + 1+ ])))+ .expect("oversized request")+ }++ fn saturated_transform_app(storage_root: &std::path::Path) -> Arc<AppState> {+ let mut cfg = Config::load_from_iter([+ (+ "FLUXER_MEDIA_PROXY_SECRET_KEY".to_owned(),+ "secret".to_owned(),+ ),+ (+ "FLUXER_MEDIA_PROXY_STORAGE_ROOT".to_owned(),+ storage_root.display().to_string(),+ ),+ ])+ .expect("test config");+ cfg.media.max_native_transforms = 1;+ cfg.media.worker_queue_capacity = 0;+ Arc::new(AppState::for_tests(cfg))+ }+async fn response_body(response: Response) -> String {let bytes = response.into_body()@@ -405,4 +438,77 @@ mod tests {assert_eq!(StatusCode::OK, response.status());assert!(response_body(response).await.contains("\"width\":4"));}++ #[tokio::test]+ async fn thumbnail_answers_an_oversized_body_with_413_payload_too_large() {+ let response = thumbnail_handler(+ State(test_app_state()),+ authorized_headers(),+ oversized_request(),+ )+ .await;++ assert_eq!(StatusCode::PAYLOAD_TOO_LARGE, response.status());+ assert_eq!("Payload Too Large", response_body(response).await);+ }++ #[tokio::test]+ async fn frames_answers_an_oversized_body_with_413_payload_too_large() {+ let response = frames_handler(+ State(test_app_state()),+ authorized_headers(),+ oversized_request(),+ )+ .await;++ assert_eq!(StatusCode::PAYLOAD_TOO_LARGE, response.status());+ assert_eq!("Payload Too Large", response_body(response).await);+ }++ #[tokio::test]+ async fn thumbnail_answers_a_full_admission_pool_with_504_gateway_timeout() {+ let tmp = tempfile::tempdir().expect("temp storage root");+ let storage_root = tmp.path().canonicalize().expect("canonical storage root");+ let app = saturated_transform_app(&storage_root);+ app.store+ .write_object(+ &app.cfg.storage.bucket_uploads,+ "thumb.png",+ &synthetic_png(8, 8),+ "image/png",+ )+ .await+ .expect("stored upload");+ let (release, mut released) = mpsc::channel::<()>(1);+ let (started, mut has_started) = mpsc::channel::<()>(1);+ let holder = Arc::clone(&app);+ let held = tokio::spawn(async move {+ holder+ .media+ .transforms()+ .tasks()+ .run_native(None, move || {+ let _ = started.blocking_send(());+ let _ = released.blocking_recv();+ Ok(())+ })+ .await+ });+ has_started+ .recv()+ .await+ .expect("the held transform started");++ let response = thumbnail_handler(+ State(Arc::clone(&app)),+ authorized_headers(),+ json_request(r#"{"upload_filename":"thumb.png"}"#.to_owned()),+ )+ .await;++ assert_eq!(StatusCode::GATEWAY_TIMEOUT, response.status());+ assert_eq!("Gateway Timeout", response_body(response).await);+ drop(release);+ held.await.expect("held task").expect("held work");+ }}diff --git a/fluxer_media_proxy/src/server/routes/ops.rs b/fluxer_media_proxy/src/server/routes/ops.rsindex 46b44516a..080fb895f 100644--- a/fluxer_media_proxy/src/server/routes/ops.rs+++ b/fluxer_media_proxy/src/server/routes/ops.rs@@ -1,6 +1,9 @@// SPDX-License-Identifier: AGPL-3.0-or-later-use crate::{http_headers, server::state::AppState};+use crate::{+ http_headers,+ server::{response::error::text, state::AppState},+};use axum::{body::Body,extract::{ConnectInfo, State},@@ -22,13 +25,7 @@ pub(in crate::server) async fn metrics_handler(State(app): State<Arc<AppState>>,) -> Response {if !is_loopback_peer(&peer) {- let mut denied = Response::new(Body::from("FORBIDDEN"));- *denied.status_mut() = StatusCode::FORBIDDEN;- http_headers::add_security_headers(denied.headers_mut());- denied- .headers_mut()- .insert(header::CONTENT_TYPE, HeaderValue::from_static("text/plain"));- return denied;+ return text(StatusCode::FORBIDDEN, "FORBIDDEN");}let mut response = Response::new(Body::from(app.metrics.render()));http_headers::add_security_headers(response.headers_mut());@@ -45,11 +42,19 @@ pub(in crate::server) async fn metrics_handler(#[cfg(test)]mod tests {use super::*;+ use crate::config::Config;+ use axum::body::to_bytes;fn test_peer(value: &str) -> SocketAddr {value.parse().expect("valid socket address")}+ fn test_app_state() -> Arc<AppState> {+ let cfg = Config::load_from_iter([("FLUXER_MEDIA_PROXY_SECRET_KEY", "secret")])+ .expect("test config");+ Arc::new(AppState::for_tests(cfg))+ }+#[test]fn metrics_guard_accepts_loopback_peers() {assert!(is_loopback_peer(&test_peer("127.0.0.1:5000")));@@ -66,4 +71,31 @@ mod tests {assert!(!is_loopback_peer(&test_peer("[fe80::1]:5000")));assert!(!is_loopback_peer(&test_peer("[::ffff:8.8.8.8]:5000")));}++ #[tokio::test]+ async fn metrics_denial_uses_the_shared_text_shape() {+ let response = metrics_handler(+ ConnectInfo(test_peer("8.8.8.8:5000")),+ State(test_app_state()),+ )+ .await;++ assert_eq!(StatusCode::FORBIDDEN, response.status());+ assert_eq!(+ "text/plain; charset=utf-8",+ response+ .headers()+ .get(header::CONTENT_TYPE)+ .expect("content type")+ );+ assert_eq!(+ "no-store",+ response+ .headers()+ .get(header::CACHE_CONTROL)+ .expect("cache policy")+ );+ let body = to_bytes(response.into_body(), 64).await.expect("body");+ assert_eq!(b"FORBIDDEN", body.as_ref());+ }}diff --git a/fluxer_media_proxy/src/server/routes/relay.rs b/fluxer_media_proxy/src/server/routes/relay.rsindex 2da254c56..9c5394ddf 100644--- a/fluxer_media_proxy/src/server/routes/relay.rs+++ b/fluxer_media_proxy/src/server/routes/relay.rs@@ -234,9 +234,15 @@ pub(in crate::server) fn relay_error(err: RelayError) -> Response {RelayError::MissingToken | RelayError::InvalidToken | RelayError::RelayTokenExpired => {StatusCode::UNAUTHORIZED}+ RelayError::WrongBucket+ | RelayError::KeyMismatch+ | RelayError::MethodMismatch+ | RelayError::PartNumberMismatch+ | RelayError::UploadIdMismatch => StatusCode::FORBIDDEN,RelayError::PayloadTooLarge => StatusCode::PAYLOAD_TOO_LARGE,RelayError::UpstreamRetryable => StatusCode::SERVICE_UNAVAILABLE,RelayError::UpstreamS3Error => StatusCode::BAD_GATEWAY,+ RelayError::InternalError => StatusCode::INTERNAL_SERVER_ERROR,_ => StatusCode::BAD_REQUEST,};let mut response = text(status, status.canonical_reason().unwrap_or("Bad Request"));