π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
Rework the core HTTP client
Manav Rathi53f682ba2356
diff --git a/rust/Cargo.lock b/rust/Cargo.lockindex 33a5c40379..611a49eada 100644--- a/rust/Cargo.lock+++ b/rust/Cargo.lock@@ -2328,7 +2328,9 @@ dependencies = ["base64 0.22.1","bip39","blake2b_simd",+ "bytes","crypto_secretstream",+ "futures-core","getrandom 0.2.17","hex","md-5 0.11.0",diff --git a/rust/apps/cli/src/auth_flow.rs b/rust/apps/cli/src/auth_flow.rsindex 4b9de46d45..6bb86d1605 100644--- a/rust/apps/cli/src/auth_flow.rs+++ b/rust/apps/cli/src/auth_flow.rs@@ -52,7 +52,7 @@ fn to_shared_error(error: Error) -> shared::Error {status,code,message,- } => shared::Error::from(ente_core::http::Error::Http {+ } => shared::Error::from(ente_core::http_legacy::Error::Http {status,code,message,diff --git a/rust/apps/cli/src/models/error.rs b/rust/apps/cli/src/models/error.rsindex 628c67e5c3..28d2e0375f 100644--- a/rust/apps/cli/src/models/error.rs+++ b/rust/apps/cli/src/models/error.rs@@ -84,7 +84,7 @@ impl From<AuthError> for Error {impl From<AccountsError> for Error {fn from(err: AccountsError) -> Self {match err {- AccountsError::Http(ente_core::http::Error::Http {+ AccountsError::Http(ente_core::http_legacy::Error::Http {status,code,message,@@ -93,13 +93,13 @@ impl From<AccountsError> for Error {code,message,},- AccountsError::Http(ente_core::http::Error::Network(message)) => {+ AccountsError::Http(ente_core::http_legacy::Error::Network(message)) => {Error::Generic(format!("Network error: {message}"))}- AccountsError::Http(ente_core::http::Error::Parse(message)) => {+ AccountsError::Http(ente_core::http_legacy::Error::Parse(message)) => {Error::Generic(format!("JSON parse error: {message}"))}- AccountsError::Http(ente_core::http::Error::InvalidUrl(message)) => {+ AccountsError::Http(ente_core::http_legacy::Error::InvalidUrl(message)) => {Error::InvalidConfig(message)}AccountsError::Serialization(source) => Error::Serialization(source),diff --git a/rust/bindings/frb/ente-rust/src/api/contacts.rs b/rust/bindings/frb/ente-rust/src/api/contacts.rsindex f64c21d3a3..b8b9cf3321 100644--- a/rust/bindings/frb/ente-rust/src/api/contacts.rs+++ b/rust/bindings/frb/ente-rust/src/api/contacts.rs@@ -67,16 +67,18 @@ pub enum ContactsError {impl From<CoreContactsError> for ContactsError {fn from(value: CoreContactsError) -> Self {match value {- CoreContactsError::Http(ente_core::http::Error::Http {- status, message, ..+ CoreContactsError::Http(ente_core::http_legacy::Error::Http {+ status,+ message,+ ..}) => ContactsError::Http { message, status },- CoreContactsError::Http(ente_core::http::Error::Network(message)) => {+ CoreContactsError::Http(ente_core::http_legacy::Error::Network(message)) => {ContactsError::Network { message }}- CoreContactsError::Http(ente_core::http::Error::Parse(message)) => {+ CoreContactsError::Http(ente_core::http_legacy::Error::Parse(message)) => {ContactsError::Parse { message }}- CoreContactsError::Http(ente_core::http::Error::InvalidUrl(message)) => {+ CoreContactsError::Http(ente_core::http_legacy::Error::InvalidUrl(message)) => {ContactsError::InvalidUrl { message }}CoreContactsError::Crypto(message) => ContactsError::Crypto {diff --git a/rust/bindings/frb/ente-rust/src/api/http.rs b/rust/bindings/frb/ente-rust/src/api/http.rsindex e99bc59a3a..bc6ef269d9 100644--- a/rust/bindings/frb/ente-rust/src/api/http.rs+++ b/rust/bindings/frb/ente-rust/src/api/http.rs@@ -1,6 +1,6 @@//! FRB bindings for the HTTP client-use ente_core::http::{Error as CoreError, HttpClient as CoreHttpClient};+use ente_core::http_legacy::{Error as CoreError, HttpClient as CoreHttpClient};use flutter_rust_bridge::frb;/// HTTP client errors.diff --git a/rust/bindings/wasm/ente-wasm/src/http.rs b/rust/bindings/wasm/ente-wasm/src/http.rsindex 7ee6731da7..3be5c536dc 100644--- a/rust/bindings/wasm/ente-wasm/src/http.rs+++ b/rust/bindings/wasm/ente-wasm/src/http.rs@@ -1,6 +1,6 @@//! WASM bindings for the HTTP client.-use ente_core::http::{Error as CoreError, HttpClient as CoreHttpClient};+use ente_core::http_legacy::{Error as CoreError, HttpClient as CoreHttpClient};use wasm_bindgen::prelude::*;/// HTTP client error.diff --git a/rust/crates/accounts/src/client.rs b/rust/crates/accounts/src/client.rsindex 04ac283bec..82c7398301 100644--- a/rust/crates/accounts/src/client.rs+++ b/rust/crates/accounts/src/client.rs@@ -4,7 +4,7 @@ use base64::{Engine, engine::general_purpose::STANDARD};use ente_core::{auth::{SrpAttributes as CoreSrpAttributes, SrpSession},crypto::SecretVec,- http::{Error as HttpError, HttpClient},+ http_legacy::{Error as HttpError, HttpClient},};use std::time::Duration;@@ -52,7 +52,7 @@ fn require_srp_m2(auth_response: &AuthResponse) -> Result<&str> {.ok_or_else(|| Error::AuthenticationFailed("Missing server proof".to_string()))}-/// Shared account client built on `ente_core::http::HttpClient`.+/// Shared account client built on `ente_core::http_legacy::HttpClient`.pub struct AccountsClient {http: HttpClient,client_package: String,diff --git a/rust/crates/accounts/src/error.rs b/rust/crates/accounts/src/error.rsindex 058357c375..0140b5d0c5 100644--- a/rust/crates/accounts/src/error.rs+++ b/rust/crates/accounts/src/error.rs@@ -1,7 +1,7 @@//! Shared error types for account flows.use base64::DecodeError;-use ente_core::{auth::AuthError, crypto::CryptoError, http::Error as HttpError};+use ente_core::{auth::AuthError, crypto::CryptoError, http_legacy::Error as HttpError};use thiserror::Error;/// Result alias for the shared account crate.diff --git a/rust/crates/accounts/src/types.rs b/rust/crates/accounts/src/types.rsindex 5034b5c45c..e559bcb0ef 100644--- a/rust/crates/accounts/src/types.rs+++ b/rust/crates/accounts/src/types.rs@@ -1,6 +1,6 @@//! Shared reusable types for account clients.-use ente_core::{http::HttpConfig, urls::PRODUCTION_API_BASE_URL};+use ente_core::{http_legacy::HttpConfig, urls::PRODUCTION_API_BASE_URL};use futures_timer::Delay;use serde::{Deserialize, Serialize};use std::{future::Future, pin::Pin, sync::Arc, time::Duration};diff --git a/rust/crates/contacts/src/client.rs b/rust/crates/contacts/src/client.rsindex 741fd832b4..69122054e5 100644--- a/rust/crates/contacts/src/client.rs+++ b/rust/crates/contacts/src/client.rs@@ -2,7 +2,7 @@ use std::sync::{Arc, RwLock};use ente_core::auth::{self, KeyAttributes, SrpSession};use ente_core::crypto::{self, SecretVec, sealed, secretbox};-use ente_core::http::{Error as HttpError, HttpClient, HttpConfig};+use ente_core::http_legacy::{Error as HttpError, HttpClient, HttpConfig};use sha2::{Digest, Sha256};use uuid::Uuid;@@ -63,7 +63,7 @@ pub struct OpenContactsCtxResult {pub struct ContactsCtx {user_id: i64,http: HttpClient,- object_store_http: ente_core::http::ObjectStoreHttpClient,+ object_store_http: ente_core::http_legacy::ObjectStoreHttpClient,master_key: Arc<RwLock<SecretVec>>,root_contact_key: Arc<RwLock<Option<SecretVec>>>,wrapped_root_contact_key: Arc<RwLock<Option<WrappedRootContactKey>>>,diff --git a/rust/crates/contacts/src/error.rs b/rust/crates/contacts/src/error.rsindex 89c38b6d60..003e2374e3 100644--- a/rust/crates/contacts/src/error.rs+++ b/rust/crates/contacts/src/error.rs@@ -1,4 +1,4 @@-use ente_core::{auth::AuthError, crypto::CryptoError, http::Error as HttpError};+use ente_core::{auth::AuthError, crypto::CryptoError, http_legacy::Error as HttpError};use thiserror::Error;#[derive(Debug, Error)]diff --git a/rust/crates/contacts/src/legacy_kit/mod.rs b/rust/crates/contacts/src/legacy_kit/mod.rsindex c75312c1ea..81151b8406 100644--- a/rust/crates/contacts/src/legacy_kit/mod.rs+++ b/rust/crates/contacts/src/legacy_kit/mod.rs@@ -6,7 +6,7 @@ use std::sync::Arc;use ente_core::{auth::{self, KeyAttributes, SrpSession},crypto::{self, SecretString, SecretVec, kdf, sealed, secretbox},- http::{HttpClient, HttpConfig},+ http_legacy::{HttpClient, HttpConfig},};use uuid::Uuid;diff --git a/rust/crates/core/Cargo.toml b/rust/crates/core/Cargo.tomlindex a4bce8fbbd..1b582ada22 100644--- a/rust/crates/core/Cargo.toml+++ b/rust/crates/core/Cargo.toml@@ -38,6 +38,11 @@ hex = "0.4"bip39 = { version = "2", default-features = false, features = ["std"] }zeroize = { version = "1.8.2", features = ["derive"] }+[target.'cfg(not(target_arch = "wasm32"))'.dependencies]+reqwest = { version = "0.12", default-features = false, features = ["stream"] }+bytes = "1.11.1"+futures-core = "0.3.32"+[dev-dependencies]tokio = { version = "1", features = ["rt-multi-thread", "macros"] }mockito = "1.6"diff --git a/rust/crates/core/examples/ping.rs b/rust/crates/core/examples/ping.rsindex 8e41359f5d..64c3d0b847 100644--- a/rust/crates/core/examples/ping.rs+++ b/rust/crates/core/examples/ping.rs@@ -4,16 +4,25 @@//! cargo run --example ping -- https://api.ente.com//! ```-use ente_core::http::HttpClient;+use ente_core::http::{Api, ApiConfig, Http};#[tokio::main]async fn main() {- let base_url = std::env::args().nth(1).expect("Usage: ping <base_url>");+ let origin = std::env::args().nth(1).expect("Usage: ping <origin>");- let client = HttpClient::new(&base_url).expect("failed to build HTTP client");+ let api = Api::new(+ Http::new().expect("failed to build HTTP client"),+ ApiConfig {+ origin,+ client_package: "io.ente.example".into(),+ client_version: None,+ user_agent: None,+ auth: None,+ },+ );- match client.ping().await {+ match api.ping().await {Ok(response) => println!("message: {}, id: {}", response.message, response.id),- Err(e) => eprintln!("Error: {}", e),+ Err(e) => eprintln!("Error: {e}"),}}diff --git a/rust/crates/core/src/http.rs b/rust/crates/core/src/http.rsindex c177774eea..994249363d 100644--- a/rust/crates/core/src/http.rs+++ b/rust/crates/core/src/http.rs@@ -1,910 +1,709 @@//! HTTP client for the Ente API.//!-//! [`HttpClient`] is an Ente API client bound to one base URL. It sends Ente's-//! client headers on every request, and the auth token once one is set.-//! [`ObjectStoreHttpClient`], from [`HttpClient::object_store`], is a bare-//! client for presigned object-store transfers, sending only the headers it is-//! given.--use std::error::Error as StdError;-use std::fmt::Write as _;-use std::future::Future;-use std::sync::RwLock;+//! These are thin wrappers over [`reqwest`] with Ente-specific ergonomics.+//! [`Http`] is a transparent wrapper that adds nothing of its own to a request;+//! beyond its convenience methods it exists so that a single connection pool can+//! be shared across clients (an `Http` is cheap to clone, and clones share the+//! pool). [`Api`] is tailored to one Ente API origin, with pluggable+//! authentication and built-in Ente headers.+//!+//! The interface mirrors reqwest, so if you know reqwest you will feel at home.++use std::sync::{PoisonError, RwLock};#[cfg(not(target_arch = "wasm32"))]use std::time::Duration;-use reqwest::header::{HeaderMap, HeaderName, HeaderValue, LOCATION};-#[cfg(not(target_arch = "wasm32"))]-use reqwest::redirect::Policy;-use reqwest::{Response, Url};+use reqwest::Method;+use reqwest::header::{HeaderName, HeaderValue, USER_AGENT};use serde::de::DeserializeOwned;use serde::{Deserialize, Serialize};use thiserror::Error;-use zeroize::Zeroizing;-const TOKEN_HEADER: &str = "X-Auth-Token";-const CLIENT_PKG_HEADER: &str = "X-Client-Package";-const CLIENT_VERSION_HEADER: &str = "X-Client-Version";+const CLIENT_PACKAGE: HeaderName = HeaderName::from_static("x-client-package");+const CLIENT_VERSION: HeaderName = HeaderName::from_static("x-client-version");+const AUTH_TOKEN: HeaderName = HeaderName::from_static("x-auth-token");+const ACCESS_TOKEN: HeaderName = HeaderName::from_static("x-auth-access-token");+const ACCESS_TOKEN_JWT: HeaderName = HeaderName::from_static("x-auth-access-token-jwt");+const LINK_DEVICE_TOKEN: HeaderName = HeaderName::from_static("x-auth-link-device-token");+const CAST_ACCESS_TOKEN: HeaderName = HeaderName::from_static("x-cast-access-token");-const MAX_REDIRECTS: usize = 5;--/// HTTP client errors.+/// An error from an HTTP request.#[derive(Error, Debug)]pub enum Error {- /// Network error - connection failed, timeout, etc.- #[error("Network error: {0}")]- Network(String),+ /// The request could not be sent, or the response could not be read.+ #[error(transparent)]+ Network(NetworkError),- /// Server returned an HTTP error status.- #[error("HTTP {status}: {message}")]+ /// The server responded with a non-2xx status.+ #[error("HTTP {status} at {path}")]Http {- /// Optional structured server error code.- code: Option<String>,- /// Error message or response body.- message: String,- /// HTTP status code.+ /// The HTTP status code.status: u16,+ /// The request path that failed, with its query stripped.+ path: String,},- /// Failed to parse JSON response.- #[error("JSON parse error: {0}")]- Parse(String),-- /// Invalid base URL or request path.- #[error("Invalid URL: {0}")]- InvalidUrl(String),+ /// The response arrived, but its body was not the expected JSON.+ #[error(transparent)]+ Parse(ParseError),}+/// The underlying failure of a [`Network`](Error::Network) error.+#[derive(Error, Debug)]+#[error(transparent)]+pub struct NetworkError(reqwest::Error);++/// The underlying failure of a [`Parse`](Error::Parse) error.+#[derive(Error, Debug)]+#[error(transparent)]+pub struct ParseError(serde_json::Error);+impl Error {- /// Return the HTTP status code if this is an HTTP error.- pub fn status_code(&self) -> Option<u16> {- match self {- Error::Http { status, .. } => Some(*status),- _ => None,+ /// A connection could not be established.+ pub fn is_connect(&self) -> bool {+ #[cfg(not(target_arch = "wasm32"))]+ {+ matches!(self, Error::Network(e) if e.0.is_connect())+ }+ #[cfg(target_arch = "wasm32")]+ {+ false}}- /// Return the structured server error code when available.- pub fn api_code(&self) -> Option<&str> {- match self {- Error::Http { code, .. } => code.as_deref(),- _ => None,- }+ /// The request timed out.+ pub fn is_timeout(&self) -> bool {+ matches!(self, Error::Network(e) if e.0.is_timeout())}- /// Return the server message when available.- pub fn api_message(&self) -> Option<&str> {+ /// The HTTP status code, if this is an [`Http`](Self::Http) error.+ pub fn status_code(&self) -> Option<u16> {match self {- Error::Http { message, .. } => Some(message.as_str()),+ Error::Http { status, .. } => Some(*status),_ => None,}}- fn with_request_context(self, context: &str) -> Self {- fn append(message: String, context: &str) -> String {- format!("{message} {context}")- }-+ /// Returns `true` if the request failed in transit, or if the server+ /// answered with a 429 or a 5xx status.+ pub fn is_retryable(&self) -> bool {match self {- Error::Network(message) => Error::Network(append(message, context)),- Error::Http {- status,- code,- message,- } => Error::Http {- status,- code,- message: append(message, context),- },- Error::Parse(message) => Error::Parse(append(message, context)),- Error::InvalidUrl(message) => Error::InvalidUrl(append(message, context)),+ Error::Network(e) => e.0.is_request() || e.0.is_body(),+ Error::Http { status, .. } => *status == 429 || *status >= 500,+ Error::Parse(_) => false,}}}impl From<reqwest::Error> for Error {- fn from(e: reqwest::Error) -> Self {- let message = format_reqwest_error(&e);- if let Some(status) = e.status() {- Error::Http {- status: status.as_u16(),- code: None,- message,- }- } else {- Error::Network(message)+ fn from(mut e: reqwest::Error) -> Self {+ if let Some(url) = e.url_mut() {+ url.set_query(None);}+ Error::Network(NetworkError(e))}}-impl From<serde_json::Error> for Error {- fn from(e: serde_json::Error) -> Self {- Error::Parse(e.to_string())- }-}--#[derive(Deserialize)]-struct ApiErrorBody {- code: Option<String>,- message: Option<String>,-}--fn parse_api_error_body(body: &str) -> (Option<String>, String) {- let Ok(parsed) = serde_json::from_str::<ApiErrorBody>(body) else {- return (None, body.to_string());- };- let message = parsed- .message- .or_else(|| parsed.code.clone())- .unwrap_or_else(|| body.to_string());- (parsed.code, message)+/// A bare HTTP client for requests to arbitrary URLs.+///+/// Cloning is cheap and shares one connection pool.+#[derive(Clone)]+pub struct Http {+ client: reqwest::Client,}-fn format_reqwest_error(error: &reqwest::Error) -> String {- let mut message = error.to_string();-- let mut kinds = Vec::new();- if error.is_timeout() {- kinds.push("timeout");- }- #[cfg(not(target_arch = "wasm32"))]- if error.is_connect() {- kinds.push("connect");- }- if error.is_request() {- kinds.push("request");- }- if error.is_body() {- kinds.push("body");+impl Http {+ /// Create a transport with a default connect timeout.+ pub fn new() -> Result<Self, Error> {+ let builder = reqwest::Client::builder();+ #[cfg(not(target_arch = "wasm32"))]+ let builder = builder.connect_timeout(Duration::from_secs(15));+ Ok(Http {+ client: builder.build()?,+ })}- if error.is_decode() {- kinds.push("decode");++ /// Start a GET request to `url`.+ pub fn get(&self, url: &str) -> RequestBuilder {+ self.request(Method::GET, url)}- if error.is_redirect() {- kinds.push("redirect");++ /// Start a POST request to `url`.+ pub fn post(&self, url: &str) -> RequestBuilder {+ self.request(Method::POST, url)}- if !kinds.is_empty() {- let _ = write!(message, " [kind: {}]", kinds.join(","));++ /// Start a PUT request to `url`.+ pub fn put(&self, url: &str) -> RequestBuilder {+ self.request(Method::PUT, url)}- let mut source_chain = Vec::new();- let mut source = StdError::source(error);- while let Some(cause) = source {- source_chain.push(cause.to_string());- source = cause.source();+ /// Start a DELETE request to `url`.+ pub fn delete(&self, url: &str) -> RequestBuilder {+ self.request(Method::DELETE, url)}- if !source_chain.is_empty() {- let _ = write!(message, " [caused by: {}]", source_chain.join(" -> "));++ /// Start a HEAD request to `url`.+ pub fn head(&self, url: &str) -> RequestBuilder {+ self.request(Method::HEAD, url)}- message+ fn request(&self, method: Method, url: &str) -> RequestBuilder {+ RequestBuilder(self.client.request(method, url))+ }}-fn request_context(method: &str, url: &str, query: &[(&str, String)]) -> String {- format!("[request: {method} {}]", request_target(url, query))+/// How an [`Api`] authenticates its requests.+///+/// An `Api` uses a single scheme for its lifetime. To act as more than one+/// identity at once, hold several `Api`s over the same [`Http`].+pub enum Auth {+ /// A logged-in user, sent as the `X-Auth-Token` header.+ User(String),+ /// A viewer of a public album, sent as `X-Auth-Access-Token` with an optional+ /// password JWT and link-device token.+ PublicAlbum {+ /// The album access token.+ access_token: String,+ /// The password-protected album's JWT, if the album has a password.+ jwt: Option<String>,+ /// The link-device token, if one has been issued.+ link_device: Option<String>,+ },+ /// A cast session, sent as the `X-Cast-Access-Token` header.+ Cast(String),}-fn request_target(url: &str, query: &[(&str, String)]) -> String {- let Ok(mut parsed) = Url::parse(url) else {- return url.to_string();- };-- if !query.is_empty() {- let mut pairs = parsed.query_pairs_mut();- for (key, value) in query {- pairs.append_pair(key, value);+impl Auth {+ fn apply(&self, builder: reqwest::RequestBuilder) -> reqwest::RequestBuilder {+ match self {+ Auth::User(token) => sensitive_header(builder, AUTH_TOKEN, token),+ Auth::PublicAlbum {+ access_token,+ jwt,+ link_device,+ } => {+ let mut builder = sensitive_header(builder, ACCESS_TOKEN, access_token);+ if let Some(jwt) = jwt {+ builder = sensitive_header(builder, ACCESS_TOKEN_JWT, jwt);+ }+ if let Some(link_device) = link_device {+ builder = sensitive_header(builder, LINK_DEVICE_TOKEN, link_device);+ }+ builder+ }+ Auth::Cast(token) => sensitive_header(builder, CAST_ACCESS_TOKEN, token),}}-- match parsed.query() {- Some(query) => format!("{}?{query}", parsed.path()),- None => parsed.path().to_string(),- }}-/// Response from the /ping endpoint.-#[derive(Deserialize, Debug)]-pub struct PingResponse {- /// "pong"- pub message: String,- /// Git commit hash of the server.- pub id: String,+fn sensitive_header(+ builder: reqwest::RequestBuilder,+ name: HeaderName,+ value: &str,+) -> reqwest::RequestBuilder {+ match HeaderValue::from_str(value) {+ Ok(mut value) => {+ value.set_sensitive(true);+ builder.header(name, value)+ }+ // reqwest hits the same parse failure, and reports it at send time.+ Err(_) => builder.header(name, value),+ }}-/// Authenticated HTTP client configuration.-#[derive(Clone, Default)]-pub struct HttpConfig {- /// Base API URL.- pub base_url: String,- /// Optional auth token sent via `X-Auth-Token`.- pub auth_token: Option<String>,- /// Optional user agent.- pub user_agent: Option<String>,- /// Optional client package header.- pub client_package: Option<String>,- /// Optional client version header.+/// Settings for building an [`Api`].+pub struct ApiConfig {+ /// The Ente API origin: scheme, host, and port, e.g. `https://api.ente.com`.+ pub origin: String,+ /// The client package, sent as `X-Client-Package` (e.g. `io.ente.photos`).+ pub client_package: String,+ /// The client version, sent as `X-Client-Version`.pub client_version: Option<String>,- /// Optional request timeout.- pub timeout_secs: Option<u64>,-}--impl std::fmt::Debug for HttpConfig {- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {- f.debug_struct("HttpConfig")- .field("base_url", &self.base_url)- .field(- "auth_token",- &self.auth_token.as_ref().map(|_| "<redacted>"),- )- .field("user_agent", &self.user_agent)- .field("client_package", &self.client_package)- .field("client_version", &self.client_version)- .field("timeout_secs", &self.timeout_secs)- .finish()- }+ /// The user agent to send.+ pub user_agent: Option<String>,+ /// The authentication to start with, or `None` to start unauthenticated.+ pub auth: Option<Auth>,}-/// HTTP client for the Ente API.-///-/// The client is bound to one base URL during creation. It sends Ente's-/// required HTTP headers on every request, and the auth token once one is set.+/// An Ente API client, bound to a single origin.///-/// Request `path`s are trusted endpoints, joined to the base URL verbatim, so-/// they must not be attacker-controlled.-pub struct HttpClient {- client: reqwest::Client,- no_redirect_client: reqwest::Client,- base_url: String,- auth_token: RwLock<Option<Zeroizing<String>>>,- #[cfg(not(target_arch = "wasm32"))]- user_agent: Option<String>,- client_package: Option<String>,+/// Requests take a path relative to that origin and automatically carry the Ente+/// client headers and the credentials of the [`Auth`] scheme.+pub struct Api {+ http: Http,+ origin: String,+ client_package: String,client_version: Option<String>,+ user_agent: Option<String>,+ auth: RwLock<Option<Auth>>,}-/// 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> {- Self::new_with_config(HttpConfig {- base_url: base_url.to_string(),- ..HttpConfig::default()- })- }-- /// Create a client with auth/header configuration.- ///- /// # Errors- ///- /// Returns [`Error::InvalidUrl`] if the base URL does not parse, or if it- /// carries a query or fragment.- pub fn new_with_config(config: HttpConfig) -> Result<Self, Error> {- let base_url = config.base_url.trim_end_matches('/').to_string();- let base = Url::parse(&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(),- ));- }-- #[cfg(not(target_arch = "wasm32"))]- let mut builder = reqwest::Client::builder();- #[cfg(target_arch = "wasm32")]- let builder = reqwest::Client::builder();- #[cfg(not(target_arch = "wasm32"))]- if let Some(timeout) = config.timeout_secs {- builder = builder.timeout(Duration::from_secs(timeout));- }- let client = builder.build().map_err(Error::from)?;-- #[cfg(not(target_arch = "wasm32"))]- let mut no_redirect_builder = reqwest::Client::builder().redirect(Policy::none());- #[cfg(target_arch = "wasm32")]- let no_redirect_builder = reqwest::Client::builder();- #[cfg(not(target_arch = "wasm32"))]- if let Some(timeout) = config.timeout_secs {- no_redirect_builder = no_redirect_builder.timeout(Duration::from_secs(timeout));- }- let no_redirect_client = no_redirect_builder.build().map_err(Error::from)?;-- Ok(Self {- client,- no_redirect_client,- base_url,- auth_token: RwLock::new(config.auth_token.map(Zeroizing::new)),- #[cfg(not(target_arch = "wasm32"))]- user_agent: config.user_agent,+impl Api {+ /// Build a client over `http`, sharing its connection pool.+ pub fn new(http: Http, config: ApiConfig) -> Self {+ Self {+ http,+ origin: config.origin.trim_end_matches('/').to_owned(),client_package: config.client_package,client_version: config.client_version,- })+ user_agent: config.user_agent,+ auth: RwLock::new(config.auth),+ }}- /// Replace the auth token used for authenticated requests.- pub fn set_auth_token(&self, auth_token: Option<String>) {- *self- .auth_token- .write()- .unwrap_or_else(std::sync::PoisonError::into_inner) = auth_token.map(Zeroizing::new);+ /// The bare transport underneath, for requests to other hosts.+ pub fn http(&self) -> &Http {+ &self.http}- /// Create a bare client for presigned object-store requests.- pub fn object_store(&self) -> ObjectStoreHttpClient {- ObjectStoreHttpClient {- client: self.no_redirect_client.clone(),- }+ /// Change the authentication used for subsequent requests, e.g. after login.+ pub fn set_auth(&self, auth: Option<Auth>) {+ *self.auth.write().unwrap_or_else(PoisonError::into_inner) = auth;}- /// GET request, returning the response body as text.- pub async fn get(&self, path: &str) -> Result<String, Error> {- let url = self.request_url(path)?;- let context = request_context("GET", &url, &[]);- let request = self.client.get(&url).headers(self.build_headers()?);- send_and_parse(request, &context, parse_text_response).await+ /// Start a GET request to `path`, relative to the origin.+ pub fn get(&self, path: &str) -> RequestBuilder {+ self.request(Method::GET, path)}- /// GET request returning JSON.- pub async fn get_json<T: DeserializeOwned>(- &self,- path: &str,- query: &[(&str, String)],- ) -> Result<T, Error> {- let url = self.request_url(path)?;- let context = request_context("GET", &url, query);- let request = self- .client- .get(&url)- .headers(self.build_headers()?)- .query(query);- send_and_parse(request, &context, parse_json_response).await- }-- /// GET request returning `None` for 404.- pub async fn get_json_optional<T: DeserializeOwned>(- &self,- path: &str,- query: &[(&str, String)],- ) -> Result<Option<T>, Error> {- let url = self.request_url(path)?;- let context = request_context("GET", &url, query);- let request = self- .client- .get(&url)- .headers(self.build_headers()?)- .query(query);- send_and_parse(request, &context, |response| async move {- if response.status().as_u16() == 404 {- Ok(None)- } else {- parse_json_response(response).await.map(Some)- }- })- .await- }-- /// POST JSON request.- pub async fn post_json<T: DeserializeOwned, B: Serialize + Sync + ?Sized>(- &self,- path: &str,- body: &B,- ) -> Result<T, Error> {- let url = self.request_url(path)?;- let context = request_context("POST", &url, &[]);- let request = self- .client- .post(&url)- .headers(self.build_headers()?)- .json(body);- send_and_parse(request, &context, parse_json_response).await- }-- /// POST JSON request expecting an empty response body.- pub async fn post_empty<B: Serialize + Sync + ?Sized>(- &self,- path: &str,- body: &B,- ) -> Result<(), Error> {- let url = self.request_url(path)?;- let context = request_context("POST", &url, &[]);- let request = self- .client- .post(&url)- .headers(self.build_headers()?)- .json(body);- send_and_parse(request, &context, parse_empty_response).await- }-- /// PUT JSON request.- pub async fn put_json<T: DeserializeOwned, B: Serialize + Sync + ?Sized>(- &self,- path: &str,- body: &B,- ) -> Result<T, Error> {- let url = self.request_url(path)?;- let context = request_context("PUT", &url, &[]);- let request = self- .client- .put(&url)- .headers(self.build_headers()?)- .json(body);- send_and_parse(request, &context, parse_json_response).await- }-- /// PUT JSON request expecting an empty response body.- pub async fn put_empty<B: Serialize + Sync + ?Sized>(- &self,- path: &str,- body: &B,- ) -> Result<(), Error> {- let url = self.request_url(path)?;- let context = request_context("PUT", &url, &[]);- let request = self- .client- .put(&url)- .headers(self.build_headers()?)- .json(body);- send_and_parse(request, &context, parse_empty_response).await+ /// Start a POST request to `path`, relative to the origin.+ pub fn post(&self, path: &str) -> RequestBuilder {+ self.request(Method::POST, path)}- /// DELETE request expecting an empty response body.- pub async fn delete_empty(&self, path: &str, query: &[(&str, String)]) -> Result<(), Error> {- let url = self.request_url(path)?;- let context = request_context("DELETE", &url, query);- let request = self- .client- .delete(&url)- .headers(self.build_headers()?)- .query(query);- send_and_parse(request, &context, parse_empty_response).await- }-- /// DELETE request returning JSON.- pub async fn delete_json<T: DeserializeOwned>(- &self,- path: &str,- query: &[(&str, String)],- ) -> Result<T, Error> {- let url = self.request_url(path)?;- let context = request_context("DELETE", &url, query);- let request = self- .client- .delete(&url)- .headers(self.build_headers()?)- .query(query);- send_and_parse(request, &context, parse_json_response).await+ /// Start a PUT request to `path`, relative to the origin.+ pub fn put(&self, path: &str) -> RequestBuilder {+ self.request(Method::PUT, path)}- /// Ping the API, returns [PingResponse].- pub async fn ping(&self) -> Result<PingResponse, Error> {- self.get_json("/ping", &[]).await+ /// Start a DELETE request to `path`, relative to the origin.+ pub fn delete(&self, path: &str) -> RequestBuilder {+ self.request(Method::DELETE, path)}- fn request_url(&self, path: &str) -> Result<String, Error> {- if !path.starts_with('/') {- return Err(Error::InvalidUrl(- "request paths must start with '/'".to_string(),- ));- }- debug_assert!(- !path_contains_dot_segments(path),- "request paths must be trusted endpoint paths without dot segments"- );-- Ok(format!("{}{}", self.base_url, path))+ /// Start a HEAD request to `path`, relative to the origin.+ pub fn head(&self, path: &str) -> RequestBuilder {+ self.request(Method::HEAD, path)}- fn build_headers(&self) -> Result<HeaderMap, Error> {- let mut headers = self.build_public_headers()?;- if let Some(auth_token) = self- .auth_token- .read()- .unwrap_or_else(std::sync::PoisonError::into_inner)- .as_ref()- {- let token =- HeaderValue::from_str(auth_token).map_err(|e| Error::Parse(e.to_string()))?;- headers.insert(TOKEN_HEADER, token);- }- Ok(headers)+ /// Check that the server is reachable.+ pub async fn ping(&self) -> Result<PingResponse, Error> {+ self.get("/ping")+ .send()+ .await?+ .error_for_status()?+ .json()+ .await}- fn build_public_headers(&self) -> Result<HeaderMap, Error> {- let mut headers = HeaderMap::new();- #[cfg(not(target_arch = "wasm32"))]- if let Some(user_agent) = &self.user_agent {- let value =- HeaderValue::from_str(user_agent).map_err(|e| Error::Parse(e.to_string()))?;- headers.insert(reqwest::header::USER_AGENT, value);+ fn request(&self, method: Method, path: &str) -> RequestBuilder {+ debug_assert!(path.starts_with('/'));+ let mut builder = self+ .http+ .client+ .request(method, format!("{}{}", self.origin, path))+ .header(CLIENT_PACKAGE, &self.client_package);+ if let Some(version) = &self.client_version {+ builder = builder.header(CLIENT_VERSION, version);}- if let Some(client_package) = &self.client_package {- let value =- HeaderValue::from_str(client_package).map_err(|e| Error::Parse(e.to_string()))?;- headers.insert(CLIENT_PKG_HEADER, value);+ if let Some(user_agent) = &self.user_agent {+ builder = builder.header(USER_AGENT, user_agent);}- if let Some(client_version) = &self.client_version {- let value =- HeaderValue::from_str(client_version).map_err(|e| Error::Parse(e.to_string()))?;- headers.insert(CLIENT_VERSION_HEADER, value);+ if let Some(auth) = &*self.auth.read().unwrap_or_else(PoisonError::into_inner) {+ builder = auth.apply(builder);}- Ok(headers)+ RequestBuilder(builder)}}-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).await+/// A request under construction.+///+/// Configure it by chaining methods, then [`send`](Self::send) it.+#[must_use = "a request is only sent when you call send()"]+pub struct RequestBuilder(reqwest::RequestBuilder);++impl RequestBuilder {+ /// Add URL query parameters, serialized from any [`Serialize`] value with+ /// `serde_urlencoded`.+ pub fn query<Q: Serialize + ?Sized>(self, query: &Q) -> Self {+ Self(self.0.query(query))}- /// 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+ /// Add a header.+ pub fn header(self, name: &str, value: &str) -> Self {+ Self(self.0.header(name, value))}-}-async fn send_and_parse<T, F, Fut>(- request: reqwest::RequestBuilder,- context: &str,- parse: F,-) -> Result<T, Error>-where- F: FnOnce(Response) -> Fut,- Fut: Future<Output = Result<T, Error>>,-{- let outcome = async {- let response = request.send().await?;- parse(response).await- }- .await;- outcome.map_err(|error| error.with_request_context(context))-}+ /// Set the body to `body` serialized as JSON, with a JSON `Content-Type`.+ pub fn json<B: Serialize + ?Sized>(self, body: &B) -> Self {+ Self(self.0.json(body))+ }-async fn get_bytes_with_client(client: &reqwest::Client, url: &str) -> Result<Vec<u8>, Error> {- let mut current_url = parse_url(url)?;- for _ in 0..MAX_REDIRECTS {- let response = client.get(current_url.clone()).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;+ /// Set the body to raw bytes.+ pub fn body(self, body: Vec<u8>) -> Self {+ Self(self.0.body(body))}- Err(Error::InvalidUrl("too many redirects".to_string()))+ /// Send the request, returning the [`Response`] for any status.+ pub async fn send(self) -> Result<Response, Error> {+ Ok(Response(self.0.send().await?))+ }}-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..MAX_REDIRECTS {- 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;+/// The response to a sent request.+///+/// The usual flow is to call [`error_for_status`](Self::error_for_status) to+/// turn a non-2xx status into an error, then read the body with+/// [`json`](Self::json), [`text`](Self::text), [`bytes`](Self::bytes), or+/// [`bytes_stream`](Self::bytes_stream).+///+/// The [`status`](Self::status) and [`header`](Self::header)s are also available+/// directly.+#[derive(Debug)]+pub struct Response(reqwest::Response);++impl Response {+ /// The HTTP status code.+ pub fn status(&self) -> u16 {+ self.0.status().as_u16()+ }++ /// The value of a response header, if present and valid UTF-8.+ pub fn header(&self, name: &str) -> Option<&str> {+ self.0.headers().get(name).and_then(|v| v.to_str().ok())+ }++ /// Return an [`Error::Http`] if the status is not 2xx, otherwise the response.+ pub fn error_for_status(self) -> Result<Self, Error> {+ if self.0.status().is_success() {+ Ok(self)+ } else {+ Err(Error::Http {+ status: self.0.status().as_u16(),+ path: self.0.url().path().to_owned(),+ })}- return parse_empty_response(response).await;}- Err(Error::InvalidUrl("too many redirects".to_string()))-}+ /// Read the whole body and deserialize it as JSON.+ pub async fn json<T: DeserializeOwned>(self) -> Result<T, Error> {+ serde_json::from_slice(&self.0.bytes().await?).map_err(|e| Error::Parse(ParseError(e)))+ }-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);+ /// Read the whole body as text.+ pub async fn text(self) -> Result<String, Error> {+ Ok(self.0.text().await?)}- Ok(header_map)-}-fn parse_url(url: &str) -> Result<Url, Error> {- Url::parse(url).map_err(|e| Error::InvalidUrl(format!("invalid url: {e}")))+ /// Read the whole body as bytes.+ pub async fn bytes(self) -> Result<Vec<u8>, Error> {+ Ok(self.0.bytes().await?.into())+ }}-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}")))-}+#[cfg(not(target_arch = "wasm32"))]+mod body_stream {+ use std::pin::Pin;+ use std::task::{Context, Poll};-/// Pass through successful responses; turn error statuses into [`Error::Http`].-async fn check_success(response: Response) -> Result<Response, Error> {- if response.status().is_success() {- return Ok(response);- }- let status = response.status().as_u16();- let body = response- .text()- .await- .unwrap_or_else(|_| "failed to read error body".to_string());- let (code, message) = parse_api_error_body(&body);- Err(Error::Http {- status,- code,- message,- })-}+ use bytes::Bytes;+ use futures_core::Stream;-async fn parse_text_response(response: Response) -> Result<String, Error> {- check_success(response)- .await?- .text()- .await- .map_err(Into::into)-}+ use super::{Error, Response};-async fn parse_json_response<T: DeserializeOwned>(response: Response) -> Result<T, Error> {- let text = parse_text_response(response).await?;- serde_json::from_str(&text).map_err(Into::into)-}+ impl Response {+ /// Stream the body in chunks instead of buffering it, for large downloads.+ pub fn bytes_stream(self) -> impl Stream<Item = Result<Bytes, Error>> + Send {+ BytesStream(Box::pin(self.0.bytes_stream()))+ }+ }-async fn parse_empty_response(response: Response) -> Result<(), Error> {- check_success(response).await.map(drop)-}+ struct BytesStream(Pin<Box<dyn Stream<Item = reqwest::Result<Bytes>> + Send>>);-async fn parse_bytes_response(response: Response) -> Result<Vec<u8>, Error> {- check_success(response)- .await?- .bytes()- .await- .map(|bytes| bytes.to_vec())- .map_err(Into::into)+ impl Stream for BytesStream {+ type Item = Result<Bytes, Error>;++ fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {+ self.0+ .as_mut()+ .poll_next(cx)+ .map(|chunk| chunk.map(|chunk| chunk.map_err(Error::from)))+ }+ }}-fn path_contains_dot_segments(path: &str) -> bool {- path.split(['?', '#'])- .next()- .unwrap_or(path)- .split('/')- .any(|segment| {- matches!(segment, "." | "..")- || segment.eq_ignore_ascii_case("%2e")- || segment.eq_ignore_ascii_case("%2e%2e")- })+/// The reply from the `/ping` endpoint.+#[derive(Deserialize, Debug)]+pub struct PingResponse {+ /// Always `"pong"`.+ pub message: String,+ /// The server's git commit hash.+ pub id: String,}#[cfg(test)]mod tests {+ use futures_core::Stream;+ use mockito::{Matcher, Server, ServerGuard};+use super::*;- use mockito::{Matcher, Server};- fn test_client(base_url: &str) -> HttpClient {- HttpClient::new_with_config(HttpConfig {- base_url: base_url.to_string(),- ..HttpConfig::default()- })- .expect("test client creation should succeed")+ fn api(server: &ServerGuard, auth: Option<Auth>) -> Api {+ Api::new(+ Http::new().unwrap(),+ ApiConfig {+ origin: server.url(),+ client_package: "io.ente.test".into(),+ client_version: Some("1.0".into()),+ user_agent: None,+ auth,+ },+ )}- #[test]- fn test_client_creation() {- let client = test_client("https://api.ente.com/");- assert_eq!(client.base_url, "https://api.ente.com");- }+ #[tokio::test]+ async fn api_sends_client_and_auth_headers() {+ let mut server = Server::new_async().await;+ let mock = server+ .mock("GET", "/ping")+ .match_header("x-client-package", "io.ente.test")+ .match_header("x-client-version", "1.0")+ .match_header("x-auth-token", "tok")+ .with_body(r#"{"message":"pong","id":"abc"}"#)+ .create_async()+ .await;- #[test]- fn test_parse_error_conversion() {- let bad_json = "not json";- let err: Result<PingResponse, Error> = serde_json::from_str(bad_json).map_err(|e| e.into());- assert!(matches!(err, Err(Error::Parse(_))))- }+ let api = api(&server, Some(Auth::User("tok".into())));+ let response = api.ping().await.unwrap();- #[test]- fn test_parse_api_error_body_prefers_message_and_preserves_code() {- let (code, message) =- parse_api_error_body(r#"{"code":"TOO_MANY_WRONG_ATTEMPTS","message":"wait"}"#);- assert_eq!(code.as_deref(), Some("TOO_MANY_WRONG_ATTEMPTS"));- assert_eq!(message, "wait");+ mock.assert_async().await;+ assert_eq!(response.message, "pong");+ assert_eq!(response.id, "abc");}- #[test]- fn test_parse_api_error_body_falls_back_to_code_when_message_missing() {- let (code, message) = parse_api_error_body(r#"{"code":"SESSION_EXPIRED"}"#);- assert_eq!(code.as_deref(), Some("SESSION_EXPIRED"));- assert_eq!(message, "SESSION_EXPIRED");- }+ #[tokio::test]+ async fn api_sends_public_album_auth_headers() {+ let mut server = Server::new_async().await;+ let mock = server+ .mock("GET", "/public-collection/info")+ .match_header("x-auth-access-token", "at")+ .match_header("x-auth-access-token-jwt", "jwt")+ .match_header("x-auth-link-device-token", "ld")+ .match_header("x-auth-token", Matcher::Missing)+ .create_async()+ .await;- #[test]- fn test_request_url_uses_string_join() {- let client = test_client("https://api.ente.com/v1");- let url = client.request_url("/ping").unwrap();- assert_eq!(url, "https://api.ente.com/v1/ping");- }+ let api = api(+ &server,+ Some(Auth::PublicAlbum {+ access_token: "at".into(),+ jwt: Some("jwt".into()),+ link_device: Some("ld".into()),+ }),+ );+ let response = api.get("/public-collection/info").send().await.unwrap();- #[test]- fn test_request_url_preserves_query_and_special_bytes() {- let client = test_client("https://api.ente.com/v1");- let url = client.request_url("/%2e%2e%5cadmin?fresh=true").unwrap();- assert_eq!(url, "https://api.ente.com/v1/%2e%2e%5cadmin?fresh=true");+ mock.assert_async().await;+ assert_eq!(response.status(), 200);}- #[test]- fn test_path_contains_dot_segments() {- assert!(!path_contains_dot_segments("/ping?fresh=true"));- assert!(path_contains_dot_segments("/../admin"));- assert!(path_contains_dot_segments("/safe/%2e%2e/admin"));- assert!(path_contains_dot_segments("/safe/%2E/admin"));- }+ #[tokio::test]+ async fn set_auth_changes_subsequent_requests() {+ let mut server = Server::new_async().await;+ let unauthed = server+ .mock("GET", "/a")+ .match_header("x-auth-token", Matcher::Missing)+ .create_async()+ .await;+ let authed = server+ .mock("GET", "/b")+ .match_header("x-auth-token", "tok")+ .create_async()+ .await;- #[test]- fn test_request_url_rejects_missing_leading_slash() {- let client = test_client("https://api.ente.com");- let err = client.request_url("ping").unwrap_err();- assert!(matches!(err, Error::InvalidUrl(_)));- }+ let api = api(&server, None);+ api.get("/a").send().await.unwrap();+ api.set_auth(Some(Auth::User("tok".into())));+ api.get("/b").send().await.unwrap();- #[test]- fn test_new_rejects_invalid_base_url() {- assert!(matches!(- HttpClient::new("not a url"),- Err(Error::InvalidUrl(_))- ));+ unauthed.assert_async().await;+ authed.assert_async().await;}- #[test]- fn test_new_rejects_base_url_with_query() {- assert!(matches!(- HttpClient::new("https://api.ente.com/v1?stale=true"),- Err(Error::InvalidUrl(_))- ));- }+ #[tokio::test]+ async fn http_sends_only_explicit_headers() {+ let mut server = Server::new_async().await;+ let mock = server+ .mock("PUT", "/upload")+ .match_header("x-client-package", Matcher::Missing)+ .match_header("x-client-version", Matcher::Missing)+ .match_header("x-auth-token", Matcher::Missing)+ .match_header("content-type", Matcher::Missing)+ .match_header("content-md5", "digest")+ .match_body("payload")+ .create_async()+ .await;- #[test]- fn test_new_rejects_base_url_with_fragment() {- assert!(matches!(- HttpClient::new("https://api.ente.com/v1#old"),- Err(Error::InvalidUrl(_))- ));+ let http = Http::new().unwrap();+ http.put(&format!("{}/upload", server.url()))+ .header("Content-MD5", "digest")+ .body(b"payload".to_vec())+ .send()+ .await+ .unwrap()+ .error_for_status()+ .unwrap();++ mock.assert_async().await;}- #[test]- fn test_set_auth_token_replaces_token() {- let client = test_client("https://api.ente.com");- client.set_auth_token(Some("token-1".to_string()));- assert_eq!(- client- .auth_token- .read()- .unwrap()- .as_ref()- .map(|token| token.as_str()),- Some("token-1")- );- client.set_auth_token(None);- assert_eq!(- client- .auth_token- .read()- .unwrap()- .as_ref()- .map(|token| token.as_str()),- None- );+ #[tokio::test]+ async fn json_body_sets_content_type() {+ let mut server = Server::new_async().await;+ let mock = server+ .mock("POST", "/echo")+ .match_header("content-type", "application/json")+ .match_body(Matcher::JsonString(r#"{"a":1}"#.into()))+ .create_async()+ .await;++ let api = api(&server, None);+ api.post("/echo")+ .json(&serde_json::json!({"a": 1}))+ .send()+ .await+ .unwrap();++ mock.assert_async().await;}#[tokio::test]- async fn object_store_client_only_sends_explicit_headers() {+ async fn error_for_status_strips_the_query() {let mut server = Server::new_async().await;- let get_mock = server+ 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")+ .match_query(Matcher::Any)+ .with_status(403).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)++ let api = api(&server, None);+ let err = api+ .get("/download")+ .query(&[("X-Amz-Signature", "secret")])+ .send()+ .await+ .unwrap()+ .error_for_status()+ .unwrap_err();++ let Error::Http { status, path } = &err else {+ panic!("expected Error::Http, got {err:?}");+ };+ assert_eq!(*status, 403);+ assert_eq!(path, "/download");+ assert!(!err.to_string().contains("secret"));+ }++ #[tokio::test]+ async fn invalid_json_is_a_parse_error() {+ let mut server = Server::new_async().await;+ server+ .mock("GET", "/ping")+ .with_body("not json").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 api = api(&server, None);+ let err = api.ping().await.unwrap_err();+ assert!(matches!(err, Error::Parse(_)));+ }- 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())],- )+ #[tokio::test]+ async fn query_parameters_are_encoded() {+ let mut server = Server::new_async().await;+ let mock = server+ .mock("GET", "/search")+ .match_query(Matcher::UrlEncoded("q".into(), "a b&c".into()))+ .create_async()+ .await;++ let api = api(&server, None);+ api.get("/search")+ .query(&[("q", "a b&c")])+ .send().await.unwrap();- get_mock.assert_async().await;- put_mock.assert_async().await;- assert_eq!(bytes, b"ok");+ mock.assert_async().await;}#[tokio::test]- async fn api_json_calls_still_follow_redirects() {+ async fn status_and_header_read_directly() {let mut server = Server::new_async().await;-- let redirect_mock = server- .mock("GET", "/ping")- .match_header("x-auth-token", "auth-token")- .with_status(302)- .with_header("location", "/pong")+ server+ .mock("GET", "/maybe")+ .with_status(404)+ .with_header("x-request-id", "rid").create_async().await;- let target_mock = server- .mock("GET", "/pong")- .match_header("x-auth-token", "auth-token")- .with_status(200)- .with_body(- serde_json::json!({- "message": "pong",- "id": "redirected"- })- .to_string(),- )+ let api = api(&server, None);+ let response = api.get("/maybe").send().await.unwrap();+ assert_eq!(response.status(), 404);+ assert_eq!(response.header("x-request-id"), Some("rid"));+ assert_eq!(response.header("x-absent"), None);+ }++ #[tokio::test]+ async fn bytes_stream_yields_the_body() {+ let body: Vec<u8> = (0..100_000).map(|i| (i % 251) as u8).collect();+ let mut server = Server::new_async().await;+ server+ .mock("GET", "/file")+ .with_body(&body).create_async().await;- let client = HttpClient::new_with_config(HttpConfig {- base_url: server.url(),- auth_token: Some("auth-token".to_string()),- user_agent: None,- client_package: None,- client_version: None,- timeout_secs: None,- })- .unwrap();+ let http = Http::new().unwrap();+ let response = http+ .get(&format!("{}/file", server.url()))+ .send()+ .await+ .unwrap()+ .error_for_status()+ .unwrap();- let response: PingResponse = client.get_json("/ping", &[]).await.unwrap();+ let mut stream = std::pin::pin!(response.bytes_stream());+ let mut out = Vec::new();+ while let Some(chunk) = std::future::poll_fn(|cx| stream.as_mut().poll_next(cx)).await {+ out.extend_from_slice(&chunk.unwrap());+ }+ assert_eq!(out, body);+ }- redirect_mock.assert_async().await;- target_mock.assert_async().await;- assert_eq!(response.message, "pong");- assert_eq!(response.id, "redirected");+ #[tokio::test]+ async fn origin_trailing_slash_is_trimmed() {+ let mut server = Server::new_async().await;+ let mock = server+ .mock("GET", "/ping")+ .with_body(r#"{"message":"pong","id":"abc"}"#)+ .create_async()+ .await;++ let api = Api::new(+ Http::new().unwrap(),+ ApiConfig {+ origin: format!("{}/", server.url()),+ client_package: "io.ente.test".into(),+ client_version: None,+ user_agent: None,+ auth: None,+ },+ );+ api.ping().await.unwrap();++ mock.assert_async().await;}}diff --git a/rust/crates/core/src/http_legacy.rs b/rust/crates/core/src/http_legacy.rsnew file mode 100644index 0000000000..11200e8374--- /dev/null+++ b/rust/crates/core/src/http_legacy.rs@@ -0,0 +1,910 @@+//! Legacy HTTP client, superseded by [`crate::http`].+//!+//! [`HttpClient`] is an Ente API client bound to one base URL. It sends Ente's+//! client headers on every request, and the auth token once one is set.+//! [`ObjectStoreHttpClient`], from [`HttpClient::object_store`], is a bare+//! client for presigned object-store transfers, sending only the headers it is+//! given.++use std::error::Error as StdError;+use std::fmt::Write as _;+use std::future::Future;+use std::sync::RwLock;+#[cfg(not(target_arch = "wasm32"))]+use std::time::Duration;++use reqwest::header::{HeaderMap, HeaderName, HeaderValue, LOCATION};+#[cfg(not(target_arch = "wasm32"))]+use reqwest::redirect::Policy;+use reqwest::{Response, Url};+use serde::de::DeserializeOwned;+use serde::{Deserialize, Serialize};+use thiserror::Error;+use zeroize::Zeroizing;++const TOKEN_HEADER: &str = "X-Auth-Token";+const CLIENT_PKG_HEADER: &str = "X-Client-Package";+const CLIENT_VERSION_HEADER: &str = "X-Client-Version";++const MAX_REDIRECTS: usize = 5;++/// HTTP client errors.+#[derive(Error, Debug)]+pub enum Error {+ /// Network error - connection failed, timeout, etc.+ #[error("Network error: {0}")]+ Network(String),++ /// Server returned an HTTP error status.+ #[error("HTTP {status}: {message}")]+ Http {+ /// Optional structured server error code.+ code: Option<String>,+ /// Error message or response body.+ message: String,+ /// HTTP status code.+ status: u16,+ },++ /// Failed to parse JSON response.+ #[error("JSON parse error: {0}")]+ Parse(String),++ /// Invalid base URL or request path.+ #[error("Invalid URL: {0}")]+ InvalidUrl(String),+}++impl Error {+ /// Return the HTTP status code if this is an HTTP error.+ pub fn status_code(&self) -> Option<u16> {+ match self {+ Error::Http { status, .. } => Some(*status),+ _ => None,+ }+ }++ /// Return the structured server error code when available.+ pub fn api_code(&self) -> Option<&str> {+ match self {+ Error::Http { code, .. } => code.as_deref(),+ _ => None,+ }+ }++ /// Return the server message when available.+ pub fn api_message(&self) -> Option<&str> {+ match self {+ Error::Http { message, .. } => Some(message.as_str()),+ _ => None,+ }+ }++ fn with_request_context(self, context: &str) -> Self {+ fn append(message: String, context: &str) -> String {+ format!("{message} {context}")+ }++ match self {+ Error::Network(message) => Error::Network(append(message, context)),+ Error::Http {+ status,+ code,+ message,+ } => Error::Http {+ status,+ code,+ message: append(message, context),+ },+ Error::Parse(message) => Error::Parse(append(message, context)),+ Error::InvalidUrl(message) => Error::InvalidUrl(append(message, context)),+ }+ }+}++impl From<reqwest::Error> for Error {+ fn from(e: reqwest::Error) -> Self {+ let message = format_reqwest_error(&e);+ if let Some(status) = e.status() {+ Error::Http {+ status: status.as_u16(),+ code: None,+ message,+ }+ } else {+ Error::Network(message)+ }+ }+}++impl From<serde_json::Error> for Error {+ fn from(e: serde_json::Error) -> Self {+ Error::Parse(e.to_string())+ }+}++#[derive(Deserialize)]+struct ApiErrorBody {+ code: Option<String>,+ message: Option<String>,+}++fn parse_api_error_body(body: &str) -> (Option<String>, String) {+ let Ok(parsed) = serde_json::from_str::<ApiErrorBody>(body) else {+ return (None, body.to_string());+ };+ let message = parsed+ .message+ .or_else(|| parsed.code.clone())+ .unwrap_or_else(|| body.to_string());+ (parsed.code, message)+}++fn format_reqwest_error(error: &reqwest::Error) -> String {+ let mut message = error.to_string();++ let mut kinds = Vec::new();+ if error.is_timeout() {+ kinds.push("timeout");+ }+ #[cfg(not(target_arch = "wasm32"))]+ if error.is_connect() {+ kinds.push("connect");+ }+ if error.is_request() {+ kinds.push("request");+ }+ if error.is_body() {+ kinds.push("body");+ }+ if error.is_decode() {+ kinds.push("decode");+ }+ if error.is_redirect() {+ kinds.push("redirect");+ }+ if !kinds.is_empty() {+ let _ = write!(message, " [kind: {}]", kinds.join(","));+ }++ let mut source_chain = Vec::new();+ let mut source = StdError::source(error);+ while let Some(cause) = source {+ source_chain.push(cause.to_string());+ source = cause.source();+ }+ if !source_chain.is_empty() {+ let _ = write!(message, " [caused by: {}]", source_chain.join(" -> "));+ }++ message+}++fn request_context(method: &str, url: &str, query: &[(&str, String)]) -> String {+ format!("[request: {method} {}]", request_target(url, query))+}++fn request_target(url: &str, query: &[(&str, String)]) -> String {+ let Ok(mut parsed) = Url::parse(url) else {+ return url.to_string();+ };++ if !query.is_empty() {+ let mut pairs = parsed.query_pairs_mut();+ for (key, value) in query {+ pairs.append_pair(key, value);+ }+ }++ match parsed.query() {+ Some(query) => format!("{}?{query}", parsed.path()),+ None => parsed.path().to_string(),+ }+}++/// Response from the /ping endpoint.+#[derive(Deserialize, Debug)]+pub struct PingResponse {+ /// "pong"+ pub message: String,+ /// Git commit hash of the server.+ pub id: String,+}++/// Authenticated HTTP client configuration.+#[derive(Clone, Default)]+pub struct HttpConfig {+ /// Base API URL.+ pub base_url: String,+ /// Optional auth token sent via `X-Auth-Token`.+ pub auth_token: Option<String>,+ /// Optional user agent.+ pub user_agent: Option<String>,+ /// Optional client package header.+ pub client_package: Option<String>,+ /// Optional client version header.+ pub client_version: Option<String>,+ /// Optional request timeout.+ pub timeout_secs: Option<u64>,+}++impl std::fmt::Debug for HttpConfig {+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ f.debug_struct("HttpConfig")+ .field("base_url", &self.base_url)+ .field(+ "auth_token",+ &self.auth_token.as_ref().map(|_| "<redacted>"),+ )+ .field("user_agent", &self.user_agent)+ .field("client_package", &self.client_package)+ .field("client_version", &self.client_version)+ .field("timeout_secs", &self.timeout_secs)+ .finish()+ }+}++/// HTTP client for the Ente API.+///+/// The client is bound to one base URL during creation. It sends Ente's+/// required HTTP headers on every request, and the auth token once one is set.+///+/// Request `path`s are trusted endpoints, joined to the base URL verbatim, so+/// they must not be attacker-controlled.+pub struct HttpClient {+ client: reqwest::Client,+ no_redirect_client: reqwest::Client,+ base_url: String,+ auth_token: RwLock<Option<Zeroizing<String>>>,+ #[cfg(not(target_arch = "wasm32"))]+ user_agent: Option<String>,+ client_package: Option<String>,+ 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> {+ Self::new_with_config(HttpConfig {+ base_url: base_url.to_string(),+ ..HttpConfig::default()+ })+ }++ /// Create a client with auth/header configuration.+ ///+ /// # Errors+ ///+ /// Returns [`Error::InvalidUrl`] if the base URL does not parse, or if it+ /// carries a query or fragment.+ pub fn new_with_config(config: HttpConfig) -> Result<Self, Error> {+ let base_url = config.base_url.trim_end_matches('/').to_string();+ let base = Url::parse(&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(),+ ));+ }++ #[cfg(not(target_arch = "wasm32"))]+ let mut builder = reqwest::Client::builder();+ #[cfg(target_arch = "wasm32")]+ let builder = reqwest::Client::builder();+ #[cfg(not(target_arch = "wasm32"))]+ if let Some(timeout) = config.timeout_secs {+ builder = builder.timeout(Duration::from_secs(timeout));+ }+ let client = builder.build().map_err(Error::from)?;++ #[cfg(not(target_arch = "wasm32"))]+ let mut no_redirect_builder = reqwest::Client::builder().redirect(Policy::none());+ #[cfg(target_arch = "wasm32")]+ let no_redirect_builder = reqwest::Client::builder();+ #[cfg(not(target_arch = "wasm32"))]+ if let Some(timeout) = config.timeout_secs {+ no_redirect_builder = no_redirect_builder.timeout(Duration::from_secs(timeout));+ }+ let no_redirect_client = no_redirect_builder.build().map_err(Error::from)?;++ Ok(Self {+ client,+ no_redirect_client,+ base_url,+ auth_token: RwLock::new(config.auth_token.map(Zeroizing::new)),+ #[cfg(not(target_arch = "wasm32"))]+ user_agent: config.user_agent,+ client_package: config.client_package,+ client_version: config.client_version,+ })+ }++ /// Replace the auth token used for authenticated requests.+ pub fn set_auth_token(&self, auth_token: Option<String>) {+ *self+ .auth_token+ .write()+ .unwrap_or_else(std::sync::PoisonError::into_inner) = auth_token.map(Zeroizing::new);+ }++ /// Create a bare client for presigned object-store requests.+ pub fn object_store(&self) -> ObjectStoreHttpClient {+ ObjectStoreHttpClient {+ client: self.no_redirect_client.clone(),+ }+ }++ /// GET request, returning the response body as text.+ pub async fn get(&self, path: &str) -> Result<String, Error> {+ let url = self.request_url(path)?;+ let context = request_context("GET", &url, &[]);+ let request = self.client.get(&url).headers(self.build_headers()?);+ send_and_parse(request, &context, parse_text_response).await+ }++ /// GET request returning JSON.+ pub async fn get_json<T: DeserializeOwned>(+ &self,+ path: &str,+ query: &[(&str, String)],+ ) -> Result<T, Error> {+ let url = self.request_url(path)?;+ let context = request_context("GET", &url, query);+ let request = self+ .client+ .get(&url)+ .headers(self.build_headers()?)+ .query(query);+ send_and_parse(request, &context, parse_json_response).await+ }++ /// GET request returning `None` for 404.+ pub async fn get_json_optional<T: DeserializeOwned>(+ &self,+ path: &str,+ query: &[(&str, String)],+ ) -> Result<Option<T>, Error> {+ let url = self.request_url(path)?;+ let context = request_context("GET", &url, query);+ let request = self+ .client+ .get(&url)+ .headers(self.build_headers()?)+ .query(query);+ send_and_parse(request, &context, |response| async move {+ if response.status().as_u16() == 404 {+ Ok(None)+ } else {+ parse_json_response(response).await.map(Some)+ }+ })+ .await+ }++ /// POST JSON request.+ pub async fn post_json<T: DeserializeOwned, B: Serialize + Sync + ?Sized>(+ &self,+ path: &str,+ body: &B,+ ) -> Result<T, Error> {+ let url = self.request_url(path)?;+ let context = request_context("POST", &url, &[]);+ let request = self+ .client+ .post(&url)+ .headers(self.build_headers()?)+ .json(body);+ send_and_parse(request, &context, parse_json_response).await+ }++ /// POST JSON request expecting an empty response body.+ pub async fn post_empty<B: Serialize + Sync + ?Sized>(+ &self,+ path: &str,+ body: &B,+ ) -> Result<(), Error> {+ let url = self.request_url(path)?;+ let context = request_context("POST", &url, &[]);+ let request = self+ .client+ .post(&url)+ .headers(self.build_headers()?)+ .json(body);+ send_and_parse(request, &context, parse_empty_response).await+ }++ /// PUT JSON request.+ pub async fn put_json<T: DeserializeOwned, B: Serialize + Sync + ?Sized>(+ &self,+ path: &str,+ body: &B,+ ) -> Result<T, Error> {+ let url = self.request_url(path)?;+ let context = request_context("PUT", &url, &[]);+ let request = self+ .client+ .put(&url)+ .headers(self.build_headers()?)+ .json(body);+ send_and_parse(request, &context, parse_json_response).await+ }++ /// PUT JSON request expecting an empty response body.+ pub async fn put_empty<B: Serialize + Sync + ?Sized>(+ &self,+ path: &str,+ body: &B,+ ) -> Result<(), Error> {+ let url = self.request_url(path)?;+ let context = request_context("PUT", &url, &[]);+ let request = self+ .client+ .put(&url)+ .headers(self.build_headers()?)+ .json(body);+ send_and_parse(request, &context, parse_empty_response).await+ }++ /// DELETE request expecting an empty response body.+ pub async fn delete_empty(&self, path: &str, query: &[(&str, String)]) -> Result<(), Error> {+ let url = self.request_url(path)?;+ let context = request_context("DELETE", &url, query);+ let request = self+ .client+ .delete(&url)+ .headers(self.build_headers()?)+ .query(query);+ send_and_parse(request, &context, parse_empty_response).await+ }++ /// DELETE request returning JSON.+ pub async fn delete_json<T: DeserializeOwned>(+ &self,+ path: &str,+ query: &[(&str, String)],+ ) -> Result<T, Error> {+ let url = self.request_url(path)?;+ let context = request_context("DELETE", &url, query);+ let request = self+ .client+ .delete(&url)+ .headers(self.build_headers()?)+ .query(query);+ send_and_parse(request, &context, parse_json_response).await+ }++ /// 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(),+ ));+ }+ debug_assert!(+ !path_contains_dot_segments(path),+ "request paths must be trusted endpoint paths without dot segments"+ );++ Ok(format!("{}{}", self.base_url, path))+ }++ fn build_headers(&self) -> Result<HeaderMap, Error> {+ let mut headers = self.build_public_headers()?;+ if let Some(auth_token) = self+ .auth_token+ .read()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .as_ref()+ {+ let token =+ HeaderValue::from_str(auth_token).map_err(|e| Error::Parse(e.to_string()))?;+ headers.insert(TOKEN_HEADER, token);+ }+ Ok(headers)+ }++ fn build_public_headers(&self) -> Result<HeaderMap, Error> {+ let mut headers = HeaderMap::new();+ #[cfg(not(target_arch = "wasm32"))]+ if let Some(user_agent) = &self.user_agent {+ let value =+ HeaderValue::from_str(user_agent).map_err(|e| Error::Parse(e.to_string()))?;+ headers.insert(reqwest::header::USER_AGENT, value);+ }+ if let Some(client_package) = &self.client_package {+ let value =+ HeaderValue::from_str(client_package).map_err(|e| Error::Parse(e.to_string()))?;+ headers.insert(CLIENT_PKG_HEADER, value);+ }+ if let Some(client_version) = &self.client_version {+ let value =+ HeaderValue::from_str(client_version).map_err(|e| Error::Parse(e.to_string()))?;+ headers.insert(CLIENT_VERSION_HEADER, value);+ }+ Ok(headers)+ }+}++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).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 send_and_parse<T, F, Fut>(+ request: reqwest::RequestBuilder,+ context: &str,+ parse: F,+) -> Result<T, Error>+where+ F: FnOnce(Response) -> Fut,+ Fut: Future<Output = Result<T, Error>>,+{+ let outcome = async {+ let response = request.send().await?;+ parse(response).await+ }+ .await;+ outcome.map_err(|error| error.with_request_context(context))+}++async fn get_bytes_with_client(client: &reqwest::Client, url: &str) -> Result<Vec<u8>, Error> {+ let mut current_url = parse_url(url)?;+ for _ in 0..MAX_REDIRECTS {+ let response = client.get(current_url.clone()).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..MAX_REDIRECTS {+ 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}")))+}++/// Pass through successful responses; turn error statuses into [`Error::Http`].+async fn check_success(response: Response) -> Result<Response, Error> {+ if response.status().is_success() {+ return Ok(response);+ }+ let status = response.status().as_u16();+ let body = response+ .text()+ .await+ .unwrap_or_else(|_| "failed to read error body".to_string());+ let (code, message) = parse_api_error_body(&body);+ Err(Error::Http {+ status,+ code,+ message,+ })+}++async fn parse_text_response(response: Response) -> Result<String, Error> {+ check_success(response)+ .await?+ .text()+ .await+ .map_err(Into::into)+}++async fn parse_json_response<T: DeserializeOwned>(response: Response) -> Result<T, Error> {+ let text = parse_text_response(response).await?;+ serde_json::from_str(&text).map_err(Into::into)+}++async fn parse_empty_response(response: Response) -> Result<(), Error> {+ check_success(response).await.map(drop)+}++async fn parse_bytes_response(response: Response) -> Result<Vec<u8>, Error> {+ check_success(response)+ .await?+ .bytes()+ .await+ .map(|bytes| bytes.to_vec())+ .map_err(Into::into)+}++fn path_contains_dot_segments(path: &str) -> bool {+ path.split(['?', '#'])+ .next()+ .unwrap_or(path)+ .split('/')+ .any(|segment| {+ matches!(segment, "." | "..")+ || segment.eq_ignore_ascii_case("%2e")+ || segment.eq_ignore_ascii_case("%2e%2e")+ })+}++#[cfg(test)]+mod tests {+ use super::*;+ use mockito::{Matcher, Server};++ fn test_client(base_url: &str) -> HttpClient {+ HttpClient::new_with_config(HttpConfig {+ base_url: base_url.to_string(),+ ..HttpConfig::default()+ })+ .expect("test client creation should succeed")+ }++ #[test]+ fn test_client_creation() {+ let client = test_client("https://api.ente.com/");+ assert_eq!(client.base_url, "https://api.ente.com");+ }++ #[test]+ fn test_parse_error_conversion() {+ let bad_json = "not json";+ let err: Result<PingResponse, Error> = serde_json::from_str(bad_json).map_err(|e| e.into());+ assert!(matches!(err, Err(Error::Parse(_))))+ }++ #[test]+ fn test_parse_api_error_body_prefers_message_and_preserves_code() {+ let (code, message) =+ parse_api_error_body(r#"{"code":"TOO_MANY_WRONG_ATTEMPTS","message":"wait"}"#);+ assert_eq!(code.as_deref(), Some("TOO_MANY_WRONG_ATTEMPTS"));+ assert_eq!(message, "wait");+ }++ #[test]+ fn test_parse_api_error_body_falls_back_to_code_when_message_missing() {+ let (code, message) = parse_api_error_body(r#"{"code":"SESSION_EXPIRED"}"#);+ assert_eq!(code.as_deref(), Some("SESSION_EXPIRED"));+ assert_eq!(message, "SESSION_EXPIRED");+ }++ #[test]+ fn test_request_url_uses_string_join() {+ let client = test_client("https://api.ente.com/v1");+ let url = client.request_url("/ping").unwrap();+ assert_eq!(url, "https://api.ente.com/v1/ping");+ }++ #[test]+ fn test_request_url_preserves_query_and_special_bytes() {+ let client = test_client("https://api.ente.com/v1");+ let url = client.request_url("/%2e%2e%5cadmin?fresh=true").unwrap();+ assert_eq!(url, "https://api.ente.com/v1/%2e%2e%5cadmin?fresh=true");+ }++ #[test]+ fn test_path_contains_dot_segments() {+ assert!(!path_contains_dot_segments("/ping?fresh=true"));+ assert!(path_contains_dot_segments("/../admin"));+ assert!(path_contains_dot_segments("/safe/%2e%2e/admin"));+ assert!(path_contains_dot_segments("/safe/%2E/admin"));+ }++ #[test]+ fn test_request_url_rejects_missing_leading_slash() {+ let client = test_client("https://api.ente.com");+ let err = client.request_url("ping").unwrap_err();+ assert!(matches!(err, Error::InvalidUrl(_)));+ }++ #[test]+ fn test_new_rejects_invalid_base_url() {+ assert!(matches!(+ HttpClient::new("not a url"),+ Err(Error::InvalidUrl(_))+ ));+ }++ #[test]+ fn test_new_rejects_base_url_with_query() {+ assert!(matches!(+ HttpClient::new("https://api.ente.com/v1?stale=true"),+ Err(Error::InvalidUrl(_))+ ));+ }++ #[test]+ fn test_new_rejects_base_url_with_fragment() {+ assert!(matches!(+ HttpClient::new("https://api.ente.com/v1#old"),+ Err(Error::InvalidUrl(_))+ ));+ }++ #[test]+ fn test_set_auth_token_replaces_token() {+ let client = test_client("https://api.ente.com");+ client.set_auth_token(Some("token-1".to_string()));+ assert_eq!(+ client+ .auth_token+ .read()+ .unwrap()+ .as_ref()+ .map(|token| token.as_str()),+ Some("token-1")+ );+ client.set_auth_token(None);+ assert_eq!(+ client+ .auth_token+ .read()+ .unwrap()+ .as_ref()+ .map(|token| token.as_str()),+ None+ );+ }++ #[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");+ }++ #[tokio::test]+ async fn api_json_calls_still_follow_redirects() {+ let mut server = Server::new_async().await;++ let redirect_mock = server+ .mock("GET", "/ping")+ .match_header("x-auth-token", "auth-token")+ .with_status(302)+ .with_header("location", "/pong")+ .create_async()+ .await;++ let target_mock = server+ .mock("GET", "/pong")+ .match_header("x-auth-token", "auth-token")+ .with_status(200)+ .with_body(+ serde_json::json!({+ "message": "pong",+ "id": "redirected"+ })+ .to_string(),+ )+ .create_async()+ .await;++ let client = HttpClient::new_with_config(HttpConfig {+ base_url: server.url(),+ auth_token: Some("auth-token".to_string()),+ user_agent: None,+ client_package: None,+ client_version: None,+ timeout_secs: None,+ })+ .unwrap();++ let response: PingResponse = client.get_json("/ping", &[]).await.unwrap();++ redirect_mock.assert_async().await;+ target_mock.assert_async().await;+ assert_eq!(response.message, "pong");+ assert_eq!(response.id, "redirected");+ }+}diff --git a/rust/crates/core/src/lib.rs b/rust/crates/core/src/lib.rsindex fd5e457c66..fded1318de 100644--- a/rust/crates/core/src/lib.rs+++ b/rust/crates/core/src/lib.rs@@ -6,5 +6,6 @@pub mod auth;pub mod crypto;pub mod http;+pub mod http_legacy;pub mod io;pub mod urls;diff --git a/rust/e2e/tests/full_e2e.rs b/rust/e2e/tests/full_e2e.rsindex 8530820421..b90c01a8c5 100644--- a/rust/e2e/tests/full_e2e.rs+++ b/rust/e2e/tests/full_e2e.rs@@ -6,7 +6,7 @@ use ente_contacts::{LegacyKitRecoveryClient, LegacyKitRecoveryStatus,legacy_models::{LegacyContactState, LegacyRecoveryStatus},};-use ente_core::http::Error as CoreHttpError;+use ente_core::http_legacy::Error as CoreHttpError;use ente_rs::models::account::App;use ente_test_support::{Museum, TestResult};use serde::{Deserialize, Serialize};