proton-sdk 0.1.7

Core Proton account/session/crypto primitives for the Rust Proton SDK
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
//! Account client: user, addresses and their decrypted private keys.
//!
//! Mirrors the parts of `ProtonAccountClient` / `AddressOperations` that the
//! Drive read path needs. The unlock chain is:
//!
//! 1. mailbox password + per-key salt → bcrypt-derived passphrase
//! 2. passphrase → unlock **user keys**
//! 3. user keys → decrypt an **address key token** → unlock the address key
//!
//! (Some address keys have no token and instead reuse an account-key passphrase
//! derived in step 1.) Decrypted keys are cached for the lifetime of the client.

mod dtos;

use std::collections::HashMap;
use std::sync::Arc;

use tokio::sync::Mutex;

use crate::crypto::{self, PrivateKey, PublicKey};
use crate::error::{ProtonError, Result};
use crate::http::ApiHttpClient;
use crate::ids::{AddressId, AddressKeyId};
use crate::session::ProtonApiSession;

use dtos::{
    AddressDto, AddressListResponse, AddressPublicKeyListResponse, KeySaltListResponse,
    UserResponse,
};

pub use dtos::KeySalt;

/// Public view of an email address attached to the account.
#[derive(Debug, Clone)]
pub struct Address {
    pub id: AddressId,
    pub email: String,
    pub order: i32,
    pub status: i32,
    /// Index, within the decrypted key list, of the primary key.
    pub primary_key_index: usize,
    /// Id of the address's primary key (the `AddressKeyID` for write requests).
    pub primary_key_id: AddressKeyId,
}

/// Total account storage usage, in bytes (all Proton products, not Drive-only).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Quota {
    /// Total storage available to the account.
    pub max_space: i64,
    /// Storage currently used.
    pub used_space: i64,
}

impl Quota {
    /// Bytes still free (never negative).
    pub fn available(&self) -> i64 {
        (self.max_space - self.used_space).max(0)
    }

    /// Fraction of the quota in use, `0.0..=1.0` (0 when `max_space` is 0).
    pub fn used_fraction(&self) -> f64 {
        if self.max_space <= 0 {
            0.0
        } else {
            (self.used_space as f64 / self.max_space as f64).clamp(0.0, 1.0)
        }
    }
}

/// Resolves account keys needed to decrypt Drive metadata.
///
/// Construction takes the mailbox (data) password because, per Proton's key
/// model, it is required even for read-only decryption.
#[derive(Clone)]
pub struct AccountClient {
    inner: Arc<Inner>,
}

struct Inner {
    http: ApiHttpClient,
    mailbox_password: Vec<u8>,
    cache: Mutex<Cache>,
}

#[derive(Default)]
struct Cache {
    /// Raw key salts, either fetched from `core/v4/keys/salts` or seeded by the
    /// caller (see [`AccountClient::with_key_salts`]).
    key_salts: Option<Vec<KeySalt>>,
    /// key id → passphrase derived from the mailbox password and key salts.
    key_passphrases: Option<HashMap<String, Vec<u8>>>,
    user_keys: Option<Vec<PrivateKey>>,
    addresses: Option<Vec<Address>>,
    address_keys: HashMap<AddressId, Vec<PrivateKey>>,
    /// email → active (non-compromised) public keys, for authorship verification.
    public_keys: HashMap<String, Vec<PublicKey>>,
}

impl AccountClient {
    pub fn new(session: &ProtonApiSession, mailbox_password: impl Into<Vec<u8>>) -> Self {
        Self {
            inner: Arc::new(Inner {
                http: session.http().clone(),
                mailbox_password: mailbox_password.into(),
                cache: Mutex::new(Cache::default()),
            }),
        }
    }

    /// Build a client with the account's key salts already known, so the key
    /// chain unlocks without calling `core/v4/keys/salts`.
    ///
    /// That endpoint requires the `locked` scope, which only a
    /// password-authenticated access token carries: a session resumed from
    /// persisted tokens (or one whose token has since gone through
    /// `auth/v4/refresh`) gets a 403 there. Capture the salts with
    /// [`key_salts`](Self::key_salts) right after login, persist them next to
    /// the session tokens, and seed them here on resume.
    pub fn with_key_salts(
        session: &ProtonApiSession,
        mailbox_password: impl Into<Vec<u8>>,
        key_salts: Vec<KeySalt>,
    ) -> Self {
        Self {
            inner: Arc::new(Inner {
                http: session.http().clone(),
                mailbox_password: mailbox_password.into(),
                cache: Mutex::new(Cache {
                    key_salts: Some(key_salts),
                    ..Cache::default()
                }),
            }),
        }
    }

    /// The account's key salts, fetched (and cached) unless already seeded.
    ///
    /// Requires the `locked` scope — call it on a freshly password-authenticated
    /// session; see [`with_key_salts`](Self::with_key_salts).
    pub async fn key_salts(&self) -> Result<Vec<KeySalt>> {
        {
            let cache = self.inner.cache.lock().await;
            if let Some(salts) = &cache.key_salts {
                return Ok(salts.clone());
            }
        }

        let response: KeySaltListResponse = self.inner.http.get("core/v4/keys/salts").await?;
        self.inner.cache.lock().await.key_salts = Some(response.key_salts.clone());
        Ok(response.key_salts)
    }

    /// All addresses on the account, ordered by their `Order` field.
    pub async fn addresses(&self) -> Result<Vec<Address>> {
        {
            let cache = self.inner.cache.lock().await;
            if let Some(addresses) = &cache.addresses {
                return Ok(addresses.clone());
            }
        }

        // Ensure user keys (and thus the key passphrases) are loaded first.
        self.user_keys().await?;

        let response: AddressListResponse = self.inner.http.get("core/v4/addresses").await?;
        let mut addresses = Vec::with_capacity(response.addresses.len());
        for dto in &response.addresses {
            let (address, keys) = self.decrypt_address(dto).await?;
            self.inner
                .cache
                .lock()
                .await
                .address_keys
                .insert(address.id.clone(), keys);
            addresses.push(address);
        }
        addresses.sort_by_key(|a| a.order);

        self.inner.cache.lock().await.addresses = Some(addresses.clone());
        Ok(addresses)
    }

    /// The default (lowest-ordered) address.
    pub async fn default_address(&self) -> Result<Address> {
        self.addresses()
            .await?
            .into_iter()
            .next()
            .ok_or_else(|| ProtonError::invalid_operation("user has no address"))
    }

    /// Decrypted private keys for a given address.
    pub async fn address_private_keys(&self, address_id: &AddressId) -> Result<Vec<PrivateKey>> {
        {
            let cache = self.inner.cache.lock().await;
            if let Some(keys) = cache.address_keys.get(address_id) {
                return Ok(keys.clone());
            }
        }

        // Loading all addresses populates the per-address key cache.
        self.addresses().await?;

        let cache = self.inner.cache.lock().await;
        cache.address_keys.get(address_id).cloned().ok_or_else(|| {
            ProtonError::invalid_operation(format!("no keys for address {address_id}"))
        })
    }

    /// Active public keys for an email address, used to verify authorship
    /// signatures. Mirrors C# `AddressOperations.GetPublicKeysAsync`:
    /// `core/v4/keys/all?InternalOnly=1&Email=…`, keeping only keys whose
    /// `Flags` mark them not-compromised. Cached per email.
    ///
    /// Because verification is non-fatal, a resolution failure (unknown
    /// address, external domain, transport error) is logged and yields an empty
    /// key set rather than propagating — the caller then sees
    /// [`crate::crypto::VerificationStatus::NoVerifier`].
    pub async fn public_keys(&self, email: &str) -> Vec<PublicKey> {
        {
            let cache = self.inner.cache.lock().await;
            if let Some(keys) = cache.public_keys.get(email) {
                return keys.clone();
            }
        }

        let path = format!(
            "core/v4/keys/all?InternalOnly=1&Email={}",
            encode_query_component(email)
        );
        let keys = match self
            .inner
            .http
            .get::<AddressPublicKeyListResponse>(&path)
            .await
        {
            Ok(response) => response
                .address
                .keys
                .iter()
                .filter(|entry| entry.is_not_compromised())
                .filter_map(|entry| match PublicKey::from_armored(&entry.public_key) {
                    Ok(key) => Some(key),
                    Err(e) => {
                        tracing::warn!(%email, error = %e, "failed to parse public key");
                        None
                    }
                })
                .collect::<Vec<_>>(),
            Err(e) => {
                tracing::warn!(%email, error = %e, "failed to resolve public keys; treating as unverified");
                Vec::new()
            }
        };

        self.inner
            .cache
            .lock()
            .await
            .public_keys
            .insert(email.to_string(), keys.clone());
        keys
    }

    /// Total account storage usage (`core/v4/users`).
    ///
    /// Account-wide `MaxSpace`/`UsedSpace` across all Proton products, not the
    /// Drive-only quota. Not cached — reflects live usage on each call.
    pub async fn quota(&self) -> Result<Quota> {
        let response: UserResponse = self.inner.http.get("core/v4/users").await?;
        Ok(Quota {
            max_space: response.user.max_space,
            used_space: response.user.used_space,
        })
    }

    /// Decrypted user (account) keys.
    async fn user_keys(&self) -> Result<Vec<PrivateKey>> {
        {
            let cache = self.inner.cache.lock().await;
            if let Some(keys) = &cache.user_keys {
                return Ok(keys.clone());
            }
        }

        let passphrases = self.key_passphrases().await?;
        let response: UserResponse = self.inner.http.get("core/v4/users").await?;

        let mut keys = Vec::new();
        for key_dto in &response.user.keys {
            if !key_dto.is_active() {
                continue;
            }
            let Some(passphrase) = passphrases.get(key_dto.id.as_str()) else {
                tracing::warn!(key_id = %key_dto.id, "no passphrase for user key");
                continue;
            };
            match PrivateKey::from_armored(&key_dto.private_key, passphrase) {
                Ok(key) => keys.push(key),
                Err(e) => {
                    tracing::warn!(key_id = %key_dto.id, error = %e, "failed to unlock user key")
                }
            }
        }

        if keys.is_empty() {
            return Err(ProtonError::invalid_operation(
                "no active user key could be unlocked",
            ));
        }

        self.inner.cache.lock().await.user_keys = Some(keys.clone());
        Ok(keys)
    }

    /// Derive (and cache) the per-key passphrases from the mailbox password and
    /// the account's key salts.
    async fn key_passphrases(&self) -> Result<HashMap<String, Vec<u8>>> {
        {
            let cache = self.inner.cache.lock().await;
            if let Some(passphrases) = &cache.key_passphrases {
                return Ok(passphrases.clone());
            }
        }

        let salts = self.key_salts().await?;
        let mut passphrases = HashMap::new();
        for salt in &salts {
            let Some(salt_b64) = &salt.value else {
                continue;
            };
            if salt_b64.is_empty() {
                continue;
            }
            let salt_bytes = decode_base64(salt_b64)?;
            let passphrase =
                crypto::derive_key_passphrase(&self.inner.mailbox_password, &salt_bytes)?;
            passphrases.insert(salt.key_id.clone(), passphrase);
        }

        self.inner.cache.lock().await.key_passphrases = Some(passphrases.clone());
        Ok(passphrases)
    }

    /// Build the public [`Address`] and unlock all of its active private keys.
    async fn decrypt_address(&self, dto: &AddressDto) -> Result<(Address, Vec<PrivateKey>)> {
        let user_keys = self.user_keys().await?;
        let passphrases = self.key_passphrases().await?;

        let mut keys = Vec::new();
        let mut primary_key_index = None;
        let mut primary_key_id = None;

        for key_dto in &dto.keys {
            if !key_dto.is_active() {
                continue;
            }

            // Two ways to obtain the passphrase that unlocks an address key:
            // decrypt its token with the user keys, or fall back to an
            // account-key passphrase derived from the mailbox password.
            let passphrase = match (&key_dto.token, &key_dto.signature) {
                (Some(token), Some(_signature)) => {
                    match crypto::decrypt_armored_with_keys(token, &user_keys) {
                        Ok(passphrase) => passphrase,
                        Err(e) => {
                            tracing::warn!(key_id = %key_dto.id, error = %e, "failed to decrypt address key token");
                            continue;
                        }
                    }
                }
                _ => match passphrases.get(key_dto.id.as_str()) {
                    Some(passphrase) => passphrase.clone(),
                    None => {
                        tracing::warn!(key_id = %key_dto.id, "no passphrase for address key");
                        continue;
                    }
                },
            };

            match PrivateKey::from_armored(&key_dto.private_key, &passphrase) {
                Ok(key) => {
                    if key_dto.is_primary() && primary_key_index.is_none() {
                        primary_key_index = Some(keys.len());
                        primary_key_id = Some(key_dto.id.clone());
                    }
                    keys.push(key);
                }
                Err(e) => {
                    tracing::warn!(key_id = %key_dto.id, error = %e, "failed to unlock address key");
                }
            }
        }

        let primary_key_index = primary_key_index.ok_or_else(|| {
            ProtonError::invalid_operation(format!("address {} has no primary key", dto.id))
        })?;
        let primary_key_id = primary_key_id.ok_or_else(|| {
            ProtonError::invalid_operation(format!("address {} has no primary key", dto.id))
        })?;

        let address = Address {
            id: dto.id.clone(),
            email: dto.email.clone(),
            order: dto.order,
            status: dto.status,
            primary_key_index,
            primary_key_id,
        };

        Ok((address, keys))
    }
}

fn decode_base64(value: &str) -> Result<Vec<u8>> {
    use base64::Engine;
    base64::engine::general_purpose::STANDARD
        .decode(value)
        .map_err(|e| ProtonError::invalid_operation(format!("invalid base64 salt: {e}")))
}

/// Percent-encode a value for use in a URL query component. Email addresses
/// contain `@` (and may contain `+`), which must be escaped.
fn encode_query_component(value: &str) -> String {
    let mut out = String::with_capacity(value.len());
    for byte in value.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                out.push(byte as char)
            }
            _ => out.push_str(&format!("%{byte:02X}")),
        }
    }
    out
}