π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[rust][core] add bare object store HTTP client
Neeraj Gupta1c6ec105adfb
diff --git a/rust/core/Cargo.lock b/rust/core/Cargo.lockindex ff942c9e2b..ee048b03ab 100644--- a/rust/core/Cargo.lock+++ b/rust/core/Cargo.lock@@ -12,6 +12,15 @@ dependencies = ["generic-array",]+[[package]]+name = "aho-corasick"+version = "1.1.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"+dependencies = [+ "memchr",+]+[[package]]name = "argon2"version = "0.5.3"@@ -36,6 +45,16 @@ version = "0.7.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"+[[package]]+name = "assert-json-diff"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47e4f2b81832e72834d7518d8487a0396a28cc408186a2e8854c0f98011faf12"+dependencies = [+ "serde",+ "serde_json",+]+[[package]]name = "atomic-waker"version = "1.1.2"@@ -180,6 +199,15 @@ dependencies = ["zeroize",]+[[package]]+name = "colored"+version = "3.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "faf9468729b8cbcea668e36183cb69d317348c2e08e994829fb56ebfdfbaac34"+dependencies = [+ "windows-sys 0.61.2",+]+[[package]]name = "constant_time_eq"version = "0.3.1"@@ -316,6 +344,7 @@ dependencies = ["getrandom 0.2.16","hex","md-5",+ "mockito","rand_core 0.6.4","reqwest","salsa20",@@ -519,6 +548,12 @@ version = "1.10.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"+[[package]]+name = "httpdate"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"+[[package]]name = "hyper"version = "1.8.1"@@ -533,6 +568,7 @@ dependencies = ["http","http-body","httparse",+ "httpdate","itoa","pin-project-lite","pin-utils",@@ -756,6 +792,15 @@ version = "0.8.1"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "6373607a59f0be73a39b6fe456b8192fcc3585f602af20751600e974dd455e77"+[[package]]+name = "lock_api"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"+dependencies = [+ "scopeguard",+]+[[package]]name = "log"version = "0.4.29"@@ -801,6 +846,31 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "mockito"+version = "1.7.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "90820618712cab19cfc46b274c6c22546a82affcb3c3bdf0f29e3db8e1bb92c0"+dependencies = [+ "assert-json-diff",+ "bytes",+ "colored",+ "futures-core",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-util",+ "log",+ "pin-project-lite",+ "rand",+ "regex",+ "serde_json",+ "serde_urlencoded",+ "similar",+ "tokio",+]+[[package]]name = "num-bigint"version = "0.4.6"@@ -847,6 +917,29 @@ version = "0.1.6"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "d05e27ee213611ffe7d6348b942e8f942b37114c00cc03cec254295a4a17852e"+[[package]]+name = "parking_lot"+version = "0.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"+dependencies = [+ "lock_api",+ "parking_lot_core",+]++[[package]]+name = "parking_lot_core"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"+dependencies = [+ "cfg-if",+ "libc",+ "redox_syscall",+ "smallvec",+ "windows-link",+]+[[package]]name = "password-hash"version = "0.5.0"@@ -1022,6 +1115,44 @@ dependencies = ["getrandom 0.3.4",]+[[package]]+name = "redox_syscall"+version = "0.5.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"+dependencies = [+ "bitflags",+]++[[package]]+name = "regex"+version = "1.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.14"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dc897dd8d9e8bd1ed8cdad82b5966c3e0ecae09fb1907d58efaa013543185d0a"+[[package]]name = "reqwest"version = "0.12.25"@@ -1169,6 +1300,12 @@ dependencies = ["windows-sys 0.61.2",]+[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"+[[package]]name = "security-framework"version = "3.5.1"@@ -1270,6 +1407,12 @@ version = "1.3.0"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"+[[package]]+name = "similar"+version = "2.7.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbbb5d9659141646ae647b42fe094daf6c6192d1620870b449d9557f748b2daa"+[[package]]name = "slab"version = "0.4.11"@@ -1423,6 +1566,7 @@ dependencies = ["bytes","libc","mio",+ "parking_lot","pin-project-lite","socket2","tokio-macros",diff --git a/rust/core/Cargo.toml b/rust/core/Cargo.tomlindex 6ba0a1206f..7c6cf16c52 100644--- a/rust/core/Cargo.toml+++ b/rust/core/Cargo.toml@@ -40,6 +40,7 @@ zeroize = { version = "1.8", features = ["derive"] }[dev-dependencies]chacha20 = "0.9.1"tokio = { version = "1", features = ["rt-multi-thread", "macros"] }+mockito = "1.6"# Keep SRP deps available for unit tests (the SRP module is compiled under cfg(test))srp = "0.6"diff --git a/rust/core/src/http.rs b/rust/core/src/http.rsindex 84bcb0b664..04d066674e 100644--- a/rust/core/src/http.rs+++ b/rust/core/src/http.rs@@ -95,6 +95,12 @@ pub struct HttpClient {client_version: Option<String>,}+/// Bare HTTP client for presigned object-store transfers.+#[derive(Clone)]+pub struct ObjectStoreHttpClient {+ client: reqwest::Client,+}+impl HttpClient {/// Create a client with the given base URL.pub fn new(base_url: &str) -> Result<Self, Error> {@@ -142,6 +148,13 @@ impl HttpClient {*self.auth_token.write().expect("auth token lock poisoned") = auth_token;}+ /// Create a bare client for presigned object-store requests.+ pub fn object_store(&self) -> ObjectStoreHttpClient {+ ObjectStoreHttpClient {+ client: self.client.clone(),+ }+ }+/// GET request, returns response body as text.////// `path` is expected to be a trusted API endpoint path chosen by the@@ -295,9 +308,21 @@ impl HttpClient {/// Download bytes from a URL, following redirects safely.pub async fn get_bytes(&self, url: &str) -> Result<Vec<u8>, Error> {+ self.get_bytes_with_headers(url, |current_url| self.build_headers_for_url(current_url))+ .await+ }++ async fn get_bytes_with_headers<F>(+ &self,+ url: &str,+ headers_for_url: F,+ ) -> Result<Vec<u8>, Error>+ where+ F: Fn(&Url) -> Result<HeaderMap, Error>,+ {let mut current_url = self.parse_url(url)?;for _ in 0..5 {- let headers = self.build_headers_for_url(¤t_url)?;+ let headers = headers_for_url(¤t_url)?;let response = self.client.get(current_url.clone())@@ -374,30 +399,11 @@ impl HttpClient {Ok(format!("{}{}", self.base_url, path))}-/// Ping the API, returns [PingResponse].pub async fn ping(&self) -> Result<PingResponse, Error> {self.get_json("/ping", &[]).await}- fn request_url(&self, path: &str) -> Result<String, Error> {- if !path.starts_with('/') {- return Err(Error::InvalidUrl(- "request paths must start with '/'".to_string(),- ));- }-- let base = Url::parse(&self.base_url)- .map_err(|e| Error::InvalidUrl(format!("invalid base URL: {e}")))?;- if base.query().is_some() || base.fragment().is_some() {- return Err(Error::InvalidUrl(- "base URL must not contain a query or fragment".to_string(),- ));- }-- Ok(format!("{}{}", self.base_url, path))- }-fn parse_url(&self, url: &str) -> Result<Url, Error> {Url::parse(url).map_err(|e| Error::InvalidUrl(format!("invalid url: {e}")))}@@ -463,6 +469,102 @@ impl HttpClient {}}+impl ObjectStoreHttpClient {+ /// Download bytes from a presigned URL without Ente headers.+ pub async fn get_bytes(&self, url: &str) -> Result<Vec<u8>, Error> {+ get_bytes_with_client(&self.client, url, |_| Ok(HeaderMap::new())).await+ }++ /// Upload raw bytes to a presigned URL without Ente headers.+ pub async fn put_bytes(+ &self,+ url: &str,+ body: &[u8],+ headers: &[(&str, String)],+ ) -> Result<(), Error> {+ put_bytes_with_client(&self.client, url, body, headers).await+ }+}++async fn get_bytes_with_client<F>(+ client: &reqwest::Client,+ url: &str,+ headers_for_url: F,+) -> Result<Vec<u8>, Error>+where+ F: Fn(&Url) -> Result<HeaderMap, Error>,+{+ let mut current_url = parse_url(url)?;+ for _ in 0..5 {+ let headers = headers_for_url(¤t_url)?;+ let response = client+ .get(current_url.clone())+ .headers(headers)+ .send()+ .await?;+ if response.status().is_redirection()+ && let Some(location) = response.headers().get(LOCATION)+ {+ current_url = resolve_redirect(¤t_url, location)?;+ continue;+ }+ return parse_bytes_response(response).await;+ }++ Err(Error::InvalidUrl("too many redirects".to_string()))+}++async fn put_bytes_with_client(+ client: &reqwest::Client,+ url: &str,+ body: &[u8],+ headers: &[(&str, String)],+) -> Result<(), Error> {+ let header_map = build_header_map(headers)?;+ let mut current_url = parse_url(url)?;+ for _ in 0..5 {+ let response = client+ .put(current_url.clone())+ .headers(header_map.clone())+ .body(body.to_vec())+ .send()+ .await?;+ if response.status().is_redirection()+ && let Some(location) = response.headers().get(LOCATION)+ {+ current_url = resolve_redirect(¤t_url, location)?;+ continue;+ }+ return parse_empty_response(response).await;+ }++ Err(Error::InvalidUrl("too many redirects".to_string()))+}++fn build_header_map(headers: &[(&str, String)]) -> Result<HeaderMap, Error> {+ let mut header_map = HeaderMap::new();+ for (name, value) in headers {+ let header_name =+ HeaderName::from_bytes(name.as_bytes()).map_err(|e| Error::Parse(e.to_string()))?;+ let header_value = HeaderValue::from_str(value).map_err(|e| Error::Parse(e.to_string()))?;+ header_map.insert(header_name, header_value);+ }+ Ok(header_map)+}++fn parse_url(url: &str) -> Result<Url, Error> {+ Url::parse(url).map_err(|e| Error::InvalidUrl(format!("invalid url: {e}")))+}++fn resolve_redirect(current_url: &Url, location: &HeaderValue) -> Result<Url, Error> {+ let next = location+ .to_str()+ .map_err(|e| Error::InvalidUrl(format!("invalid redirect location: {e}")))?;+ Url::parse(next)+ .or_else(|_| current_url.join(next))+ .map_err(|e| Error::InvalidUrl(format!("invalid redirect location: {e}")))+}+async fn parse_text_response(response: Response) -> Result<String, Error> {if !response.status().is_success() {let status = response.status().as_u16();@@ -523,6 +625,7 @@ fn path_contains_dot_segments(path: &str) -> bool {#[cfg(test)]mod tests {use super::*;+ use mockito::{Matcher, Server};fn test_client(base_url: &str) -> HttpClient {HttpClient::new_with_config(HttpConfig {@@ -606,4 +709,90 @@ mod tests {client.set_auth_token(None);assert_eq!(client.auth_token.read().unwrap().clone(), None);}++ #[tokio::test]+ async fn api_download_includes_auth_and_public_headers_for_same_origin_urls() {+ let mut server = Server::new_async().await;+ let mock = server+ .mock("GET", "/download")+ .match_header("x-auth-token", "auth-token")+ .match_header("x-client-package", "io.ente.photos")+ .match_header("x-client-version", "1.0.0")+ .match_header("user-agent", "ente-core-test")+ .with_status(200)+ .with_body("ok")+ .create_async()+ .await;++ let client = HttpClient::new_with_config(HttpConfig {+ base_url: server.url(),+ auth_token: Some("auth-token".to_string()),+ user_agent: Some("ente-core-test".to_string()),+ client_package: Some("io.ente.photos".to_string()),+ client_version: Some("1.0.0".to_string()),+ timeout_secs: None,+ })+ .unwrap();++ let bytes = client+ .get_bytes(&format!("{}/download", server.url()))+ .await+ .unwrap();++ mock.assert_async().await;+ assert_eq!(bytes, b"ok");+ }++ #[tokio::test]+ async fn object_store_client_only_sends_explicit_headers() {+ let mut server = Server::new_async().await;+ let get_mock = server+ .mock("GET", "/download")+ .match_header("x-auth-token", Matcher::Missing)+ .match_header("x-client-package", Matcher::Missing)+ .match_header("x-client-version", Matcher::Missing)+ .match_header("user-agent", Matcher::Missing)+ .with_status(200)+ .with_body("ok")+ .create_async()+ .await;+ let put_mock = server+ .mock("PUT", "/upload")+ .match_header("content-md5", "digest")+ .match_header("x-auth-token", Matcher::Missing)+ .match_header("x-client-package", Matcher::Missing)+ .match_header("x-client-version", Matcher::Missing)+ .match_header("user-agent", Matcher::Missing)+ .with_status(200)+ .create_async()+ .await;++ let client = HttpClient::new_with_config(HttpConfig {+ base_url: server.url(),+ auth_token: Some("auth-token".to_string()),+ user_agent: Some("ente-core-test".to_string()),+ client_package: Some("io.ente.photos".to_string()),+ client_version: Some("1.0.0".to_string()),+ timeout_secs: None,+ })+ .unwrap();+ let object_store = client.object_store();++ let bytes = object_store+ .get_bytes(&format!("{}/download", server.url()))+ .await+ .unwrap();+ object_store+ .put_bytes(+ &format!("{}/upload", server.url()),+ b"payload",+ &[("Content-MD5", "digest".to_string())],+ )+ .await+ .unwrap();++ get_mock.assert_async().await;+ put_mock.assert_async().await;+ assert_eq!(bytes, b"ok");+ }}