Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

[rust][contacts] fix root key races and redirect handling

Neeraj Gupta488c63c6f151
diff --git a/rust/contacts/src/client.rs b/rust/contacts/src/client.rs
index 8611572652..c6af6d2118 100644
--- a/rust/contacts/src/client.rs
+++ b/rust/contacts/src/client.rs
@@ -49,6 +49,13 @@ pub struct ContactsCtx {
root_key_confirmed: AtomicBool,
}
+fn wrapped_root_key_from_response(remote_root_key: RootKeyResponse) -> WrappedRootContactKey {
+ WrappedRootContactKey {
+ encrypted_key: remote_root_key.encrypted_key,
+ header: remote_root_key.header,
+ }
+}
+
impl ContactsCtx {
pub async fn open(input: OpenContactsCtxInput) -> Result<OpenContactsCtxResult> {
let http = HttpClient::new_with_config(HttpConfig {
@@ -71,10 +78,7 @@ impl ContactsCtx {
false,
)
} else if let Some(remote_root_key) = fetch_root_key(&http).await? {
- let wrapped_root_key = WrappedRootContactKey {
- encrypted_key: remote_root_key.encrypted_key,
- header: remote_root_key.header,
- };
+ let wrapped_root_key = wrapped_root_key_from_response(remote_root_key);
let root_contact_key = contacts_crypto::decrypt_root_contact_key(
&wrapped_root_key,
&input.master_key,
@@ -86,18 +90,33 @@ impl ContactsCtx {
true,
)
} else {
- let root_contact_key = keys::generate_key();
- let wrapped_root_key = contacts_crypto::encrypt_root_contact_key(
- &root_contact_key,
+ let generated_root_contact_key = keys::generate_key();
+ let generated_wrapped_root_key = contacts_crypto::encrypt_root_contact_key(
+ &generated_root_contact_key,
&input.master_key,
)?;
- create_root_key(&http, &wrapped_root_key).await?;
- (
- root_contact_key,
- wrapped_root_key,
- RootKeySource::Created,
- true,
- )
+ if let Some(remote_root_key) =
+ create_root_key(&http, &generated_wrapped_root_key).await?
+ {
+ let wrapped_root_key = wrapped_root_key_from_response(remote_root_key);
+ let root_contact_key = contacts_crypto::decrypt_root_contact_key(
+ &wrapped_root_key,
+ &input.master_key,
+ )?;
+ (
+ root_contact_key,
+ wrapped_root_key,
+ RootKeySource::Server,
+ true,
+ )
+ } else {
+ (
+ generated_root_contact_key,
+ generated_wrapped_root_key,
+ RootKeySource::Created,
+ true,
+ )
+ }
};
let ctx = Self {
@@ -132,6 +151,21 @@ impl ContactsCtx {
.clone()
}
+ fn apply_wrapped_root_key(&self, wrapped_root_key: WrappedRootContactKey) -> Result<()> {
+ let master_key = self.master_key.read().expect("master key lock poisoned");
+ let decrypted_root_key =
+ contacts_crypto::decrypt_root_contact_key(&wrapped_root_key, &master_key)?;
+ *self
+ .root_contact_key
+ .write()
+ .expect("root contact key lock poisoned") = SecretVec::new(decrypted_root_key);
+ *self
+ .wrapped_root_key
+ .write()
+ .expect("wrapped root key lock poisoned") = wrapped_root_key;
+ Ok(())
+ }
+
pub async fn create_contact(&self, data: &ContactData) -> Result<ContactRecord> {
contacts_crypto::validate_contact_data(data)?;
self.ensure_root_key_confirmed().await?;
@@ -426,24 +460,12 @@ impl ContactsCtx {
}
if let Some(remote_root_key) = fetch_root_key(&self.http).await? {
- let wrapped_root_key = WrappedRootContactKey {
- encrypted_key: remote_root_key.encrypted_key,
- header: remote_root_key.header,
- };
- let master_key = self.master_key.read().expect("master key lock poisoned");
- let decrypted_root_key =
- contacts_crypto::decrypt_root_contact_key(&wrapped_root_key, &master_key)?;
- *self
- .root_contact_key
- .write()
- .expect("root contact key lock poisoned") = SecretVec::new(decrypted_root_key);
- *self
- .wrapped_root_key
- .write()
- .expect("wrapped root key lock poisoned") = wrapped_root_key;
+ self.apply_wrapped_root_key(wrapped_root_key_from_response(remote_root_key))?;
} else {
let wrapped_root_key = self.current_wrapped_root_key();
- create_root_key(&self.http, &wrapped_root_key).await?;
+ if let Some(remote_root_key) = create_root_key(&self.http, &wrapped_root_key).await? {
+ self.apply_wrapped_root_key(wrapped_root_key_from_response(remote_root_key))?;
+ }
}
self.root_key_confirmed.store(true, Ordering::Release);
@@ -460,7 +482,7 @@ async fn fetch_root_key(http: &HttpClient) -> Result<Option<RootKeyResponse>> {
async fn create_root_key(
http: &HttpClient,
wrapped_root_key: &WrappedRootContactKey,
-) -> Result<()> {
+) -> Result<Option<RootKeyResponse>> {
let request = CreateRootKeyRequest {
r#type: CONTACT_TYPE,
encrypted_key: &wrapped_root_key.encrypted_key,
@@ -468,10 +490,10 @@ async fn create_root_key(
};
match http.post_empty("/user-entity/key", &request).await {
- Ok(()) => Ok(()),
+ Ok(()) => Ok(None),
Err(HttpError::Http { .. }) => {
- if fetch_root_key(http).await?.is_some() {
- Ok(())
+ if let Some(remote_root_key) = fetch_root_key(http).await? {
+ Ok(Some(remote_root_key))
} else {
Err(HttpError::Http {
status: 500,
diff --git a/rust/contacts/tests/contacts_mock.rs b/rust/contacts/tests/contacts_mock.rs
index 6b41d2d28c..e75cc1461c 100644
--- a/rust/contacts/tests/contacts_mock.rs
+++ b/rust/contacts/tests/contacts_mock.rs
@@ -87,6 +87,81 @@ async fn open_fetches_existing_root_key_from_server() {
assert_eq!(opened.wrapped_root_key, wrapped_root);
}
+#[tokio::test]
+async fn open_applies_server_root_key_when_create_loses_race() {
+ let mut server = Server::new_async().await;
+ let master_key = keys::generate_key();
+ let server_root_key = keys::generate_key();
+ let server_wrapped_root = wrap_root(&server_root_key, &master_key);
+ let contact = sample_contact();
+
+ let initial_fetch_mock = server
+ .mock("GET", "/user-entity/key")
+ .match_query(Matcher::UrlEncoded("type".into(), "contact".into()))
+ .with_status(404)
+ .expect(1)
+ .create_async()
+ .await;
+
+ let create_race_mock = server
+ .mock("POST", "/user-entity/key")
+ .match_body(Matcher::PartialJson(serde_json::json!({
+ "type": "contact"
+ })))
+ .with_status(409)
+ .expect(1)
+ .create_async()
+ .await;
+
+ let winner_fetch_mock = server
+ .mock("GET", "/user-entity/key")
+ .match_query(Matcher::UrlEncoded("type".into(), "contact".into()))
+ .with_status(200)
+ .with_body(
+ serde_json::json!({
+ "userID": 7,
+ "type": "contact",
+ "encryptedKey": server_wrapped_root.encrypted_key,
+ "header": server_wrapped_root.header,
+ "createdAt": 1
+ })
+ .to_string(),
+ )
+ .expect(1)
+ .create_async()
+ .await;
+
+ let get_contact_mock = server
+ .mock("GET", "/contacts/ct_contact1")
+ .with_status(200)
+ .with_body(
+ live_entity_json(
+ "ct_contact1",
+ &contact,
+ &server_root_key,
+ None,
+ )
+ .to_string(),
+ )
+ .expect(1)
+ .create_async()
+ .await;
+
+ let opened = ContactsCtx::open(open_input(server.url(), master_key))
+ .await
+ .unwrap();
+ let fetched = opened.ctx.get_contact("ct_contact1").await.unwrap();
+
+ initial_fetch_mock.assert_async().await;
+ create_race_mock.assert_async().await;
+ winner_fetch_mock.assert_async().await;
+ get_contact_mock.assert_async().await;
+ assert_eq!(opened.root_key_source, RootKeySource::Server);
+ assert_eq!(opened.wrapped_root_key, server_wrapped_root);
+ assert_eq!(fetched.name.as_deref(), Some(contact.name.as_str()));
+}
+
#[tokio::test]
async fn create_contact_uses_cached_root_key_but_confirms_before_write() {
let mut server = Server::new_async().await;
diff --git a/rust/core/src/http.rs b/rust/core/src/http.rs
index 04d066674e..bef049cb07 100644
--- a/rust/core/src/http.rs
+++ b/rust/core/src/http.rs
@@ -5,6 +5,8 @@ use std::sync::RwLock;
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};
@@ -122,7 +124,7 @@ impl HttpClient {
});
#[cfg(not(target_arch = "wasm32"))]
- let mut builder = reqwest::Client::builder();
+ let mut builder = reqwest::Client::builder().redirect(Policy::none());
#[cfg(target_arch = "wasm32")]
let builder = reqwest::Client::builder();
#[cfg(not(target_arch = "wasm32"))]
@@ -795,4 +797,51 @@ mod tests {
put_mock.assert_async().await;
assert_eq!(bytes, b"ok");
}
+
+ #[tokio::test]
+ async fn api_download_drops_auth_header_on_cross_origin_redirect() {
+ let mut origin_server = Server::new_async().await;
+ let mut redirect_server = Server::new_async().await;
+
+ let redirect_mock = origin_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(302)
+ .with_header("location", &format!("{}/redirected", redirect_server.url()))
+ .create_async()
+ .await;
+
+ let target_mock = redirect_server
+ .mock("GET", "/redirected")
+ .match_header("x-auth-token", Matcher::Missing)
+ .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: origin_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", origin_server.url()))
+ .await
+ .unwrap();
+
+ redirect_mock.assert_async().await;
+ target_mock.assert_async().await;
+ assert_eq!(bytes, b"ok");
+ }
}