use bytes::Bytes; use std::sync::Arc; use tracing::instrument; use crate::{ crypto, error::Result, keystore, types::*, }; use super::SyncKitClient; use super::helpers::check_response; impl SyncKitClient { /// Check if the server has an encrypted master key for this user. #[instrument(skip(self))] pub async fn has_server_key(&self) -> Result { let (url, token) = self.key_url_and_token()?; let result = self .retry_request(|| { let req = self.http.get(url).bearer_auth(&token); async move { let resp = req.send().await?; match resp.status().as_u16() { 200 | 404 => Ok(resp), status => { let message = resp.text().await.unwrap_or_default(); Err(crate::error::SyncKitError::Server { status, message, retry_after_secs: None }) } } } }) .await?; Ok(result.status().as_u16() == 200) } /// First device: generate a new master key, encrypt it, push to server, cache in keychain. #[instrument(skip(self, password))] pub async fn setup_encryption_new(&self, password: &str) -> Result<()> { let (app_id, user_id) = self.require_session_ids()?; let master_key = crypto::generate_master_key(); let envelope = crypto::wrap_master_key(&master_key, password)?; // Push to server (expected_version 0 = first key) self.put_server_key(&envelope, 0).await?; // Cache in OS keychain keystore::store_key(app_id, user_id, &master_key)?; // Store in memory *self.master_key.write() = Some(crypto::ZeroizeOnDrop(master_key)); tracing::info!("New master key generated and stored"); Ok(()) } /// Second device: pull encrypted master key from server, decrypt with password, cache. #[instrument(skip(self, password))] pub async fn setup_encryption_existing(&self, password: &str) -> Result<()> { let (app_id, user_id) = self.require_session_ids()?; let (envelope_json, _key_version) = self.get_server_key().await?; let master_key = crypto::unwrap_master_key(&envelope_json, password)?; // Cache in OS keychain keystore::store_key(app_id, user_id, &master_key)?; // Store in memory *self.master_key.write() = Some(crypto::ZeroizeOnDrop(master_key)); tracing::info!("Master key recovered from server"); Ok(()) } /// Subsequent launches: try to load the master key from the OS keychain. /// Returns true if a key was found. pub fn try_load_key_from_keychain(&self) -> Result { let (app_id, user_id) = self.require_session_ids()?; if let Some(key) = keystore::load_key(app_id, user_id)? { *self.master_key.write() = Some(crypto::ZeroizeOnDrop(key)); tracing::info!("Master key loaded from keychain"); Ok(true) } else { Ok(false) } } /// Change the encryption password. Always validates the old password /// against the server envelope before re-encrypting with the new password. /// /// Even when the master key is cached in memory (normal case -- user is /// logged in), the old password is verified by attempting to unwrap the /// server envelope. This prevents an attacker with session access from /// changing the password without knowing the current one. #[instrument(skip(self, old_password, new_password))] pub async fn change_password( &self, old_password: &str, new_password: &str, ) -> Result<()> { // Always fetch the envelope from the server and verify old_password // can decrypt it, regardless of whether we have a cached key. let (envelope_json, key_version) = self.get_server_key().await?; let verified_key = crypto::verify_password_against_envelope( &envelope_json, old_password, )?; let master_key = crypto::ZeroizeOnDrop(verified_key); // Re-wrap with new password (generates fresh random salt) let new_envelope = crypto::wrap_master_key(&master_key, new_password)?; // Optimistic lock: reject if another device changed the password // between our GET and this PUT. self.put_server_key(&new_envelope, key_version).await?; tracing::info!("Encryption password changed"); Ok(()) } /// Build the key endpoint URL and extract the bearer token. pub(super) fn key_url_and_token(&self) -> Result<(&str, Arc)> { let token = self.require_token()?; Ok((&self.endpoints.keys, token)) } /// Upload the encrypted master key envelope to the server (PUT /api/sync/keys). /// /// `expected_version` is the key version the client expects. The server /// rejects with 409 if the current version doesn't match (another device /// changed the password). Use 0 for the initial key upload. pub(super) async fn put_server_key(&self, envelope_json: &str, expected_version: i32) -> Result<()> { let (url, token) = self.key_url_and_token()?; let body = Bytes::from(serde_json::to_vec(&PutKeyRequest { encrypted_key: envelope_json.to_string(), expected_version, })?); self.retry_request(|| { let req = self .http .put(url) .bearer_auth(&token) .header("content-type", "application/json") .body(body.clone()); async move { check_response(req.send().await?).await } }) .await?; Ok(()) } /// Download the encrypted master key envelope from the server (GET /api/sync/keys). /// Returns `(envelope_json, key_version)`. pub(super) async fn get_server_key(&self) -> Result<(String, i32)> { let (url, token) = self.key_url_and_token()?; let key_resp: GetKeyResponse = self .retry_request_json(|| { let req = self.http.get(url).bearer_auth(&token); async move { check_response(req.send().await?).await } }) .await?; Ok((key_resp.encrypted_key, key_resp.key_version.unwrap_or(0))) } } #[cfg(test)] mod tests { use crate::error::SyncKitError; use super::*; fn test_config() -> super::super::SyncKitConfig { super::super::SyncKitConfig { server_url: "https://example.com".to_string(), api_key: "test-api-key-123".to_string(), } } fn test_ids() -> (uuid::Uuid, uuid::Uuid) { ( uuid::Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(), uuid::Uuid::parse_str("6ba7b810-9dad-11d1-80b4-00c04fd430c8").unwrap(), ) } #[test] fn key_url_and_token_builds_correct_url() { let client = SyncKitClient::new(test_config()); let (app_id, user_id) = test_ids(); client.restore_session("bearer-token", user_id, app_id); let (url, token) = client.key_url_and_token().unwrap(); assert_eq!(url, "https://example.com/api/v1/sync/keys"); assert_eq!(*token, "bearer-token"); } #[test] fn key_url_and_token_fails_without_session() { let client = SyncKitClient::new(test_config()); let err = client.key_url_and_token().unwrap_err(); assert!(matches!(err, SyncKitError::NotAuthenticated)); } // ── Key types ── #[test] fn put_key_request_serialization() { let req = PutKeyRequest { encrypted_key: "envelope-json-here".to_string(), expected_version: 1, }; let json = serde_json::to_string(&req).unwrap(); let parsed: serde_json::Value = serde_json::from_str(&json).unwrap(); assert_eq!(parsed["encrypted_key"], "envelope-json-here"); assert_eq!(parsed["expected_version"], 1); } #[test] fn get_key_response_deserialization() { let json = r#"{"encrypted_key": "{\"v\":1,\"salt\":\"...\",\"nonce\":\"...\",\"ciphertext\":\"...\"}"}"#; let resp: GetKeyResponse = serde_json::from_str(json).unwrap(); assert!(resp.encrypted_key.contains("\"v\":1")); } }