Skip to main content

max / makenotwork

8.2 KB · 234 lines History Blame Raw
1 use bytes::Bytes;
2 use std::sync::Arc;
3 use tracing::instrument;
4
5 use crate::{
6 crypto,
7 error::Result,
8 keystore,
9 types::*,
10 };
11
12 use super::SyncKitClient;
13 use super::helpers::check_response;
14
15 impl SyncKitClient {
16 /// Check if the server has an encrypted master key for this user.
17 #[instrument(skip(self))]
18 pub async fn has_server_key(&self) -> Result<bool> {
19 let (url, token) = self.key_url_and_token()?;
20
21 let result = self
22 .retry_request(|| {
23 let req = self.http.get(url).bearer_auth(&token);
24 async move {
25 let resp = req.send().await?;
26 match resp.status().as_u16() {
27 200 | 404 => Ok(resp),
28 status => {
29 let message = resp.text().await.unwrap_or_default();
30 Err(crate::error::SyncKitError::Server { status, message, retry_after_secs: None })
31 }
32 }
33 }
34 })
35 .await?;
36
37 Ok(result.status().as_u16() == 200)
38 }
39
40 /// First device: generate a new master key, encrypt it, push to server, cache in keychain.
41 #[instrument(skip(self, password))]
42 pub async fn setup_encryption_new(&self, password: &str) -> Result<()> {
43 let (app_id, user_id) = self.require_session_ids()?;
44
45 let master_key = crypto::generate_master_key();
46 let envelope = crypto::wrap_master_key(&master_key, password)?;
47
48 // Push to server (expected_version 0 = first key)
49 self.put_server_key(&envelope, 0).await?;
50
51 // Cache in OS keychain
52 keystore::store_key(app_id, user_id, &master_key)?;
53
54 // Store in memory
55 *self.master_key.write() = Some(crypto::ZeroizeOnDrop(master_key));
56
57 tracing::info!("New master key generated and stored");
58 Ok(())
59 }
60
61 /// Second device: pull encrypted master key from server, decrypt with password, cache.
62 #[instrument(skip(self, password))]
63 pub async fn setup_encryption_existing(&self, password: &str) -> Result<()> {
64 let (app_id, user_id) = self.require_session_ids()?;
65
66 let (envelope_json, _key_version) = self.get_server_key().await?;
67 let master_key = crypto::unwrap_master_key(&envelope_json, password)?;
68
69 // Cache in OS keychain
70 keystore::store_key(app_id, user_id, &master_key)?;
71
72 // Store in memory
73 *self.master_key.write() = Some(crypto::ZeroizeOnDrop(master_key));
74
75 tracing::info!("Master key recovered from server");
76 Ok(())
77 }
78
79 /// Subsequent launches: try to load the master key from the OS keychain.
80 /// Returns true if a key was found.
81 pub fn try_load_key_from_keychain(&self) -> Result<bool> {
82 let (app_id, user_id) = self.require_session_ids()?;
83
84 if let Some(key) = keystore::load_key(app_id, user_id)? {
85 *self.master_key.write() = Some(crypto::ZeroizeOnDrop(key));
86 tracing::info!("Master key loaded from keychain");
87 Ok(true)
88 } else {
89 Ok(false)
90 }
91 }
92
93 /// Change the encryption password. Always validates the old password
94 /// against the server envelope before re-encrypting with the new password.
95 ///
96 /// Even when the master key is cached in memory (normal case -- user is
97 /// logged in), the old password is verified by attempting to unwrap the
98 /// server envelope. This prevents an attacker with session access from
99 /// changing the password without knowing the current one.
100 #[instrument(skip(self, old_password, new_password))]
101 pub async fn change_password(
102 &self,
103 old_password: &str,
104 new_password: &str,
105 ) -> Result<()> {
106 // Always fetch the envelope from the server and verify old_password
107 // can decrypt it, regardless of whether we have a cached key.
108 let (envelope_json, key_version) = self.get_server_key().await?;
109 let verified_key = crypto::verify_password_against_envelope(
110 &envelope_json,
111 old_password,
112 )?;
113
114 let master_key = crypto::ZeroizeOnDrop(verified_key);
115
116 // Re-wrap with new password (generates fresh random salt)
117 let new_envelope = crypto::wrap_master_key(&master_key, new_password)?;
118
119 // Optimistic lock: reject if another device changed the password
120 // between our GET and this PUT.
121 self.put_server_key(&new_envelope, key_version).await?;
122
123 tracing::info!("Encryption password changed");
124 Ok(())
125 }
126
127 /// Build the key endpoint URL and extract the bearer token.
128 pub(super) fn key_url_and_token(&self) -> Result<(&str, Arc<String>)> {
129 let token = self.require_token()?;
130 Ok((&self.endpoints.keys, token))
131 }
132
133 /// Upload the encrypted master key envelope to the server (PUT /api/sync/keys).
134 ///
135 /// `expected_version` is the key version the client expects. The server
136 /// rejects with 409 if the current version doesn't match (another device
137 /// changed the password). Use 0 for the initial key upload.
138 pub(super) async fn put_server_key(&self, envelope_json: &str, expected_version: i32) -> Result<()> {
139 let (url, token) = self.key_url_and_token()?;
140
141 let body = Bytes::from(serde_json::to_vec(&PutKeyRequest {
142 encrypted_key: envelope_json.to_string(),
143 expected_version,
144 })?);
145
146 self.retry_request(|| {
147 let req = self
148 .http
149 .put(url)
150 .bearer_auth(&token)
151 .header("content-type", "application/json")
152 .body(body.clone());
153 async move { check_response(req.send().await?).await }
154 })
155 .await?;
156 Ok(())
157 }
158
159 /// Download the encrypted master key envelope from the server (GET /api/sync/keys).
160 /// Returns `(envelope_json, key_version)`.
161 pub(super) async fn get_server_key(&self) -> Result<(String, i32)> {
162 let (url, token) = self.key_url_and_token()?;
163
164 let key_resp: GetKeyResponse = self
165 .retry_request_json(|| {
166 let req = self.http.get(url).bearer_auth(&token);
167 async move { check_response(req.send().await?).await }
168 })
169 .await?;
170 Ok((key_resp.encrypted_key, key_resp.key_version.unwrap_or(0)))
171 }
172 }
173
174 #[cfg(test)]
175 mod tests {
176 use crate::error::SyncKitError;
177
178 use super::*;
179
180 fn test_config() -> super::super::SyncKitConfig {
181 super::super::SyncKitConfig {
182 server_url: "https://example.com".to_string(),
183 api_key: "test-api-key-123".to_string(),
184 }
185 }
186
187 fn test_ids() -> (uuid::Uuid, uuid::Uuid) {
188 (
189 uuid::Uuid::parse_str("550e8400-e29b-41d4-a716-446655440000").unwrap(),
190 uuid::Uuid::parse_str("6ba7b810-9dad-11d1-80b4-00c04fd430c8").unwrap(),
191 )
192 }
193
194 #[test]
195 fn key_url_and_token_builds_correct_url() {
196 let client = SyncKitClient::new(test_config());
197 let (app_id, user_id) = test_ids();
198 client.restore_session("bearer-token", user_id, app_id);
199
200 let (url, token) = client.key_url_and_token().unwrap();
201 assert_eq!(url, "https://example.com/api/v1/sync/keys");
202 assert_eq!(*token, "bearer-token");
203 }
204
205 #[test]
206 fn key_url_and_token_fails_without_session() {
207 let client = SyncKitClient::new(test_config());
208 let err = client.key_url_and_token().unwrap_err();
209 assert!(matches!(err, SyncKitError::NotAuthenticated));
210 }
211
212 // ── Key types ──
213
214 #[test]
215 fn put_key_request_serialization() {
216 let req = PutKeyRequest {
217 encrypted_key: "envelope-json-here".to_string(),
218 expected_version: 1,
219 };
220
221 let json = serde_json::to_string(&req).unwrap();
222 let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
223 assert_eq!(parsed["encrypted_key"], "envelope-json-here");
224 assert_eq!(parsed["expected_version"], 1);
225 }
226
227 #[test]
228 fn get_key_response_deserialization() {
229 let json = r#"{"encrypted_key": "{\"v\":1,\"salt\":\"...\",\"nonce\":\"...\",\"ciphertext\":\"...\"}"}"#;
230 let resp: GetKeyResponse = serde_json::from_str(json).unwrap();
231 assert!(resp.encrypted_key.contains("\"v\":1"));
232 }
233 }
234