Skip to content

armgit / ente

Public Imported from GitHub
0

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

Clean up Contacts crate structure

Manav Rathi9d234cad621c
diff --git a/rust/crates/contacts/src/client.rs b/rust/crates/contacts/src/client.rs
deleted file mode 100644
index 6f228a66fd..0000000000
--- a/rust/crates/contacts/src/client.rs
+++ /dev/null
@@ -1,533 +0,0 @@
-use std::sync::{Arc, RwLock};
-
-use ente_core::crypto::{self, SecretVec};
-use ente_core::http::Api;
-
-use crate::crypto as contacts_crypto;
-use crate::error::{Error, Result};
-use crate::models::{AttachmentType, ContactData, ContactRecord, WrappedRootContactKey};
-use crate::transport::{
- AttachmentUploadUrlRequest, AttachmentUploadUrlResponse, CommitAttachmentRequest,
- ContactDiffResponse, ContactEntityResponse, CreateContactRequest, CreateRootKeyRequest,
- RootKeyResponse, SignedUrlResponse, UpdateContactRequest,
-};
-
-const CONTACT_TYPE: &str = "contact";
-
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum RootKeySource {
- Cache,
- Unresolved,
-}
-
-pub struct OpenContactsInput {
- pub user_id: i64,
- pub cached_wrapped_root_contact_key: Option<WrappedRootContactKey>,
-}
-
-pub struct OpenContactsResult {
- pub client: ContactsClient,
- pub wrapped_root_contact_key: Option<WrappedRootContactKey>,
- pub root_key_source: RootKeySource,
-}
-
-pub struct ContactsClient {
- user_id: i64,
- api: Arc<Api>,
- master_key: Arc<SecretVec>,
- root_contact_key: Arc<RwLock<Option<SecretVec>>>,
- wrapped_root_contact_key: Arc<RwLock<Option<WrappedRootContactKey>>>,
-}
-
-fn wrapped_root_contact_key_from_response(
- remote_root_key: RootKeyResponse,
-) -> WrappedRootContactKey {
- WrappedRootContactKey {
- encrypted_key: remote_root_key.encrypted_key,
- header: remote_root_key.header,
- }
-}
-
-impl ContactsClient {
- pub fn open(
- api: Arc<Api>,
- master_key: Arc<SecretVec>,
- input: OpenContactsInput,
- ) -> Result<OpenContactsResult> {
- let (root_contact_key, wrapped_root_contact_key, root_key_source) =
- if let Some(cached_wrapped_root_contact_key) = input.cached_wrapped_root_contact_key {
- let root_contact_key = contacts_crypto::decrypt_root_contact_key(
- &cached_wrapped_root_contact_key,
- master_key.as_ref(),
- )?;
- (
- Some(SecretVec::new(root_contact_key)),
- Some(cached_wrapped_root_contact_key),
- RootKeySource::Cache,
- )
- } else {
- (None, None, RootKeySource::Unresolved)
- };
- let client = Self {
- user_id: input.user_id,
- api,
- master_key,
- root_contact_key: Arc::new(RwLock::new(root_contact_key)),
- wrapped_root_contact_key: Arc::new(RwLock::new(wrapped_root_contact_key.clone())),
- };
-
- Ok(OpenContactsResult {
- client,
- wrapped_root_contact_key,
- root_key_source,
- })
- }
-
- pub fn user_id(&self) -> i64 {
- self.user_id
- }
-
- pub fn current_wrapped_root_contact_key(&self) -> Option<WrappedRootContactKey> {
- self.wrapped_root_contact_key
- .read()
- .expect("wrapped root key lock poisoned")
- .clone()
- }
-
- fn apply_wrapped_root_contact_key(
- &self,
- wrapped_root_contact_key: WrappedRootContactKey,
- ) -> Result<()> {
- let decrypted_root_key = contacts_crypto::decrypt_root_contact_key(
- &wrapped_root_contact_key,
- self.master_key.as_ref(),
- )?;
- *self
- .root_contact_key
- .write()
- .expect("root contact key lock poisoned") = Some(SecretVec::new(decrypted_root_key));
- *self
- .wrapped_root_contact_key
- .write()
- .expect("wrapped root key lock poisoned") = Some(wrapped_root_contact_key);
- Ok(())
- }
-
- pub async fn create_contact(&self, data: &ContactData) -> Result<ContactRecord> {
- contacts_crypto::validate_contact_data(data)?;
- self.ensure_confirmed_root_contact_key().await?;
-
- let contact_key = SecretVec::new(crypto::random_bytes(32));
- let wrapped_contact_key = {
- let root_contact_key_guard = self
- .root_contact_key
- .read()
- .expect("root contact key lock poisoned");
- let root_contact_key = root_contact_key_guard
- .as_ref()
- .ok_or_else(|| Error::InvalidInput("contacts root key is unresolved".into()))?;
- contacts_crypto::wrap_contact_key(&contact_key, root_contact_key)?
- };
- let encrypted_data = contacts_crypto::encrypt_contact_data(data, &contact_key)?;
- let response = self
- .api
- .post("/contacts")
- .json(&CreateContactRequest {
- contact_user_id: data.contact_user_id,
- encrypted_key: &wrapped_contact_key,
- encrypted_data: &encrypted_data,
- })
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
-
- self.decode_contact(response)
- }
-
- pub async fn get_contact(&self, contact_id: &str) -> Result<ContactRecord> {
- let response = self
- .api
- .get(&format!("/contacts/{contact_id}"))
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
- if !response.is_deleted {
- self.ensure_confirmed_root_contact_key().await?;
- }
- self.decode_contact(response)
- }
-
- pub async fn get_diff(&self, since_time: i64, limit: u16) -> Result<Vec<ContactRecord>> {
- let response = self
- .api
- .get("/contacts/diff")
- .query(&[
- ("sinceTime", since_time.to_string()),
- ("limit", limit.to_string()),
- ])
- .send()
- .await?
- .error_for_status()?
- .json::<ContactDiffResponse>()
- .await?;
- if response.diff.iter().any(|entity| !entity.is_deleted) {
- self.ensure_confirmed_root_contact_key().await?;
- }
-
- response
- .diff
- .into_iter()
- .map(|entity| self.decode_contact(entity))
- .collect()
- }
-
- pub async fn update_contact(
- &self,
- contact_id: &str,
- data: &ContactData,
- ) -> Result<ContactRecord> {
- contacts_crypto::validate_contact_data(data)?;
- self.ensure_confirmed_root_contact_key().await?;
-
- let current = self
- .api
- .get(&format!("/contacts/{contact_id}"))
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
- let encrypted_key = current
- .encrypted_key
- .as_deref()
- .ok_or(Error::MissingEncryptedKey)?;
- let contact_key = {
- let root_contact_key_guard = self
- .root_contact_key
- .read()
- .expect("root contact key lock poisoned");
- let root_contact_key = root_contact_key_guard
- .as_ref()
- .ok_or_else(|| Error::InvalidInput("contacts root key is unresolved".into()))?;
- contacts_crypto::unwrap_contact_key(encrypted_key, root_contact_key)?
- };
- let encrypted_data = contacts_crypto::encrypt_contact_data(data, &contact_key)?;
-
- let response = self
- .api
- .put(&format!("/contacts/{contact_id}"))
- .json(&UpdateContactRequest {
- contact_user_id: data.contact_user_id,
- encrypted_data: &encrypted_data,
- })
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
-
- self.decode_contact(response)
- }
-
- pub async fn delete_contact(&self, contact_id: &str) -> Result<()> {
- self.api
- .delete(&format!("/contacts/{contact_id}"))
- .send()
- .await?
- .error_for_status()?;
- Ok(())
- }
-
- pub async fn set_attachment(
- &self,
- contact_id: &str,
- attachment_type: AttachmentType,
- attachment_bytes: &[u8],
- ) -> Result<ContactRecord> {
- self.ensure_confirmed_root_contact_key().await?;
-
- let current = self
- .api
- .get(&format!("/contacts/{contact_id}"))
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
- let encrypted_key = current
- .encrypted_key
- .as_deref()
- .ok_or(Error::MissingEncryptedKey)?;
- let contact_key = {
- let root_contact_key_guard = self
- .root_contact_key
- .read()
- .expect("root contact key lock poisoned");
- let root_contact_key = root_contact_key_guard
- .as_ref()
- .ok_or_else(|| Error::InvalidInput("contacts root key is unresolved".into()))?;
- contacts_crypto::unwrap_contact_key(encrypted_key, root_contact_key)?
- };
- let encrypted_attachment =
- contacts_crypto::encrypt_profile_picture(attachment_bytes, &contact_key)?;
- let content_md5 = contacts_crypto::content_md5_base64(&encrypted_attachment);
- let size = encrypted_attachment.len() as i64;
-
- let upload = self
- .api
- .post(&format!(
- "/attachments/{}/upload-url",
- attachment_type.as_str()
- ))
- .json(&AttachmentUploadUrlRequest {
- content_length: size,
- content_md5: content_md5.clone(),
- })
- .send()
- .await?
- .error_for_status()?
- .json::<AttachmentUploadUrlResponse>()
- .await?;
-
- self.api
- .http()
- .put(&upload.url)
- .header("Content-MD5", &content_md5)
- .body(encrypted_attachment)
- .send()
- .await?
- .error_for_status()?;
-
- let response = self
- .api
- .put(&format!(
- "/contacts/{contact_id}/attachments/{}",
- attachment_type.as_str()
- ))
- .json(&CommitAttachmentRequest {
- attachment_id: &upload.attachment_id,
- size,
- })
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
-
- self.decode_contact(response)
- }
-
- pub async fn get_attachment_encrypted(
- &self,
- attachment_type: AttachmentType,
- attachment_id: &str,
- ) -> Result<Vec<u8>> {
- let download = self
- .api
- .get(&format!(
- "/attachments/{}/{attachment_id}",
- attachment_type.as_str()
- ))
- .send()
- .await?
- .error_for_status()?
- .json::<SignedUrlResponse>()
- .await?;
- Ok(self
- .api
- .http()
- .get(&download.url)
- .send()
- .await?
- .error_for_status()?
- .bytes()
- .await?)
- }
-
- pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>> {
- let current = self
- .api
- .get(&format!("/contacts/{contact_id}"))
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
- if current.is_deleted || current.profile_picture_attachment_id.is_none() {
- return Err(Error::ProfilePictureNotFound);
- }
- self.ensure_confirmed_root_contact_key().await?;
-
- let encrypted_key = current
- .encrypted_key
- .as_deref()
- .ok_or(Error::MissingEncryptedKey)?;
- let contact_key = {
- let root_contact_key_guard = self
- .root_contact_key
- .read()
- .expect("root contact key lock poisoned");
- let root_contact_key = root_contact_key_guard
- .as_ref()
- .ok_or_else(|| Error::InvalidInput("contacts root key is unresolved".into()))?;
- contacts_crypto::unwrap_contact_key(encrypted_key, root_contact_key)?
- };
- let encrypted_picture = self
- .get_attachment_encrypted(
- AttachmentType::ProfilePicture,
- current.profile_picture_attachment_id.as_deref().unwrap(),
- )
- .await?;
- contacts_crypto::decrypt_profile_picture(&encrypted_picture, &contact_key)
- }
-
- pub async fn delete_attachment(
- &self,
- contact_id: &str,
- attachment_type: AttachmentType,
- ) -> Result<ContactRecord> {
- self.ensure_confirmed_root_contact_key().await?;
- let response = self
- .api
- .delete(&format!(
- "/contacts/{contact_id}/attachments/{}",
- attachment_type.as_str()
- ))
- .send()
- .await?
- .error_for_status()?
- .json::<ContactEntityResponse>()
- .await?;
- self.decode_contact(response)
- }
-
- pub async fn set_profile_picture(
- &self,
- contact_id: &str,
- profile_picture: &[u8],
- ) -> Result<ContactRecord> {
- self.set_attachment(contact_id, AttachmentType::ProfilePicture, profile_picture)
- .await
- }
-
- pub async fn delete_profile_picture(&self, contact_id: &str) -> Result<ContactRecord> {
- self.delete_attachment(contact_id, AttachmentType::ProfilePicture)
- .await
- }
-
- fn decode_contact(&self, entity: ContactEntityResponse) -> Result<ContactRecord> {
- if entity.is_deleted {
- return Ok(ContactRecord {
- id: entity.id,
- contact_user_id: entity.contact_user_id,
- email: None,
- name: None,
- profile_picture_attachment_id: None,
- is_deleted: true,
- created_at: entity.created_at,
- updated_at: entity.updated_at,
- });
- }
-
- let encrypted_key = entity
- .encrypted_key
- .as_deref()
- .ok_or(Error::MissingEncryptedKey)?;
- let encrypted_data = entity
- .encrypted_data
- .as_deref()
- .ok_or(Error::MissingEncryptedData)?;
- let root_contact_key_guard = self
- .root_contact_key
- .read()
- .expect("root contact key lock poisoned");
- let root_contact_key = root_contact_key_guard
- .as_ref()
- .ok_or_else(|| Error::InvalidInput("contacts root key is unresolved".into()))?;
- let contact_key = contacts_crypto::unwrap_contact_key(encrypted_key, root_contact_key)?;
- let data = contacts_crypto::decrypt_contact_data(encrypted_data, &contact_key)?;
-
- Ok(ContactRecord {
- id: entity.id,
- contact_user_id: entity.contact_user_id,
- email: entity.email,
- name: Some(data.name),
- profile_picture_attachment_id: entity.profile_picture_attachment_id,
- is_deleted: false,
- created_at: entity.created_at,
- updated_at: entity.updated_at,
- })
- }
-
- async fn ensure_confirmed_root_contact_key(&self) -> Result<()> {
- if self
- .root_contact_key
- .read()
- .expect("root contact key lock poisoned")
- .is_some()
- {
- return Ok(());
- }
-
- if let Some(remote_root_key) = fetch_root_key(&self.api).await? {
- self.apply_wrapped_root_contact_key(wrapped_root_contact_key_from_response(
- remote_root_key,
- ))?;
- } else {
- let generated_root_contact_key = SecretVec::new(crypto::random_bytes(32));
- let generated_wrapped_root_contact_key = {
- contacts_crypto::encrypt_root_contact_key(
- &generated_root_contact_key,
- self.master_key.as_ref(),
- )?
- };
- if let Some(remote_root_key) =
- create_root_key(&self.api, &generated_wrapped_root_contact_key).await?
- {
- self.apply_wrapped_root_contact_key(wrapped_root_contact_key_from_response(
- remote_root_key,
- ))?;
- } else {
- self.apply_wrapped_root_contact_key(generated_wrapped_root_contact_key)?;
- }
- }
-
- Ok(())
- }
-}
-
-async fn fetch_root_key(api: &Api) -> Result<Option<RootKeyResponse>> {
- let response = api
- .get("/user-entity/key")
- .query(&[("type", CONTACT_TYPE)])
- .send()
- .await?;
- if response.status() == 404 {
- return Ok(None);
- }
- Ok(Some(response.error_for_status()?.json().await?))
-}
-
-async fn create_root_key(
- api: &Api,
- wrapped_root_contact_key: &WrappedRootContactKey,
-) -> Result<Option<RootKeyResponse>> {
- let request = CreateRootKeyRequest {
- r#type: CONTACT_TYPE,
- encrypted_key: &wrapped_root_contact_key.encrypted_key,
- header: &wrapped_root_contact_key.header,
- };
-
- let response = api.post("/user-entity/key").json(&request).send().await?;
- if response.status() == 409
- && let Some(remote_root_key) = fetch_root_key(api).await?
- {
- return Ok(Some(remote_root_key));
- }
- response.error_for_status()?;
- Ok(None)
-}
diff --git a/rust/crates/contacts/src/client/attachment.rs b/rust/crates/contacts/src/client/attachment.rs
new file mode 100644
index 0000000000..ea28ca568a
--- /dev/null
+++ b/rust/crates/contacts/src/client/attachment.rs
@@ -0,0 +1,231 @@
+use md5::{Digest, Md5};
+
+use ente_core::b64;
+use ente_core::crypto::{self, blob};
+use serde::{Deserialize, Serialize};
+
+use super::contact::ContactEntityResponse;
+use super::{ContactRecord, ContactsClient};
+use crate::{Error, Result};
+
+#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "snake_case")]
+pub enum AttachmentType {
+ ProfilePicture,
+}
+
+impl AttachmentType {
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::ProfilePicture => "profile_picture",
+ }
+ }
+}
+
+impl ContactsClient {
+ pub async fn set_profile_picture(
+ &self,
+ contact_id: &str,
+ profile_picture: &[u8],
+ ) -> Result<ContactRecord> {
+ self.set_attachment(contact_id, AttachmentType::ProfilePicture, profile_picture)
+ .await
+ }
+
+ pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>> {
+ let current = self
+ .api
+ .get(&format!("/contacts/{contact_id}"))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+ if current.is_deleted {
+ return Err(Error::ProfilePictureNotFound);
+ }
+ let attachment_id = current
+ .profile_picture_attachment_id
+ .as_deref()
+ .ok_or(Error::ProfilePictureNotFound)?;
+ self.ensure_confirmed_root_contact_key().await?;
+
+ let encrypted_key = current
+ .encrypted_key
+ .as_deref()
+ .ok_or(Error::MissingEncryptedKey)?;
+ let contact_key = self.decrypt_contact_key(encrypted_key)?;
+ let encrypted_picture = self
+ .get_attachment_encrypted(AttachmentType::ProfilePicture, attachment_id)
+ .await?;
+ decrypt_attachment(&encrypted_picture, &contact_key)
+ }
+
+ pub async fn delete_profile_picture(&self, contact_id: &str) -> Result<ContactRecord> {
+ self.delete_attachment(contact_id, AttachmentType::ProfilePicture)
+ .await
+ }
+
+ pub async fn set_attachment(
+ &self,
+ contact_id: &str,
+ attachment_type: AttachmentType,
+ attachment_bytes: &[u8],
+ ) -> Result<ContactRecord> {
+ self.ensure_confirmed_root_contact_key().await?;
+
+ let current = self
+ .api
+ .get(&format!("/contacts/{contact_id}"))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+ let encrypted_key = current
+ .encrypted_key
+ .as_deref()
+ .ok_or(Error::MissingEncryptedKey)?;
+ let contact_key = self.decrypt_contact_key(encrypted_key)?;
+ let encrypted_attachment = encrypt_attachment(attachment_bytes, &contact_key)?;
+ let content_md5 = content_md5_base64(&encrypted_attachment);
+ let size = encrypted_attachment.len() as i64;
+
+ let upload = self
+ .api
+ .post(&format!(
+ "/attachments/{}/upload-url",
+ attachment_type.as_str()
+ ))
+ .json(&AttachmentUploadUrlRequest {
+ content_length: size,
+ content_md5: content_md5.clone(),
+ })
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<AttachmentUploadUrlResponse>()
+ .await?;
+
+ self.api
+ .http()
+ .put(&upload.url)
+ .header("Content-MD5", &content_md5)
+ .body(encrypted_attachment)
+ .send()
+ .await?
+ .error_for_status()?;
+
+ let response = self
+ .api
+ .put(&format!(
+ "/contacts/{contact_id}/attachments/{}",
+ attachment_type.as_str()
+ ))
+ .json(&CommitAttachmentRequest {
+ attachment_id: &upload.attachment_id,
+ size,
+ })
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+
+ self.decode_contact(response)
+ }
+
+ pub async fn get_attachment_encrypted(
+ &self,
+ attachment_type: AttachmentType,
+ attachment_id: &str,
+ ) -> Result<Vec<u8>> {
+ let download = self
+ .api
+ .get(&format!(
+ "/attachments/{}/{attachment_id}",
+ attachment_type.as_str()
+ ))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<SignedUrlResponse>()
+ .await?;
+ Ok(self
+ .api
+ .http()
+ .get(&download.url)
+ .send()
+ .await?
+ .error_for_status()?
+ .bytes()
+ .await?)
+ }
+
+ pub async fn delete_attachment(
+ &self,
+ contact_id: &str,
+ attachment_type: AttachmentType,
+ ) -> Result<ContactRecord> {
+ self.ensure_confirmed_root_contact_key().await?;
+ let response = self
+ .api
+ .delete(&format!(
+ "/contacts/{contact_id}/attachments/{}",
+ attachment_type.as_str()
+ ))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+ self.decode_contact(response)
+ }
+}
+
+fn encrypt_attachment(bytes: &[u8], contact_key: &[u8]) -> Result<Vec<u8>> {
+ Ok(blob::encrypt_combined(
+ bytes,
+ &crypto::Key::try_from_slice(contact_key)?,
+ )?)
+}
+
+fn decrypt_attachment(bytes: &[u8], contact_key: &[u8]) -> Result<Vec<u8>> {
+ Ok(blob::decrypt_combined(
+ bytes,
+ &crypto::Key::try_from_slice(contact_key)?,
+ )?)
+}
+
+fn content_md5_base64(bytes: &[u8]) -> String {
+ b64::encode(Md5::digest(bytes).as_slice())
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct AttachmentUploadUrlRequest {
+ content_length: i64,
+ #[serde(rename = "contentMD5")]
+ content_md5: String,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct AttachmentUploadUrlResponse {
+ #[serde(rename = "attachmentID")]
+ attachment_id: String,
+ url: String,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct CommitAttachmentRequest<'a> {
+ #[serde(rename = "attachmentID")]
+ attachment_id: &'a str,
+ size: i64,
+}
+
+#[derive(Deserialize)]
+struct SignedUrlResponse {
+ url: String,
+}
diff --git a/rust/crates/contacts/src/client/contact.rs b/rust/crates/contacts/src/client/contact.rs
new file mode 100644
index 0000000000..9ed7194ac7
--- /dev/null
+++ b/rust/crates/contacts/src/client/contact.rs
@@ -0,0 +1,238 @@
+use ente_core::b64;
+use ente_core::crypto::{self, SecretVec, blob};
+use serde::{Deserialize, Serialize};
+
+use super::ContactsClient;
+use crate::{Error, Result};
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct ContactData {
+ pub contact_user_id: i64,
+ pub name: String,
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ContactRecord {
+ pub id: String,
+ pub contact_user_id: i64,
+ pub email: Option<String>,
+ pub name: Option<String>,
+ pub profile_picture_attachment_id: Option<String>,
+ pub is_deleted: bool,
+ pub created_at: i64,
+ pub updated_at: i64,
+}
+
+impl ContactsClient {
+ pub async fn create_contact(&self, data: &ContactData) -> Result<ContactRecord> {
+ validate_contact_data(data)?;
+ self.ensure_confirmed_root_contact_key().await?;
+
+ let contact_key = SecretVec::new(crypto::random_bytes(32));
+ let wrapped_contact_key = self.encrypt_contact_key(&contact_key)?;
+ let encrypted_data = encrypt_contact_data(data, &contact_key)?;
+ let response = self
+ .api
+ .post("/contacts")
+ .json(&CreateContactRequest {
+ contact_user_id: data.contact_user_id,
+ encrypted_key: &wrapped_contact_key,
+ encrypted_data: &encrypted_data,
+ })
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+
+ self.decode_contact(response)
+ }
+
+ pub async fn get_contact(&self, contact_id: &str) -> Result<ContactRecord> {
+ let response = self
+ .api
+ .get(&format!("/contacts/{contact_id}"))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+ if !response.is_deleted {
+ self.ensure_confirmed_root_contact_key().await?;
+ }
+ self.decode_contact(response)
+ }
+
+ pub async fn update_contact(
+ &self,
+ contact_id: &str,
+ data: &ContactData,
+ ) -> Result<ContactRecord> {
+ validate_contact_data(data)?;
+ self.ensure_confirmed_root_contact_key().await?;
+
+ let current = self
+ .api
+ .get(&format!("/contacts/{contact_id}"))
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+ let encrypted_key = current
+ .encrypted_key
+ .as_deref()
+ .ok_or(Error::MissingEncryptedKey)?;
+ let contact_key = self.decrypt_contact_key(encrypted_key)?;
+ let encrypted_data = encrypt_contact_data(data, &contact_key)?;
+
+ let response = self
+ .api
+ .put(&format!("/contacts/{contact_id}"))
+ .json(&UpdateContactRequest {
+ contact_user_id: data.contact_user_id,
+ encrypted_data: &encrypted_data,
+ })
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactEntityResponse>()
+ .await?;
+
+ self.decode_contact(response)
+ }
+
+ pub async fn delete_contact(&self, contact_id: &str) -> Result<()> {
+ self.api
+ .delete(&format!("/contacts/{contact_id}"))
+ .send()
+ .await?
+ .error_for_status()?;
+ Ok(())
+ }
+
+ pub async fn get_diff(&self, since_time: i64, limit: u16) -> Result<Vec<ContactRecord>> {
+ let response = self
+ .api
+ .get("/contacts/diff")
+ .query(&[
+ ("sinceTime", since_time.to_string()),
+ ("limit", limit.to_string()),
+ ])
+ .send()
+ .await?
+ .error_for_status()?
+ .json::<ContactDiffResponse>()
+ .await?;
+ if response.diff.iter().any(|entity| !entity.is_deleted) {
+ self.ensure_confirmed_root_contact_key().await?;
+ }
+
+ response
+ .diff
+ .into_iter()
+ .map(|entity| self.decode_contact(entity))
+ .collect()
+ }
+
+ pub(super) fn decode_contact(&self, entity: ContactEntityResponse) -> Result<ContactRecord> {
+ if entity.is_deleted {
+ return Ok(ContactRecord {
+ id: entity.id,
+ contact_user_id: entity.contact_user_id,
+ email: None,
+ name: None,
+ profile_picture_attachment_id: None,
+ is_deleted: true,
+ created_at: entity.created_at,
+ updated_at: entity.updated_at,
+ });
+ }
+
+ let encrypted_key = entity
+ .encrypted_key
+ .as_deref()
+ .ok_or(Error::MissingEncryptedKey)?;
+ let encrypted_data = entity
+ .encrypted_data
+ .as_deref()
+ .ok_or(Error::MissingEncryptedData)?;
+ let contact_key = self.decrypt_contact_key(encrypted_key)?;
+ let data = decrypt_contact_data(encrypted_data, &contact_key)?;
+
+ Ok(ContactRecord {
+ id: entity.id,
+ contact_user_id: entity.contact_user_id,
+ email: entity.email,
+ name: Some(data.name),
+ profile_picture_attachment_id: entity.profile_picture_attachment_id,
+ is_deleted: false,
+ created_at: entity.created_at,
+ updated_at: entity.updated_at,
+ })
+ }
+}
+
+fn validate_contact_data(data: &ContactData) -> Result<()> {
+ if data.contact_user_id <= 0 {
+ return Err(Error::InvalidInput(
+ "contact_user_id must be greater than 0".to_string(),
+ ));
+ }
+ if data.name.trim().is_empty() {
+ return Err(Error::InvalidInput("name is required".to_string()));
+ }
+ Ok(())
+}
+
+fn encrypt_contact_data(data: &ContactData, contact_key: &[u8]) -> Result<String> {
+ let encrypted = blob::encrypt_json_combined(data, &crypto::Key::try_from_slice(contact_key)?)?;
+ Ok(b64::encode(&encrypted))
+}
+
+fn decrypt_contact_data(encrypted_data: &str, contact_key: &[u8]) -> Result<ContactData> {
+ let encrypted_data = b64::decode(encrypted_data)?;
+ Ok(blob::decrypt_json_combined(
+ &encrypted_data,
+ &crypto::Key::try_from_slice(contact_key)?,
+ )?)
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct CreateContactRequest<'a> {
+ #[serde(rename = "contactUserID")]
+ contact_user_id: i64,
+ encrypted_key: &'a str,
+ encrypted_data: &'a str,
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct UpdateContactRequest<'a> {
+ #[serde(rename = "contactUserID")]
+ contact_user_id: i64,
+ encrypted_data: &'a str,
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+pub(super) struct ContactEntityResponse {
+ id: String,
+ #[serde(rename = "contactUserID")]
+ contact_user_id: i64,
+ email: Option<String>,
+ #[serde(rename = "profilePictureAttachmentID")]
+ pub(super) profile_picture_attachment_id: Option<String>,
+ pub(super) encrypted_key: Option<String>,
+ encrypted_data: Option<String>,
+ pub(super) is_deleted: bool,
+ created_at: i64,
+ updated_at: i64,
+}
+
+#[derive(Deserialize)]
+struct ContactDiffResponse {
+ diff: Vec<ContactEntityResponse>,
+}
diff --git a/rust/crates/contacts/src/client/mod.rs b/rust/crates/contacts/src/client/mod.rs
new file mode 100644
index 0000000000..0dbaf77e74
--- /dev/null
+++ b/rust/crates/contacts/src/client/mod.rs
@@ -0,0 +1,252 @@
+mod attachment;
+mod contact;
+
+pub use attachment::AttachmentType;
+pub use contact::{ContactData, ContactRecord};
+
+use std::sync::{Arc, RwLock};
+
+use ente_core::b64;
+use ente_core::crypto::{self, SecretVec, secretbox};
+use ente_core::http::Api;
+use serde::{Deserialize, Serialize};
+
+use crate::{Error, Result};
+
+const CONTACT_TYPE: &str = "contact";
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum RootKeySource {
+ Cache,
+ Unresolved,
+}
+
+#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
+#[serde(rename_all = "camelCase")]
+pub struct WrappedRootContactKey {
+ pub encrypted_key: String,
+ pub header: String,
+}
+
+pub struct OpenContactsInput {
+ pub user_id: i64,
+ pub cached_wrapped_root_contact_key: Option<WrappedRootContactKey>,
+}
+
+pub struct OpenContactsResult {
+ pub client: ContactsClient,
+ pub wrapped_root_contact_key: Option<WrappedRootContactKey>,
+ pub root_key_source: RootKeySource,
+}
+
+pub struct ContactsClient {
+ user_id: i64,
+ api: Arc<Api>,
+ master_key: Arc<SecretVec>,
+ root_contact_key: Arc<RwLock<Option<SecretVec>>>,
+ wrapped_root_contact_key: Arc<RwLock<Option<WrappedRootContactKey>>>,
+}
+
+impl ContactsClient {
+ pub fn open(
+ api: Arc<Api>,
+ master_key: Arc<SecretVec>,
+ input: OpenContactsInput,
+ ) -> Result<OpenContactsResult> {
+ let (root_contact_key, wrapped_root_contact_key, root_key_source) =
+ if let Some(cached_wrapped_root_contact_key) = input.cached_wrapped_root_contact_key {
+ let root_contact_key = decrypt_root_contact_key(
+ &cached_wrapped_root_contact_key,
+ master_key.as_ref(),
+ )?;
+ (
+ Some(root_contact_key),
+ Some(cached_wrapped_root_contact_key),
+ RootKeySource::Cache,
+ )
+ } else {
+ (None, None, RootKeySource::Unresolved)
+ };
+ let client = Self {
+ user_id: input.user_id,
+ api,
+ master_key,
+ root_contact_key: Arc::new(RwLock::new(root_contact_key)),
+ wrapped_root_contact_key: Arc::new(RwLock::new(wrapped_root_contact_key.clone())),
+ };
+
+ Ok(OpenContactsResult {
+ client,
+ wrapped_root_contact_key,
+ root_key_source,
+ })
+ }
+
+ pub fn user_id(&self) -> i64 {
+ self.user_id
+ }
+
+ pub fn current_wrapped_root_contact_key(&self) -> Option<WrappedRootContactKey> {
+ self.wrapped_root_contact_key
+ .read()
+ .expect("wrapped root key lock poisoned")
+ .clone()
+ }
+
+ fn encrypt_contact_key(&self, contact_key: &[u8]) -> Result<String> {
+ let root_contact_key = self
+ .root_contact_key
+ .read()
+ .expect("root contact key lock poisoned");
+ let root_contact_key = root_contact_key
+ .as_ref()
+ .ok_or_else(|| Error::InvalidInput("contacts root key is unresolved".into()))?;
+ let encrypted = secretbox::encrypt_combined(
+ contact_key,
+ &crypto::Key::try_from_slice(root_contact_key)?,
+ );
+ Ok(b64::encode(&encrypted))
+ }
+
+ fn decrypt_contact_key(&self, encrypted_key: &str) -> Result<SecretVec> {
+ let root_contact_key = self
+ .root_contact_key
+ .read()
+ .expect("root contact key lock poisoned");
+ let root_contact_key = root_contact_key
+ .as_ref()
+ .ok_or_else(|| Error::InvalidInput("contacts root key is unresolved".into()))?;
+ let encrypted_key = b64::decode(encrypted_key)?;
+ let contact_key = secretbox::decrypt_combined(
+ &encrypted_key,
+ &crypto::Key::try_from_slice(root_contact_key)?,
+ )?;
+ Ok(SecretVec::new(contact_key))
+ }
+
+ async fn ensure_confirmed_root_contact_key(&self) -> Result<()> {
+ if self
+ .root_contact_key
+ .read()
+ .expect("root contact key lock poisoned")
+ .is_some()
+ {
+ return Ok(());
+ }
+
+ if let Some(remote_root_key) = fetch_root_key(&self.api).await? {
+ self.apply_wrapped_root_contact_key(remote_root_key.into())?;
+ } else {
+ let generated_root_contact_key = SecretVec::new(crypto::random_bytes(32));
+ let generated_wrapped_root_contact_key =
+ encrypt_root_contact_key(&generated_root_contact_key, self.master_key.as_ref())?;
+ if let Some(remote_root_key) =
+ create_root_key(&self.api, &generated_wrapped_root_contact_key).await?
+ {
+ self.apply_wrapped_root_contact_key(remote_root_key.into())?;
+ } else {
+ self.apply_wrapped_root_contact_key(generated_wrapped_root_contact_key)?;
+ }
+ }
+
+ Ok(())
+ }
+
+ fn apply_wrapped_root_contact_key(
+ &self,
+ wrapped_root_contact_key: WrappedRootContactKey,
+ ) -> Result<()> {
+ let decrypted_root_key =
+ decrypt_root_contact_key(&wrapped_root_contact_key, self.master_key.as_ref())?;
+ *self
+ .root_contact_key
+ .write()
+ .expect("root contact key lock poisoned") = Some(decrypted_root_key);
+ *self
+ .wrapped_root_contact_key
+ .write()
+ .expect("wrapped root key lock poisoned") = Some(wrapped_root_contact_key);
+ Ok(())
+ }
+}
+
+fn encrypt_root_contact_key(
+ root_contact_key: &[u8],
+ master_key: &[u8],
+) -> Result<WrappedRootContactKey> {
+ let encrypted = secretbox::encrypt(root_contact_key, &crypto::Key::try_from_slice(master_key)?);
+ Ok(WrappedRootContactKey {
+ encrypted_key: b64::encode(&encrypted.encrypted_data),
+ header: b64::encode(encrypted.nonce.as_bytes()),
+ })
+}
+
+fn decrypt_root_contact_key(
+ wrapped_root_contact_key: &WrappedRootContactKey,
+ master_key: &[u8],
+) -> Result<SecretVec> {
+ let encrypted_key = b64::decode(&wrapped_root_contact_key.encrypted_key)?;
+ let header = b64::decode(&wrapped_root_contact_key.header)?;
+ let root_contact_key = secretbox::decrypt(
+ &encrypted_key,
+ &crypto::Nonce::try_from_slice(&header)?,
+ &crypto::Key::try_from_slice(master_key)?,
+ )?;
+ Ok(SecretVec::new(root_contact_key))
+}
+
+async fn fetch_root_key(api: &Api) -> Result<Option<RootKeyResponse>> {
+ let response = api
+ .get("/user-entity/key")
+ .query(&[("type", CONTACT_TYPE)])
+ .send()
+ .await?;
+ if response.status() == 404 {
+ return Ok(None);
+ }
+ Ok(Some(response.error_for_status()?.json().await?))
+}
+
+async fn create_root_key(
+ api: &Api,
+ wrapped_root_contact_key: &WrappedRootContactKey,
+) -> Result<Option<RootKeyResponse>> {
+ let request = CreateRootKeyRequest {
+ r#type: CONTACT_TYPE,
+ encrypted_key: &wrapped_root_contact_key.encrypted_key,
+ header: &wrapped_root_contact_key.header,
+ };
+
+ let response = api.post("/user-entity/key").json(&request).send().await?;
+ if response.status() == 409
+ && let Some(remote_root_key) = fetch_root_key(api).await?
+ {
+ return Ok(Some(remote_root_key));
+ }
+ response.error_for_status()?;
+ Ok(None)
+}
+
+#[derive(Deserialize)]
+#[serde(rename_all = "camelCase")]
+struct RootKeyResponse {
+ encrypted_key: String,
+ header: String,
+}
+
+impl From<RootKeyResponse> for WrappedRootContactKey {
+ fn from(value: RootKeyResponse) -> Self {
+ Self {
+ encrypted_key: value.encrypted_key,
+ header: value.header,
+ }
+ }
+}
+
+#[derive(Serialize)]
+#[serde(rename_all = "camelCase")]
+struct CreateRootKeyRequest<'a> {
+ r#type: &'a str,
+ encrypted_key: &'a str,
+ header: &'a str,
+}
diff --git a/rust/crates/contacts/src/crypto.rs b/rust/crates/contacts/src/crypto.rs
deleted file mode 100644
index 7bf73e98fc..0000000000
--- a/rust/crates/contacts/src/crypto.rs
+++ /dev/null
@@ -1,89 +0,0 @@
-use md5::{Digest, Md5};
-
-use ente_core::b64;
-use ente_core::crypto::{self, blob, secretbox};
-
-use crate::error::{Error, Result};
-use crate::models::{ContactData, WrappedRootContactKey};
-
-pub fn encrypt_root_contact_key(
- root_contact_key: &[u8],
- master_key: &[u8],
-) -> Result<WrappedRootContactKey> {
- let encrypted = secretbox::encrypt(root_contact_key, &crypto::Key::try_from_slice(master_key)?);
- Ok(WrappedRootContactKey {
- encrypted_key: b64::encode(&encrypted.encrypted_data),
- header: b64::encode(encrypted.nonce.as_bytes()),
- })
-}
-
-pub fn decrypt_root_contact_key(
- wrapped_root_contact_key: &WrappedRootContactKey,
- master_key: &[u8],
-) -> Result<Vec<u8>> {
- let encrypted_key = b64::decode(&wrapped_root_contact_key.encrypted_key)?;
- let header = b64::decode(&wrapped_root_contact_key.header)?;
- Ok(secretbox::decrypt(
- &encrypted_key,
- &crypto::Nonce::try_from_slice(&header)?,
- &crypto::Key::try_from_slice(master_key)?,
- )?)
-}
-
-pub fn wrap_contact_key(contact_key: &[u8], root_contact_key: &[u8]) -> Result<String> {
- let encrypted =
- secretbox::encrypt_combined(contact_key, &crypto::Key::try_from_slice(root_contact_key)?);
- Ok(b64::encode(&encrypted))
-}
-
-pub fn unwrap_contact_key(encrypted_key_b64: &str, root_contact_key: &[u8]) -> Result<Vec<u8>> {
- let encrypted_key = b64::decode(encrypted_key_b64)?;
- Ok(secretbox::decrypt_combined(
- &encrypted_key,
- &crypto::Key::try_from_slice(root_contact_key)?,
- )?)
-}
-
-pub fn encrypt_contact_data(data: &ContactData, contact_key: &[u8]) -> Result<String> {
- let encrypted = blob::encrypt_json_combined(data, &crypto::Key::try_from_slice(contact_key)?)?;
- Ok(b64::encode(&encrypted))
-}
-
-pub fn decrypt_contact_data(encrypted_data_b64: &str, contact_key: &[u8]) -> Result<ContactData> {
- let encrypted_data = b64::decode(encrypted_data_b64)?;
- Ok(blob::decrypt_json_combined(
- &encrypted_data,
- &crypto::Key::try_from_slice(contact_key)?,
- )?)
-}
-
-pub fn encrypt_profile_picture(bytes: &[u8], contact_key: &[u8]) -> Result<Vec<u8>> {
- Ok(blob::encrypt_combined(
- bytes,
- &crypto::Key::try_from_slice(contact_key)?,
- )?)
-}
-
-pub fn decrypt_profile_picture(bytes: &[u8], contact_key: &[u8]) -> Result<Vec<u8>> {
- Ok(blob::decrypt_combined(
- bytes,
- &crypto::Key::try_from_slice(contact_key)?,
- )?)
-}
-
-pub fn content_md5_base64(bytes: &[u8]) -> String {
- let digest = Md5::digest(bytes);
- b64::encode(digest.as_slice())
-}
-
-pub fn validate_contact_data(data: &ContactData) -> Result<()> {
- if data.contact_user_id <= 0 {
- return Err(Error::InvalidInput(
- "contact_user_id must be greater than 0".to_string(),
- ));
- }
- if data.name.trim().is_empty() {
- return Err(Error::InvalidInput("name is required".to_string()));
- }
- Ok(())
-}
diff --git a/rust/crates/contacts/src/lib.rs b/rust/crates/contacts/src/lib.rs
index 33245c0107..8a9291b908 100644
--- a/rust/crates/contacts/src/lib.rs
+++ b/rust/crates/contacts/src/lib.rs
@@ -1,9 +1,8 @@
mod client;
-pub mod crypto;
mod error;
-mod models;
-mod transport;
-pub use client::{ContactsClient, OpenContactsInput, OpenContactsResult, RootKeySource};
+pub use client::{
+ AttachmentType, ContactData, ContactRecord, ContactsClient, OpenContactsInput,
+ OpenContactsResult, RootKeySource, WrappedRootContactKey,
+};
pub use error::{Error, Result};
-pub use models::{AttachmentType, ContactData, ContactRecord, WrappedRootContactKey};
diff --git a/rust/crates/contacts/src/models.rs b/rust/crates/contacts/src/models.rs
deleted file mode 100644
index 83dc25ecd5..0000000000
--- a/rust/crates/contacts/src/models.rs
+++ /dev/null
@@ -1,41 +0,0 @@
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "snake_case")]
-pub enum AttachmentType {
- ProfilePicture,
-}
-
-impl AttachmentType {
- pub fn as_str(self) -> &'static str {
- match self {
- Self::ProfilePicture => "profile_picture",
- }
- }
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "camelCase")]
-pub struct WrappedRootContactKey {
- pub encrypted_key: String,
- pub header: String,
-}
-
-#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
-#[serde(rename_all = "camelCase")]
-pub struct ContactData {
- pub contact_user_id: i64,
- pub name: String,
-}
-
-#[derive(Debug, Clone, PartialEq, Eq)]
-pub struct ContactRecord {
- pub id: String,
- pub contact_user_id: i64,
- pub email: Option<String>,
- pub name: Option<String>,
- pub profile_picture_attachment_id: Option<String>,
- pub is_deleted: bool,
- pub created_at: i64,
- pub updated_at: i64,
-}
diff --git a/rust/crates/contacts/src/transport.rs b/rust/crates/contacts/src/transport.rs
deleted file mode 100644
index 512476a02c..0000000000
--- a/rust/crates/contacts/src/transport.rs
+++ /dev/null
@@ -1,83 +0,0 @@
-use serde::{Deserialize, Serialize};
-
-#[derive(Debug, Clone, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct RootKeyResponse {
- pub encrypted_key: String,
- pub header: String,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CreateRootKeyRequest<'a> {
- pub r#type: &'a str,
- pub encrypted_key: &'a str,
- pub header: &'a str,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CreateContactRequest<'a> {
- #[serde(rename = "contactUserID")]
- pub contact_user_id: i64,
- pub encrypted_key: &'a str,
- pub encrypted_data: &'a str,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct UpdateContactRequest<'a> {
- #[serde(rename = "contactUserID")]
- pub contact_user_id: i64,
- pub encrypted_data: &'a str,
-}
-
-#[derive(Debug, Clone, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct ContactEntityResponse {
- pub id: String,
- #[serde(rename = "contactUserID")]
- pub contact_user_id: i64,
- pub email: Option<String>,
- #[serde(rename = "profilePictureAttachmentID")]
- pub profile_picture_attachment_id: Option<String>,
- pub encrypted_key: Option<String>,
- pub encrypted_data: Option<String>,
- pub is_deleted: bool,
- pub created_at: i64,
- pub updated_at: i64,
-}
-
-#[derive(Debug, Clone, Deserialize)]
-pub struct ContactDiffResponse {
- pub diff: Vec<ContactEntityResponse>,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct AttachmentUploadUrlRequest {
- pub content_length: i64,
- #[serde(rename = "contentMD5")]
- pub content_md5: String,
-}
-
-#[derive(Debug, Clone, Deserialize)]
-#[serde(rename_all = "camelCase")]
-pub struct AttachmentUploadUrlResponse {
- #[serde(rename = "attachmentID")]
- pub attachment_id: String,
- pub url: String,
-}
-
-#[derive(Debug, Clone, Serialize)]
-#[serde(rename_all = "camelCase")]
-pub struct CommitAttachmentRequest<'a> {
- #[serde(rename = "attachmentID")]
- pub attachment_id: &'a str,
- pub size: i64,
-}
-
-#[derive(Debug, Clone, Deserialize)]
-pub struct SignedUrlResponse {
- pub url: String,
-}
diff --git a/rust/crates/contacts/tests/contacts_mock.rs b/rust/crates/contacts/tests/contacts_mock.rs
index fce15e6a20..f77c3323a9 100644
--- a/rust/crates/contacts/tests/contacts_mock.rs
+++ b/rust/crates/contacts/tests/contacts_mock.rs
@@ -1,12 +1,12 @@
use std::sync::Arc;
-use ente_contacts::crypto as contacts_crypto;
use ente_contacts::{
AttachmentType, ContactData, ContactsClient, OpenContactsInput, OpenContactsResult,
RootKeySource, WrappedRootContactKey,
};
use ente_core::{
- crypto::{Key, SecretVec},
+ b64,
+ crypto::{Key, SecretVec, blob, secretbox},
http::{Api, ApiConfig, Auth, Http},
};
use mockito::{Matcher, Server};
@@ -44,7 +44,11 @@ fn open(
}
fn wrap_root(root_key: &[u8], master_key: &[u8]) -> WrappedRootContactKey {
- contacts_crypto::encrypt_root_contact_key(root_key, master_key).unwrap()
+ let encrypted = secretbox::encrypt(root_key, &Key::try_from_slice(master_key).unwrap());
+ WrappedRootContactKey {
+ encrypted_key: b64::encode(&encrypted.encrypted_data),
+ header: b64::encode(encrypted.nonce.as_bytes()),
+ }
}
fn live_entity_json(
@@ -55,8 +59,13 @@ fn live_entity_json(
profile_picture_attachment_id: Option<&str>,
) -> serde_json::Value {
let contact_key = Key::generate().as_bytes().to_vec();
- let encrypted_key = contacts_crypto::wrap_contact_key(&contact_key, root_key).unwrap();
- let encrypted_data = contacts_crypto::encrypt_contact_data(data, &contact_key).unwrap();
+ let encrypted_key = b64::encode(&secretbox::encrypt_combined(
+ &contact_key,
+ &Key::try_from_slice(root_key).unwrap(),
+ ));
+ let encrypted_data = b64::encode(
+ &blob::encrypt_json_combined(data, &Key::try_from_slice(&contact_key).unwrap()).unwrap(),
+ );
serde_json::json!({
"id": id,
@@ -360,13 +369,14 @@ async fn get_profile_picture_uses_signed_download_url() {
&root_key,
Some("ua_picture1"),
);
- let contact_key = contacts_crypto::unwrap_contact_key(
- attached_entity["encryptedKey"].as_str().unwrap(),
- &root_key,
+ let contact_key = secretbox::decrypt_combined(
+ &b64::decode(attached_entity["encryptedKey"].as_str().unwrap()).unwrap(),
+ &Key::try_from_slice(&root_key).unwrap(),
)
.unwrap();
let encrypted_picture =
- contacts_crypto::encrypt_profile_picture(&picture_bytes, &contact_key).unwrap();
+ blob::encrypt_combined(&picture_bytes, &Key::try_from_slice(&contact_key).unwrap())
+ .unwrap();
let get_contact_mock = server
.mock("GET", "/contacts/ct_picture1")