This is an automated email from the ASF dual-hosted git repository. Xuanwo pushed a commit to branch xuanwo/fix-http-endpoint-errors-and-uri-creds in repository https://gitbox.apache.org/repos/asf/opendal.git
commit c0c49e727a81c096a867b8be4a2e5ccc4742c539 Author: Xuanwo <[email protected]> AuthorDate: Tue Nov 24 01:51:11 2026 +0100 fix(services/http): normalize and validate endpoint, map 401/429 errors, and parse URI credentials --- core/services/http/src/backend.rs | 302 +++++++++++++++++++++++++++++++++++++- core/services/http/src/config.rs | 83 +++++++++++ core/services/http/src/core.rs | 25 +++- core/services/http/src/docs.md | 2 +- 4 files changed, 405 insertions(+), 7 deletions(-) diff --git a/core/services/http/src/backend.rs b/core/services/http/src/backend.rs index 4dbf0bfc26..ad44ec942e 100644 --- a/core/services/http/src/backend.rs +++ b/core/services/http/src/backend.rs @@ -106,13 +106,40 @@ impl Builder for HttpBuilder { debug!("backend build started: {:?}", self); let endpoint = match &self.config.endpoint { - Some(v) => v, - None => { + Some(v) if !v.is_empty() => v, + _ => { return Err(Error::new(ErrorKind::ConfigInvalid, "endpoint is empty") .with_context("service", HTTP_SCHEME)); } }; + let uri = endpoint.parse::<http::Uri>().map_err(|err| { + Error::new(ErrorKind::ConfigInvalid, "endpoint is invalid") + .with_context("service", HTTP_SCHEME) + .set_source(err) + })?; + let is_http_scheme = matches!( + uri.scheme(), + Some(scheme) + if *scheme == http::uri::Scheme::HTTP || *scheme == http::uri::Scheme::HTTPS + ); + if !is_http_scheme || uri.host().is_none_or(str::is_empty) { + return Err(Error::new( + ErrorKind::ConfigInvalid, + "endpoint must be a valid http or https URI with a host", + ) + .with_context("service", HTTP_SCHEME)); + } + if uri.query().is_some() || endpoint.contains('#') { + return Err(Error::new( + ErrorKind::ConfigInvalid, + "endpoint must not contain a query or fragment", + ) + .with_context("service", HTTP_SCHEME)); + } + + let endpoint = endpoint.trim_end_matches('/').to_string(); + let root = normalize_root(&self.config.root.unwrap_or_default()); debug!("backend use root {root}"); @@ -157,7 +184,7 @@ impl Builder for HttpBuilder { let core = Arc::new(HttpCore { info: accessor_info, capability, - endpoint: endpoint.to_string(), + endpoint, root, authorization: auth, }); @@ -316,3 +343,272 @@ impl Service for HttpBackend { ))) } } + +#[cfg(test)] +mod tests { + use std::sync::Mutex; + use std::time::Duration; + + use http::Method; + use http::Request; + use http::Response; + use http::Uri; + use http::header; + + use super::*; + + #[derive(Debug)] + struct RecordedRequest { + method: Method, + uri: Uri, + authorization: Option<String>, + } + + #[derive(Debug, Default)] + struct RecordingTransport { + requests: Arc<Mutex<Vec<RecordedRequest>>>, + } + + impl HttpTransport for RecordingTransport { + async fn fetch(&self, req: Request<Buffer>) -> Result<Response<HttpBody>> { + let authorization = req + .headers() + .get(header::AUTHORIZATION) + .and_then(|v| v.to_str().ok()) + .map(str::to_string); + self.requests + .lock() + .expect("requests lock must not be poisoned") + .push(RecordedRequest { + method: req.method().clone(), + uri: req.uri().clone(), + authorization, + }); + + let body = if req.method() == Method::HEAD { + HttpBody::new(futures::stream::empty(), Some(0)) + } else { + HttpBody::new(futures::stream::iter([Ok(Buffer::from("hello"))]), Some(5)) + }; + + Ok(Response::builder() + .status(StatusCode::OK) + .header(header::CONTENT_LENGTH, "5") + .body(body) + .expect("response must build")) + } + } + + #[derive(Debug)] + struct StatusTransport { + status: StatusCode, + } + + impl HttpTransport for StatusTransport { + async fn fetch(&self, _req: Request<Buffer>) -> Result<Response<HttpBody>> { + let body = Buffer::from(self.status.canonical_reason().unwrap_or("error")); + let len = body.len() as u64; + Ok(Response::builder() + .status(self.status) + .body(HttpBody::new(futures::stream::iter([Ok(body)]), Some(len))) + .expect("response must build")) + } + } + + #[test] + fn build_rejects_invalid_endpoint() { + let missing_err = + Operator::new(HttpBuilder::default()).expect_err("missing endpoint must fail"); + assert_eq!(missing_err.kind(), ErrorKind::ConfigInvalid); + + let empty_cfg = HttpConfig { + endpoint: Some(String::new()), + ..Default::default() + }; + let empty_err = + Operator::new(empty_cfg.into_builder()).expect_err("empty endpoint must fail"); + assert_eq!(empty_err.kind(), ErrorKind::ConfigInvalid); + + let invalid_endpoints = [ + "example.com", + "127.0.0.1", + "127.0.0.1:8080", + "ftp://example.com", + "file:///tmp", + "https://", + "http:///path", + "https://:8080", + "https://example.com/bad path", + "https://example.com#frag", + "https://example.com/prefix#frag", + "https://example.com?foo=bar", + "https://example.com/prefix?foo=bar", + ]; + + for endpoint in invalid_endpoints { + let err = Operator::new(HttpBuilder::default().endpoint(endpoint)) + .expect_err(&format!("invalid endpoint `{endpoint}` must be rejected")); + assert_eq!(err.kind(), ErrorKind::ConfigInvalid, "endpoint={endpoint}"); + } + } + + #[tokio::test] + async fn build_normalizes_trailing_slashes_across_stat_read_and_presign() -> Result<()> { + let cases = [ + ("https://example.com", "", "https://example.com/file.txt"), + ("https://example.com/", "", "https://example.com/file.txt"), + ("https://example.com///", "", "https://example.com/file.txt"), + ( + "https://example.com/prefix/", + "", + "https://example.com/prefix/file.txt", + ), + ( + "https://example.com/prefix/", + "sub", + "https://example.com/prefix/sub/file.txt", + ), + ("http://[::1]:8080/", "", "http://[::1]:8080/file.txt"), + ("HTTP://example.com/", "", "http://example.com/file.txt"), + ]; + + for (endpoint, root, expected_uri) in cases { + let requests = Arc::new(Mutex::new(Vec::new())); + let mut builder = HttpBuilder::default().endpoint(endpoint); + if !root.is_empty() { + builder = builder.root(root); + } + let op = + Operator::new(builder)?.with_context(OperationContext::new().with_http_transport( + HttpTransporter::new(RecordingTransport { + requests: requests.clone(), + }), + )); + + let meta = op.stat("file.txt").await?; + assert_eq!(meta.content_length(), 5, "endpoint={endpoint} root={root}"); + + let data = op.read("file.txt").await?; + assert_eq!( + data.to_bytes(), + b"hello".as_slice(), + "endpoint={endpoint} root={root}" + ); + + let presign_stat = op.presign_stat("file.txt", Duration::from_secs(60)).await?; + assert_eq!( + presign_stat.uri().to_string(), + expected_uri, + "presign_stat endpoint={endpoint} root={root}" + ); + + let presign_read = op.presign_read("file.txt", Duration::from_secs(60)).await?; + assert_eq!( + presign_read.uri().to_string(), + expected_uri, + "presign_read endpoint={endpoint} root={root}" + ); + + let recorded = requests.lock().expect("requests lock must not be poisoned"); + assert_eq!(recorded.len(), 2, "endpoint={endpoint} root={root}"); + assert_eq!(recorded[0].method, Method::HEAD); + assert_eq!(recorded[0].uri.to_string(), expected_uri); + assert_eq!(recorded[1].method, Method::GET); + assert_eq!(recorded[1].uri.to_string(), expected_uri); + } + + Ok(()) + } + + #[tokio::test] + async fn stat_and_read_map_401_and_429_errors() -> Result<()> { + let unauthorized_op = Operator::new( + HttpBuilder::default().endpoint("https://example.com"), + )? + .with_context( + OperationContext::new().with_http_transport(HttpTransporter::new(StatusTransport { + status: StatusCode::UNAUTHORIZED, + })), + ); + + for err in [ + unauthorized_op + .stat("file.txt") + .await + .expect_err("401 stat on file must fail"), + unauthorized_op + .stat("dir/") + .await + .expect_err("401 stat on dir must fail"), + unauthorized_op + .read("file.txt") + .await + .expect_err("401 read must fail"), + ] { + assert_eq!(err.kind(), ErrorKind::PermissionDenied); + assert!(!err.is_temporary()); + } + + let rate_limited_op = Operator::new( + HttpBuilder::default().endpoint("https://example.com"), + )? + .with_context( + OperationContext::new().with_http_transport(HttpTransporter::new(StatusTransport { + status: StatusCode::TOO_MANY_REQUESTS, + })), + ); + + for err in [ + rate_limited_op + .stat("file.txt") + .await + .expect_err("429 stat must fail"), + rate_limited_op + .read("file.txt") + .await + .expect_err("429 read must fail"), + ] { + assert_eq!(err.kind(), ErrorKind::RateLimited); + assert!(err.is_temporary()); + } + + Ok(()) + } + + #[tokio::test] + async fn from_uri_credentials_send_basic_auth_and_disable_presign() -> Result<()> { + crate::register_http_service(OperatorRegistry::get()); + + let requests = Arc::new(Mutex::new(Vec::new())); + let op = Operator::from_uri("https://alice:[email protected]/static")?.with_context( + OperationContext::new().with_http_transport(HttpTransporter::new(RecordingTransport { + requests: requests.clone(), + })), + ); + + let cap = op.info().capability(); + assert!(!cap.presign); + assert!(!cap.presign_read); + assert!(!cap.presign_stat); + + let presign_err = op + .presign_read("file.txt", Duration::from_secs(60)) + .await + .expect_err("presign must be rejected when URI carries credentials"); + assert_eq!(presign_err.kind(), ErrorKind::Unsupported); + + op.stat("file.txt").await?; + let data = op.read("file.txt").await?; + assert_eq!(data.to_bytes(), b"hello".as_slice()); + + let expected_auth = format_authorization_by_basic("alice", "secret")?; + let recorded = requests.lock().expect("requests lock must not be poisoned"); + assert_eq!(recorded.len(), 2); + for req in recorded.iter() { + assert_eq!(req.uri.to_string(), "https://example.com/static/file.txt"); + assert_eq!(req.authorization.as_deref(), Some(expected_auth.as_str())); + } + + Ok(()) + } +} diff --git a/core/services/http/src/config.rs b/core/services/http/src/config.rs index 77a62fc695..8fa9012e6a 100644 --- a/core/services/http/src/config.rs +++ b/core/services/http/src/config.rs @@ -60,6 +60,16 @@ impl opendal_core::Configurator for HttpConfig { ); } + if let Some(username) = uri.username() { + map.entry("username".to_string()) + .or_insert_with(|| username.to_string()); + } + + if let Some(password) = uri.password() { + map.entry("password".to_string()) + .or_insert_with(|| password.to_string()); + } + if let Some(root) = uri.root() { map.insert("root".to_string(), root.to_string()); } @@ -157,4 +167,77 @@ mod tests { let cfg = HttpConfig::from_uri(&uri).unwrap(); assert_eq!(cfg.endpoint.as_deref(), Some("https://example.com")); } + + #[test] + fn from_uri_extracts_credentials() { + let uri = OperatorUri::new( + "https://alice:[email protected]/static", + Vec::<(String, String)>::new(), + ) + .unwrap(); + let cfg = HttpConfig::from_uri(&uri).unwrap(); + assert_eq!(cfg.endpoint.as_deref(), Some("https://example.com")); + assert_eq!(cfg.root.as_deref(), Some("static")); + assert_eq!(cfg.username.as_deref(), Some("alice")); + assert_eq!(cfg.password.as_deref(), Some("secret")); + + let encoded = OperatorUri::new( + "https://alice%40corp:p%40ss%[email protected]/static", + Vec::<(String, String)>::new(), + ) + .unwrap(); + let cfg = HttpConfig::from_uri(&encoded).unwrap(); + assert_eq!(cfg.username.as_deref(), Some("alice@corp")); + assert_eq!(cfg.password.as_deref(), Some("p@ss:word")); + + let user_only = OperatorUri::new( + "https://[email protected]/static", + Vec::<(String, String)>::new(), + ) + .unwrap(); + let cfg = HttpConfig::from_uri(&user_only).unwrap(); + assert_eq!(cfg.username.as_deref(), Some("alice")); + assert!(cfg.password.is_none()); + } + + #[test] + fn from_uri_respects_explicit_credential_overrides() { + let uri = OperatorUri::new( + "https://alice:[email protected]/static", + vec![ + ("username".to_string(), "bob".to_string()), + ("password".to_string(), "opt-secret".to_string()), + ], + ) + .unwrap(); + let cfg = HttpConfig::from_uri(&uri).unwrap(); + assert_eq!(cfg.username.as_deref(), Some("bob")); + assert_eq!(cfg.password.as_deref(), Some("opt-secret")); + + let query_uri = OperatorUri::new( + "https://alice:[email protected]/static?username=carol&password=query-secret", + Vec::<(String, String)>::new(), + ) + .unwrap(); + let cfg = HttpConfig::from_uri(&query_uri).unwrap(); + assert_eq!(cfg.username.as_deref(), Some("carol")); + assert_eq!(cfg.password.as_deref(), Some("query-secret")); + } + + #[test] + fn operator_from_uri_credentials_disable_presign() { + register_http(); + + let authed = Operator::from_uri("https://alice:[email protected]/static").unwrap(); + let authed_cap = authed.info().capability(); + assert!(!authed_cap.presign); + assert!(!authed_cap.presign_read); + assert!(!authed_cap.presign_stat); + + let unauthed = Operator::from_uri("https://example.com/static").unwrap(); + let unauthed_cap = unauthed.info().capability(); + assert!(unauthed_cap.presign); + assert!(unauthed_cap.presign_read); + assert!(unauthed_cap.presign_stat); + } } diff --git a/core/services/http/src/core.rs b/core/services/http/src/core.rs index 80e81902f2..59ce4d7386 100644 --- a/core/services/http/src/core.rs +++ b/core/services/http/src/core.rs @@ -184,13 +184,13 @@ pub(crate) fn parse_error(ctx: ErrorContext, resp: Response<Buffer>) -> Error { let (kind, retryable) = match parts.status { StatusCode::NOT_FOUND => (ErrorKind::NotFound, false), - StatusCode::FORBIDDEN => (ErrorKind::PermissionDenied, false), + StatusCode::UNAUTHORIZED | StatusCode::FORBIDDEN => (ErrorKind::PermissionDenied, false), StatusCode::PRECONDITION_FAILED | StatusCode::NOT_MODIFIED => { (ErrorKind::ConditionNotMatch, false) } StatusCode::RANGE_NOT_SATISFIABLE => (ErrorKind::RangeNotSatisfied, false), - StatusCode::TOO_MANY_REQUESTS - | StatusCode::INTERNAL_SERVER_ERROR + StatusCode::TOO_MANY_REQUESTS => (ErrorKind::RateLimited, true), + StatusCode::INTERNAL_SERVER_ERROR | StatusCode::BAD_GATEWAY | StatusCode::SERVICE_UNAVAILABLE | StatusCode::GATEWAY_TIMEOUT => (ErrorKind::Unexpected, true), @@ -236,6 +236,25 @@ mod tests { assert_eq!(err.kind(), ErrorKind::RangeNotSatisfied); } + #[test] + fn test_parse_unauthorized_and_rate_limited() { + let unauthorized = Response::builder() + .status(StatusCode::UNAUTHORIZED) + .body(Buffer::from("unauthorized")) + .expect("response must be valid"); + let err = parse_error(ErrorContext::new(ServiceOperation("Get")), unauthorized); + assert_eq!(err.kind(), ErrorKind::PermissionDenied); + assert!(!err.is_temporary()); + + let rate_limited = Response::builder() + .status(StatusCode::TOO_MANY_REQUESTS) + .body(Buffer::from("too many requests")) + .expect("response must be valid"); + let err = parse_error(ErrorContext::new(ServiceOperation("Head")), rate_limited); + assert_eq!(err.kind(), ErrorKind::RateLimited); + assert!(err.is_temporary()); + } + #[test] fn test_http_get_request_rejects_unrepresentable_range() { let core = test_core(); diff --git a/core/services/http/src/docs.md b/core/services/http/src/docs.md index f61f65a1b4..2030834d81 100644 --- a/core/services/http/src/docs.md +++ b/core/services/http/src/docs.md @@ -38,7 +38,7 @@ use opendal_service_http::Http; #[tokio::main] async fn main() -> Result<()> { // create http backend builder - let mut builder = Http::default().endpoint("127.0.0.1"); + let builder = Http::default().endpoint("https://example.com"); let op: Operator = Operator::new(builder)?; Ok(())
