π End-to-end encrypted cloud for everything.
Dart 2faandroidauthye2eeencryptionend-to-end-encryptionfluttergolanggoogle-photosgoogle-photos-alternativeiosopensourcephotosprivacyprivacy-toolstypescriptzero-knowledge
[rust][contacts] add generic attachment operations
Neeraj Guptad4df2a9be1fb
diff --git a/mobile/packages/rust/rust/src/api/contacts.rs b/mobile/packages/rust/rust/src/api/contacts.rsindex 96fdb5c80d..e3978314c6 100644--- a/mobile/packages/rust/rust/src/api/contacts.rs+++ b/mobile/packages/rust/rust/src/api/contacts.rs@@ -3,23 +3,53 @@use std::sync::Arc;use ente_contacts::{- ContactData as CoreContactData, ContactRecord as CoreContactRecord,- ContactsCtx as CoreContactsCtx, ContactsError as CoreContactsError,- OpenContactsCtxInput as CoreOpenContactsCtxInput, RootKeySource as CoreRootKeySource,- WrappedRootContactKey as CoreWrappedRootContactKey,+ AttachmentType as CoreAttachmentType, ContactData as CoreContactData,+ ContactRecord as CoreContactRecord, ContactsCtx as CoreContactsCtx,+ ContactsError as CoreContactsError, OpenContactsCtxInput as CoreOpenContactsCtxInput,+ RootKeySource as CoreRootKeySource, WrappedRootContactKey as CoreWrappedRootContactKey,};use flutter_rust_bridge::frb;#[frb]+/// Contact API errors exposed over Flutter Rust Bridge.pub enum ContactsError {- Http { message: String, status: u16 },- Network { message: String },- Parse { message: String },- InvalidUrl { message: String },- Crypto { message: String },- InvalidInput { message: String },+ /// API HTTP error with status and message.+ Http {+ /// Error response body or summary message.+ message: String,+ /// HTTP status code returned by the API.+ status: u16,+ },+ /// Network transport error.+ Network {+ /// Underlying network error description.+ message: String,+ },+ /// Response or payload parse error.+ Parse {+ /// Parse failure description.+ message: String,+ },+ /// Invalid request or base URL error.+ InvalidUrl {+ /// Invalid URL description.+ message: String,+ },+ /// Cryptographic operation failed.+ Crypto {+ /// Cryptographic error description.+ message: String,+ },+ /// Input validation failed.+ InvalidInput {+ /// Validation failure description.+ message: String,+ },+ /// Missing encrypted contact payload on a live contact response.MissingEncryptedData,+ /// Missing encrypted contact key on a live contact response.MissingEncryptedKey,+ /// Contact profile picture does not exist.ProfilePictureNotFound,}@@ -51,8 +81,11 @@ impl From<CoreContactsError> for ContactsError {#[frb]#[derive(Clone)]+/// Persistable wrapped root contact key returned from Rust.pub struct WrappedRootContactKey {+ /// Wrapped root contact key bytes encoded as base64.pub encrypted_key: String,+ /// Blob header used to unwrap the root contact key.pub header: String,}@@ -76,9 +109,13 @@ impl From<WrappedRootContactKey> for CoreWrappedRootContactKey {#[frb]#[derive(Clone)]+/// Encrypted contact payload fields managed by the client.pub struct ContactData {+ /// User id of the contact being referenced.pub contact_user_id: i64,+ /// User-chosen display name for the contact.pub name: String,+ /// Optional birthday in `yyyy-MM-dd` format.pub birth_date: Option<String>,}@@ -94,15 +131,25 @@ impl From<ContactData> for CoreContactData {#[frb]#[derive(Clone)]+/// Fully decoded contact record returned by Rust.pub struct ContactRecord {+ /// Stable contact entity id.pub id: String,+ /// User id of the referenced contact.pub contact_user_id: i64,+ /// Server-resolved mutable email for the referenced user.pub email: Option<String>,+ /// Client-managed display name from the encrypted payload.pub name: Option<String>,+ /// Optional birthday from the encrypted payload.pub birth_date: Option<String>,+ /// Current profile picture attachment id, if any.pub profile_picture_attachment_id: Option<String>,+ /// Whether this record is a tombstone.pub is_deleted: bool,+ /// Contact creation timestamp in microseconds.pub created_at: i64,+ /// Last update timestamp in microseconds.pub updated_at: i64,}@@ -124,9 +171,13 @@ impl From<CoreContactRecord> for ContactRecord {#[frb]#[derive(Clone)]+/// Source used to obtain the root contact key during open.pub enum RootKeySource {+ /// Reused the caller-provided cached wrapped root key.Cache,+ /// Fetched the wrapped root key from the server.Server,+ /// Created a new wrapped root key on the server.Created,}@@ -141,31 +192,62 @@ impl From<CoreRootKeySource> for RootKeySource {}#[frb]+#[derive(Clone, Copy)]+/// Attachment types supported by the contacts subsystem.+pub enum AttachmentType {+ /// Current contact profile picture.+ ProfilePicture,+}++impl From<AttachmentType> for CoreAttachmentType {+ fn from(value: AttachmentType) -> Self {+ match value {+ AttachmentType::ProfilePicture => CoreAttachmentType::ProfilePicture,+ }+ }+}++#[frb]+/// Input required to open an account-scoped contacts context.pub struct OpenContactsCtxInput {+ /// Base Ente API URL.pub base_url: String,+ /// Auth token for Ente API requests.pub auth_token: String,+ /// Logged-in owner user id.pub user_id: i64,+ /// Logged-in account key used to unwrap or create the root contact key.pub master_key: Vec<u8>,+ /// Optional cached wrapped root key for the current user.pub cached_root_key: Option<WrappedRootContactKey>,+ /// Optional user agent to send to Ente API endpoints.pub user_agent: Option<String>,+ /// Optional client package header to send to Ente API endpoints.pub client_package: Option<String>,+ /// Optional client version header to send to Ente API endpoints.pub client_version: Option<String>,}#[frb]+/// Result returned when opening a contacts context.pub struct OpenContactsCtxResult {+ /// Opaque contacts context bound to the current account/session.pub ctx: ContactsCtx,+ /// Current wrapped root key that the caller may persist.pub wrapped_root_key: WrappedRootContactKey,+ /// Source used to obtain the root key during open.pub root_key_source: RootKeySource,}#[frb(opaque)]#[derive(Clone)]+/// Opaque account-scoped contacts context exposed to Flutter.pub struct ContactsCtx {inner: Arc<CoreContactsCtx>,}#[frb]+/// Open a contacts context for the current account.pub async fn open_contacts_ctx(input: OpenContactsCtxInput,) -> Result<OpenContactsCtxResult, ContactsError> {@@ -193,19 +275,23 @@ pub async fn open_contacts_ctx(impl ContactsCtx {#[frb(sync)]+ /// Return the owner user id for this contacts context.pub fn user_id(&self) -> i64 {self.inner.user_id()}+ /// Replace the auth token used for subsequent API requests.pub fn update_auth_token(&self, auth_token: String) {self.inner.update_auth_token(auth_token);}#[frb(sync)]+ /// Return the current wrapped root key for caller-managed persistence.pub fn current_wrapped_root_key(&self) -> WrappedRootContactKey {self.inner.current_wrapped_root_key().into()}+ /// Create a contact for the referenced user.pub async fn create_contact(&self, data: ContactData) -> Result<ContactRecord, ContactsError> {self.inner.create_contact(&data.into())@@ -214,6 +300,7 @@ impl ContactsCtx {.map_err(Into::into)}+ /// Fetch a single contact by id.pub async fn get_contact(&self, contact_id: String) -> Result<ContactRecord, ContactsError> {self.inner.get_contact(&contact_id)@@ -222,6 +309,7 @@ impl ContactsCtx {.map_err(Into::into)}+ /// Fetch a contacts diff since the provided timestamp.pub async fn get_diff(&self,since_time: i64,@@ -234,6 +322,7 @@ impl ContactsCtx {.map_err(Into::into)}+ /// Update the encrypted payload for an existing contact.pub async fn update_contact(&self,contact_id: String,@@ -246,6 +335,7 @@ impl ContactsCtx {.map_err(Into::into)}+ /// Tombstone a contact by id.pub async fn delete_contact(&self, contact_id: String) -> Result<(), ContactsError> {self.inner.delete_contact(&contact_id)@@ -253,33 +343,69 @@ impl ContactsCtx {.map_err(Into::into)}- pub async fn set_profile_picture(+ /// Encrypt and upload a new contact profile picture.+ pub async fn set_attachment(&self,contact_id: String,- profile_picture: Vec<u8>,+ attachment_type: AttachmentType,+ attachment_bytes: Vec<u8>,) -> Result<ContactRecord, ContactsError> {self.inner- .set_profile_picture(&contact_id, &profile_picture)+ .set_attachment(&contact_id, attachment_type.into(), &attachment_bytes).await.map(Into::into).map_err(Into::into)}- pub async fn get_profile_picture(&self, contact_id: String) -> Result<Vec<u8>, ContactsError> {+ /// Download an attachment by type and attachment id.+ pub async fn get_attachment(+ &self,+ attachment_type: AttachmentType,+ attachment_id: String,+ ) -> Result<Vec<u8>, ContactsError> {self.inner- .get_profile_picture(&contact_id)+ .get_attachment(attachment_type.into(), &attachment_id).await.map_err(Into::into)}- pub async fn delete_profile_picture(+ /// Remove the current attachment for a contact and type.+ pub async fn delete_attachment(&self,contact_id: String,+ attachment_type: AttachmentType,) -> Result<ContactRecord, ContactsError> {self.inner- .delete_profile_picture(&contact_id)+ .delete_attachment(&contact_id, attachment_type.into()).await.map(Into::into).map_err(Into::into)}++ /// Encrypt and upload a new contact profile picture.+ pub async fn set_profile_picture(+ &self,+ contact_id: String,+ profile_picture: Vec<u8>,+ ) -> Result<ContactRecord, ContactsError> {+ self.set_attachment(contact_id, AttachmentType::ProfilePicture, profile_picture)+ .await+ }++ /// Download and decrypt the current contact profile picture.+ pub async fn get_profile_picture(&self, contact_id: String) -> Result<Vec<u8>, ContactsError> {+ self.inner+ .get_profile_picture(&contact_id)+ .await+ .map_err(Into::into)+ }++ /// Remove the current contact profile picture.+ pub async fn delete_profile_picture(+ &self,+ contact_id: String,+ ) -> Result<ContactRecord, ContactsError> {+ self.delete_attachment(contact_id, AttachmentType::ProfilePicture)+ .await+ }}diff --git a/rust/contacts/src/client.rs b/rust/contacts/src/client.rsindex 8d11d71745..8611572652 100644--- a/rust/contacts/src/client.rs+++ b/rust/contacts/src/client.rs@@ -6,10 +6,10 @@ use ente_core::http::{Error as HttpError, HttpClient, HttpConfig};use crate::crypto as contacts_crypto;use crate::error::{ContactsError, Result};-use crate::models::{ContactData, ContactRecord, WrappedRootContactKey};+use crate::models::{AttachmentType, ContactData, ContactRecord, WrappedRootContactKey};use crate::transport::{- CommitProfilePictureRequest, ContactDiffResponse, ContactEntityResponse, CreateContactRequest,- CreateRootKeyRequest, ProfilePictureUploadUrlRequest, ProfilePictureUploadUrlResponse,+ AttachmentUploadUrlRequest, AttachmentUploadUrlResponse, CommitAttachmentRequest,+ ContactDiffResponse, ContactEntityResponse, CreateContactRequest, CreateRootKeyRequest,RootKeyResponse, SignedUrlResponse, UpdateContactRequest,};@@ -234,10 +234,11 @@ impl ContactsCtx {Ok(())}- pub async fn set_profile_picture(+ pub async fn set_attachment(&self,contact_id: &str,- profile_picture: &[u8],+ attachment_type: AttachmentType,+ attachment_bytes: &[u8],) -> Result<ContactRecord> {self.ensure_root_key_confirmed().await?;@@ -256,16 +257,16 @@ impl ContactsCtx {.expect("root contact key lock poisoned");contacts_crypto::unwrap_contact_key(encrypted_key, &root_contact_key)?};- let encrypted_picture =- contacts_crypto::encrypt_profile_picture(profile_picture, &contact_key)?;- let content_md5 = contacts_crypto::content_md5_base64(&encrypted_picture);+ let encrypted_attachment =+ contacts_crypto::encrypt_profile_picture(attachment_bytes, &contact_key)?;+ let content_md5 = contacts_crypto::content_md5_base64(&encrypted_attachment);let upload = self.http- .post_json::<ProfilePictureUploadUrlResponse, _>(- &format!("/contacts/{contact_id}/profile-picture/upload-url"),- &ProfilePictureUploadUrlRequest {- content_length: encrypted_picture.len() as i64,+ .post_json::<AttachmentUploadUrlResponse, _>(+ &format!("/attachments/{}/upload-url", attachment_type.as_str()),+ &AttachmentUploadUrlRequest {+ content_length: encrypted_attachment.len() as i64,content_md5: content_md5.clone(),},)@@ -274,7 +275,7 @@ impl ContactsCtx {self.object_store_http.put_bytes(&upload.url,- &encrypted_picture,+ &encrypted_attachment,&[("Content-MD5", content_md5)],).await?;@@ -282,10 +283,13 @@ impl ContactsCtx {let response = self.http.put_json::<ContactEntityResponse, _>(- &format!("/contacts/{contact_id}/profile-picture"),- &CommitProfilePictureRequest {+ &format!(+ "/contacts/{contact_id}/attachments/{}",+ attachment_type.as_str()+ ),+ &CommitAttachmentRequest {attachment_id: &upload.attachment_id,- size: encrypted_picture.len() as i64,+ size: encrypted_attachment.len() as i64,},).await?;@@ -293,6 +297,24 @@ impl ContactsCtx {self.decode_contact(response)}+ pub async fn get_attachment(+ &self,+ attachment_type: AttachmentType,+ attachment_id: &str,+ ) -> Result<Vec<u8>> {+ let download = self+ .http+ .get_json::<SignedUrlResponse>(+ &format!("/attachments/{}/{attachment_id}", attachment_type.as_str()),+ &[],+ )+ .await?;+ self.object_store_http+ .get_bytes(&download.url)+ .await+ .map_err(Into::into)+ }+pub async fn get_profile_picture(&self, contact_id: &str) -> Result<Vec<u8>> {let current = self.http@@ -313,26 +335,48 @@ impl ContactsCtx {.expect("root contact key lock poisoned");contacts_crypto::unwrap_contact_key(encrypted_key, &root_contact_key)?};- let download = self- .http- .get_json::<SignedUrlResponse>(&format!("/contacts/{contact_id}/profile-picture"), &[])+ let encrypted_picture = self+ .get_attachment(+ AttachmentType::ProfilePicture,+ current.profile_picture_attachment_id.as_deref().unwrap(),+ ).await?;- let encrypted_picture = self.object_store_http.get_bytes(&download.url).await?;contacts_crypto::decrypt_profile_picture(&encrypted_picture, &contact_key)}- pub async fn delete_profile_picture(&self, contact_id: &str) -> Result<ContactRecord> {+ pub async fn delete_attachment(+ &self,+ contact_id: &str,+ attachment_type: AttachmentType,+ ) -> Result<ContactRecord> {self.ensure_root_key_confirmed().await?;let response = self.http.delete_json::<ContactEntityResponse>(- &format!("/contacts/{contact_id}/profile-picture"),+ &format!(+ "/contacts/{contact_id}/attachments/{}",+ attachment_type.as_str()+ ),&[],).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 {diff --git a/rust/contacts/src/lib.rs b/rust/contacts/src/lib.rsindex e5f6f0fa04..1c6bb4fdf8 100644--- a/rust/contacts/src/lib.rs+++ b/rust/contacts/src/lib.rs@@ -6,4 +6,4 @@ pub mod transport;pub use client::{ContactsCtx, OpenContactsCtxInput, OpenContactsCtxResult, RootKeySource};pub use error::{ContactsError, Result};-pub use models::{ContactData, ContactRecord, WrappedRootContactKey};+pub use models::{AttachmentType, ContactData, ContactRecord, WrappedRootContactKey};diff --git a/rust/contacts/src/models.rs b/rust/contacts/src/models.rsindex 54a7a31b39..990c253e86 100644--- a/rust/contacts/src/models.rs+++ b/rust/contacts/src/models.rs@@ -1,5 +1,19 @@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 {diff --git a/rust/contacts/src/transport.rs b/rust/contacts/src/transport.rsindex 0961494014..512476a02c 100644--- a/rust/contacts/src/transport.rs+++ b/rust/contacts/src/transport.rs@@ -55,7 +55,7 @@ pub struct ContactDiffResponse {#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]-pub struct ProfilePictureUploadUrlRequest {+pub struct AttachmentUploadUrlRequest {pub content_length: i64,#[serde(rename = "contentMD5")]pub content_md5: String,@@ -63,7 +63,7 @@ pub struct ProfilePictureUploadUrlRequest {#[derive(Debug, Clone, Deserialize)]#[serde(rename_all = "camelCase")]-pub struct ProfilePictureUploadUrlResponse {+pub struct AttachmentUploadUrlResponse {#[serde(rename = "attachmentID")]pub attachment_id: String,pub url: String,@@ -71,7 +71,7 @@ pub struct ProfilePictureUploadUrlResponse {#[derive(Debug, Clone, Serialize)]#[serde(rename_all = "camelCase")]-pub struct CommitProfilePictureRequest<'a> {+pub struct CommitAttachmentRequest<'a> {#[serde(rename = "attachmentID")]pub attachment_id: &'a str,pub size: i64,diff --git a/rust/contacts/tests/contacts_mock.rs b/rust/contacts/tests/contacts_mock.rsindex 1e93585d66..6b41d2d28c 100644--- a/rust/contacts/tests/contacts_mock.rs+++ b/rust/contacts/tests/contacts_mock.rs@@ -1,6 +1,6 @@use ente_contacts::client::{ContactsCtx, OpenContactsCtxInput, RootKeySource};use ente_contacts::crypto as contacts_crypto;-use ente_contacts::models::{ContactData, WrappedRootContactKey};+use ente_contacts::models::{AttachmentType, ContactData, WrappedRootContactKey};use ente_core::crypto::{encode_b64, keys};use md5::Digest;use mockito::{Matcher, Server};@@ -197,7 +197,7 @@ async fn set_profile_picture_uses_signed_upload_url_and_commit() {let upload_url = format!("{}/upload/ua_picture1", server.url());let upload_url_mock = server- .mock("POST", "/contacts/ct_picture1/profile-picture/upload-url")+ .mock("POST", "/attachments/profile_picture/upload-url").with_status(200).with_body(serde_json::json!({@@ -233,7 +233,7 @@ async fn set_profile_picture_uses_signed_upload_url_and_commit() {Some("ua_picture1"),);let commit_mock = server- .mock("PUT", "/contacts/ct_picture1/profile-picture")+ .mock("PUT", "/contacts/ct_picture1/attachments/profile_picture").with_status(200).with_body(attached_entity.to_string()).expect(1)@@ -313,7 +313,7 @@ async fn get_profile_picture_uses_signed_download_url() {let signed_download_url = format!("{}/download/ua_picture1", server.url());let signed_url_mock = server- .mock("GET", "/contacts/ct_picture1/profile-picture")+ .mock("GET", "/attachments/profile_picture/ua_picture1").with_status(200).with_body(serde_json::json!({@@ -351,6 +351,73 @@ async fn get_profile_picture_uses_signed_download_url() {assert_eq!(downloaded, picture_bytes);}+#[tokio::test]+async fn get_attachment_uses_generic_signed_download_url() {+ let mut server = Server::new_async().await;+ let master_key = keys::generate_key();+ let root_key = keys::generate_key();+ let wrapped_root = wrap_root(&root_key, &master_key);+ let payload = b"generic-attachment-bytes".to_vec();++ let root_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": wrapped_root.encrypted_key,+ "header": wrapped_root.header,+ "createdAt": 1+ })+ .to_string(),+ )+ .create_async()+ .await;++ let signed_download_url = format!("{}/download/ua_generic1", server.url());+ let signed_url_mock = server+ .mock("GET", "/attachments/profile_picture/ua_generic1")+ .with_status(200)+ .with_body(+ serde_json::json!({+ "url": signed_download_url+ })+ .to_string(),+ )+ .expect(1)+ .create_async()+ .await;++ let download_mock = server+ .mock("GET", "/download/ua_generic1")+ .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(payload.clone())+ .expect(1)+ .create_async()+ .await;++ let ctx = ContactsCtx::open(open_input(server.url(), master_key))+ .await+ .unwrap()+ .ctx;++ let downloaded = ctx+ .get_attachment(AttachmentType::ProfilePicture, "ua_generic1")+ .await+ .unwrap();++ root_mock.assert_async().await;+ signed_url_mock.assert_async().await;+ download_mock.assert_async().await;+ assert_eq!(downloaded, payload);+}+#[tokio::test]async fn deleted_contacts_surface_as_tombstones() {let mut server = Server::new_async().await;