1use std::collections::HashMap;
8
9use chrono::{DateTime, Utc};
10use serde::{Deserialize, Serialize};
11use tsafe_core::audit::{AuditClipboardContext, AuditContext, AuditEntry, AuditRevealContext};
12use tsafe_core::crypto::{self, CipherKind, KeyPurpose, KeySchedule, VaultKey};
13pub use tsafe_core::errors::{SafeError, SafeResult};
14use tsafe_core::vault::{SecretEntry, SecretSlot, StructureBinding, VaultFile};
15use tsafe_core::{team, totp};
16use zeroize::{Zeroize, Zeroizing};
17
18pub mod envelopes;
19
20const VAULT_SCHEMA: &str = "tsafe/vault/v1";
21const TEAM_SCHEMA: &str = "tsafe/vault/v2";
22const BOUND_SCHEMA: &str = "tsafe/vault/v3";
26const VAULT_KDF_ALGORITHM: &str = "argon2id";
27const VAULT_CHALLENGE_PLAINTEXT: &[u8] = b"tsafe-vault-challenge-v1";
28const KDF_M_COST_MIN: u32 = 8_192;
29const KDF_M_COST_MAX: u32 = 131_072;
30const KDF_T_COST_MIN: u32 = 1;
31const KDF_T_COST_MAX: u32 = 20;
32const KDF_P_COST_MIN: u32 = 1;
33const KDF_P_COST_MAX: u32 = 16;
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
37#[serde(rename_all = "snake_case")]
38pub enum MobileVaultKind {
39 Password,
40 Team,
41}
42
43#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
49pub struct MobileItemMetadata {
50 pub key: String,
51 pub created_at: DateTime<Utc>,
52 pub updated_at: DateTime<Utc>,
53 #[serde(default, skip_serializing_if = "HashMap::is_empty")]
54 pub tags: HashMap<String, String>,
55 pub history_len: usize,
56 pub item_kind: MobileItemKind,
57}
58
59#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
61#[serde(rename_all = "snake_case")]
62pub enum MobileItemKind {
63 Secret,
64 Totp,
65}
66
67#[derive(Debug)]
73pub struct MobileVaultItem {
74 pub key: String,
75 pub value: Zeroizing<String>,
76 pub metadata: MobileItemMetadata,
77}
78
79#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
81pub struct MobileTotpCode {
82 pub code: String,
83 pub seconds_remaining: u64,
84}
85
86pub struct MobileVault {
88 kind: MobileVaultKind,
89 file: VaultFile,
90 key: VaultKey,
91 cipher: CipherKind,
92 key_schedule: KeySchedule,
93}
94
95impl MobileVault {
96 pub fn open_password_vault_from_bytes(bytes: &[u8], password: &[u8]) -> SafeResult<Self> {
98 let file = parse_vault_file(bytes)?;
99 if !matches!(file.schema.as_str(), VAULT_SCHEMA | BOUND_SCHEMA) {
100 return Err(SafeError::InvalidVault {
101 reason: format!("unsupported password vault schema: {}", file.schema),
102 });
103 }
104 if team::is_team_vault(&file) {
105 return Err(SafeError::InvalidVault {
106 reason: "team vault requires age identity open path".into(),
107 });
108 }
109 validate_password_kdf(&file)?;
110 let salt = crypto::decode_b64(&file.kdf.salt)?;
111 let key = crypto::derive_key(
112 password,
113 &salt,
114 file.kdf.m_cost,
115 file.kdf.t_cost,
116 file.kdf.p_cost,
117 )?;
118 Self::open_with_key(file, key, MobileVaultKind::Password)
119 }
120
121 pub fn open_team_vault_from_bytes(bytes: &[u8], identity_file: &str) -> SafeResult<Self> {
123 let file = parse_vault_file(bytes)?;
124 if !matches!(file.schema.as_str(), TEAM_SCHEMA | BOUND_SCHEMA) {
125 return Err(SafeError::InvalidVault {
126 reason: format!("unsupported team vault schema: {}", file.schema),
127 });
128 }
129 if !team::is_team_vault(&file) {
130 return Err(SafeError::InvalidVault {
131 reason: "vault is missing team age recipients or wrapped DEK".into(),
132 });
133 }
134 let identities = parse_age_identities(identity_file)?;
135 let key = team::unwrap_dek(&file, &identities)?;
136 Self::open_with_key(file, key, MobileVaultKind::Team)
137 }
138
139 pub fn kind(&self) -> MobileVaultKind {
140 self.kind
141 }
142
143 pub fn list_items(&self) -> Vec<MobileItemMetadata> {
145 let mut items: Vec<_> = self
146 .file
147 .secrets
148 .iter()
149 .map(|(key, entry)| metadata_for(key, entry))
150 .collect();
151 items.sort_by(|a, b| a.key.cmp(&b.key));
152 items
153 }
154
155 pub fn get_item(&self, key: &str) -> SafeResult<MobileVaultItem> {
157 let entry = self
158 .file
159 .secrets
160 .get(key)
161 .ok_or_else(|| SafeError::SecretNotFound {
162 key: key.to_string(),
163 })?;
164 let nonce = crypto::decode_b64(&entry.nonce)?;
165 let ciphertext = crypto::decode_b64(&entry.ciphertext)?;
166 let aad = StructureBinding::of_file(&self.file).aad(key, SecretSlot::Live);
169 let plaintext = crypto::decrypt_with_key_schedule_aad(
170 &self.key,
171 self.key_schedule,
172 KeyPurpose::SecretData,
173 self.cipher,
174 &nonce,
175 &ciphertext,
176 &aad,
177 )?;
178 let value = zeroizing_string_from_utf8(plaintext)?;
179 Ok(MobileVaultItem {
180 key: key.to_string(),
181 value,
182 metadata: metadata_for(key, entry),
183 })
184 }
185
186 pub fn generate_totp_code(&self, key: &str) -> SafeResult<MobileTotpCode> {
188 let item = self.get_item(key)?;
189 let code = totp::generate_code(&item.value)?;
190 let seconds_remaining = totp::seconds_remaining_for(&item.value)?;
191 Ok(MobileTotpCode {
192 code,
193 seconds_remaining,
194 })
195 }
196
197 fn open_with_key(file: VaultFile, key: VaultKey, kind: MobileVaultKind) -> SafeResult<Self> {
198 let cipher = crypto::parse_cipher_kind(&file.cipher)?;
199 let challenge_nonce = crypto::decode_b64(&file.vault_challenge.nonce)?;
200 let challenge_ciphertext = crypto::decode_b64(&file.vault_challenge.ciphertext)?;
201 let key_schedule = crypto::detect_key_schedule(
202 &key,
203 KeyPurpose::VaultChallenge,
204 cipher,
205 &challenge_nonce,
206 &challenge_ciphertext,
207 VAULT_CHALLENGE_PLAINTEXT,
208 )?;
209 Ok(Self {
210 kind,
211 file,
212 key,
213 cipher,
214 key_schedule,
215 })
216 }
217}
218
219#[derive(Debug, Clone, PartialEq, Eq)]
221pub enum MobileAuditKind {
222 VaultPull,
223 Unlock,
224 Reveal { ttl_secs: u64 },
225 Copy { ttl_secs: u64 },
226 TotpGet,
227 Sync,
228 RevocationSeen,
229 StalePolicy,
230}
231
232#[derive(Debug, Clone, PartialEq, Eq)]
234pub enum MobileAuditStatus {
235 Success,
236 Failure { summary: String },
237}
238
239pub fn build_mobile_audit_event(
242 profile: &str,
243 kind: MobileAuditKind,
244 key: Option<&str>,
245 status: MobileAuditStatus,
246) -> AuditEntry {
247 let operation = mobile_operation_name(&kind);
248 let mut entry = match status {
249 MobileAuditStatus::Success => AuditEntry::success(profile, operation, key),
250 MobileAuditStatus::Failure { summary } => {
251 AuditEntry::failure(profile, operation, key, &summary)
252 }
253 };
254 entry.context = match kind {
255 MobileAuditKind::Reveal { ttl_secs } => {
256 Some(AuditContext::from_reveal(AuditRevealContext { ttl_secs }))
257 }
258 MobileAuditKind::Copy { ttl_secs } => {
259 Some(AuditContext::from_clipboard(AuditClipboardContext {
260 ttl_secs,
261 reason: None,
262 excluded_from_history: None,
263 cleared_verified: None,
264 }))
265 }
266 _ => None,
267 };
268 entry
269}
270
271fn parse_vault_file(bytes: &[u8]) -> SafeResult<VaultFile> {
272 serde_json::from_slice(bytes).map_err(|err| SafeError::VaultCorrupted {
273 reason: format!("the vault file could not be parsed ({err}). It has not been modified."),
277 })
278}
279
280fn validate_password_kdf(file: &VaultFile) -> SafeResult<()> {
281 if file.kdf.algorithm != VAULT_KDF_ALGORITHM {
282 return Err(SafeError::InvalidVault {
283 reason: format!(
284 "unsupported KDF algorithm: '{}' (expected '{VAULT_KDF_ALGORITHM}')",
285 file.kdf.algorithm
286 ),
287 });
288 }
289 if file.kdf.m_cost < KDF_M_COST_MIN || file.kdf.m_cost > KDF_M_COST_MAX {
290 return Err(SafeError::InvalidVault {
291 reason: format!(
292 "KDF m_cost {} is outside allowed range [{KDF_M_COST_MIN}, {KDF_M_COST_MAX}]",
293 file.kdf.m_cost
294 ),
295 });
296 }
297 if file.kdf.t_cost < KDF_T_COST_MIN || file.kdf.t_cost > KDF_T_COST_MAX {
298 return Err(SafeError::InvalidVault {
299 reason: format!(
300 "KDF t_cost {} is outside allowed range [{KDF_T_COST_MIN}, {KDF_T_COST_MAX}]",
301 file.kdf.t_cost
302 ),
303 });
304 }
305 if file.kdf.p_cost < KDF_P_COST_MIN || file.kdf.p_cost > KDF_P_COST_MAX {
306 return Err(SafeError::InvalidVault {
307 reason: format!(
308 "KDF p_cost {} is outside allowed range [{KDF_P_COST_MIN}, {KDF_P_COST_MAX}]",
309 file.kdf.p_cost
310 ),
311 });
312 }
313 Ok(())
314}
315
316fn parse_age_identities(
317 identity_file: &str,
318) -> SafeResult<Vec<Box<dyn age::Identity + Send + Sync>>> {
319 age::IdentityFile::from_buffer(identity_file.as_bytes())
320 .map_err(|err| SafeError::Crypto {
321 context: format!("parse age identity: {err}"),
322 })?
323 .into_identities()
324 .map_err(|err| SafeError::Crypto {
325 context: format!("extract age identities: {err}"),
326 })
327}
328
329fn metadata_for(key: &str, entry: &SecretEntry) -> MobileItemMetadata {
330 MobileItemMetadata {
331 key: key.to_string(),
332 created_at: entry.created_at,
333 updated_at: entry.updated_at,
334 tags: entry.tags.clone(),
335 history_len: entry.history.len(),
336 item_kind: if entry
337 .tags
338 .get("type")
339 .is_some_and(|value| value.eq_ignore_ascii_case("totp"))
340 {
341 MobileItemKind::Totp
342 } else {
343 MobileItemKind::Secret
344 },
345 }
346}
347
348fn zeroizing_string_from_utf8(bytes: Vec<u8>) -> SafeResult<Zeroizing<String>> {
349 match String::from_utf8(bytes) {
350 Ok(value) => Ok(Zeroizing::new(value)),
351 Err(err) => {
352 let mut bytes = err.into_bytes();
353 bytes.zeroize();
354 Err(SafeError::InvalidVault {
355 reason: "secret is not valid UTF-8".into(),
356 })
357 }
358 }
359}
360
361fn mobile_operation_name(kind: &MobileAuditKind) -> &'static str {
362 match kind {
363 MobileAuditKind::VaultPull => "mobile.vault_pull",
364 MobileAuditKind::Unlock => "mobile.unlock",
365 MobileAuditKind::Reveal { .. } => "mobile.reveal",
366 MobileAuditKind::Copy { .. } => "mobile.copy",
367 MobileAuditKind::TotpGet => "mobile.totp_get",
368 MobileAuditKind::Sync => "mobile.sync",
369 MobileAuditKind::RevocationSeen => "mobile.revocation_seen",
370 MobileAuditKind::StalePolicy => "mobile.stale_policy",
371 }
372}
373
374#[cfg(test)]
375mod tests {
376 use std::collections::HashMap;
377
378 use chrono::Utc;
379 use tempfile::tempdir;
380 use tsafe_core::age_crypto;
381 use tsafe_core::crypto::{self, KeyPurpose, KeySchedule};
382 use tsafe_core::team;
383 use tsafe_core::vault::{SecretEntry, Vault};
384
385 use crate::{
386 build_mobile_audit_event, MobileAuditKind, MobileAuditStatus, MobileVault, MobileVaultKind,
387 };
388
389 #[test]
390 fn opens_password_vault_bytes_and_lists_metadata_without_values() {
391 let dir = tempdir().unwrap();
392 let path = dir.path().join("default.vault");
393 let mut vault = Vault::create(&path, b"mobile-passphrase").unwrap();
394 vault
395 .set(
396 "API_TOKEN",
397 "super-secret-value",
398 HashMap::from([("env".to_string(), "prod".to_string())]),
399 )
400 .unwrap();
401 vault
402 .set("TOTP_GITHUB", "JBSWY3DPEHPK3PXP", HashMap::new())
403 .unwrap();
404 let vault_bytes = serde_json::to_vec(vault.file()).unwrap();
405
406 let mobile =
407 MobileVault::open_password_vault_from_bytes(&vault_bytes, b"mobile-passphrase")
408 .unwrap();
409
410 assert_eq!(mobile.kind(), MobileVaultKind::Password);
411 let items = mobile.list_items();
412 assert_eq!(
413 items
414 .iter()
415 .map(|item| item.key.as_str())
416 .collect::<Vec<_>>(),
417 vec!["API_TOKEN", "TOTP_GITHUB"]
418 );
419 assert_eq!(items[0].tags.get("env").map(String::as_str), Some("prod"));
420 assert_eq!(items[0].history_len, 0);
421 let serialized = serde_json::to_string(&items).unwrap();
422 assert!(!serialized.contains("super-secret-value"));
423
424 let item = mobile.get_item("API_TOKEN").unwrap();
425 assert_eq!(item.key, "API_TOKEN");
426 assert_eq!(&*item.value, "super-secret-value");
427 }
428
429 #[test]
430 fn wrong_password_fails_closed() {
431 let dir = tempdir().unwrap();
432 let path = dir.path().join("default.vault");
433 let vault = Vault::create(&path, b"right-passphrase").unwrap();
434 let vault_bytes = serde_json::to_vec(vault.file()).unwrap();
435
436 let result = MobileVault::open_password_vault_from_bytes(&vault_bytes, b"wrong");
437
438 assert!(result.is_err());
439 }
440
441 #[test]
442 fn opens_team_vault_bytes_with_age_identity() {
443 let (identity, recipient) = age_crypto::generate_identity();
444 let (mut file, dek) = team::create_team_vault(&[recipient]).unwrap();
445 let now = Utc::now();
446 let (nonce, ciphertext) = crypto::encrypt_with_key_schedule_aad(
449 &dek,
450 KeySchedule::HkdfSha256V1,
451 KeyPurpose::SecretData,
452 crypto::default_vault_cipher(),
453 b"team-secret-value",
454 &tsafe_core::vault::secret_aad("TEAM_TOKEN", tsafe_core::vault::SecretSlot::Live),
455 )
456 .unwrap();
457 file.secrets.insert(
458 "TEAM_TOKEN".to_string(),
459 SecretEntry {
460 nonce: crypto::encode_b64(&nonce),
461 ciphertext: crypto::encode_b64(&ciphertext),
462 created_at: now,
463 updated_at: now,
464 tags: HashMap::from([("scope".to_string(), "team".to_string())]),
465 history: Vec::new(),
466 },
467 );
468 let vault_bytes = serde_json::to_vec(&file).unwrap();
469
470 let mobile = MobileVault::open_team_vault_from_bytes(&vault_bytes, &identity).unwrap();
471
472 assert_eq!(mobile.kind(), MobileVaultKind::Team);
473 assert_eq!(mobile.list_items()[0].key, "TEAM_TOKEN");
474 assert_eq!(
475 &*mobile.get_item("TEAM_TOKEN").unwrap().value,
476 "team-secret-value"
477 );
478 }
479
480 #[test]
481 fn totp_generation_honors_stored_otpauth_profile() {
482 let dir = tempdir().unwrap();
483 let path = dir.path().join("default.vault");
484 let mut vault = Vault::create(&path, b"mobile-passphrase").unwrap();
485 vault
486 .set(
487 "GITHUB_2FA",
488 "otpauth://totp/GitHub?secret=JBSWY3DPEHPK3PXP&issuer=GitHub&digits=8&period=60",
489 HashMap::from([("type".to_string(), "totp".to_string())]),
490 )
491 .unwrap();
492 let vault_bytes = serde_json::to_vec(vault.file()).unwrap();
493 let mobile =
494 MobileVault::open_password_vault_from_bytes(&vault_bytes, b"mobile-passphrase")
495 .unwrap();
496
497 let code = mobile.generate_totp_code("GITHUB_2FA").unwrap();
498
499 assert_eq!(code.code.len(), 8);
500 assert!(code.code.chars().all(|ch| ch.is_ascii_digit()));
501 assert!((1..=60).contains(&code.seconds_remaining));
502 }
503
504 #[test]
505 fn mobile_audit_event_is_redacted() {
506 let event = build_mobile_audit_event(
507 "mobile-default",
508 MobileAuditKind::Copy { ttl_secs: 30 },
509 Some("API_TOKEN"),
510 MobileAuditStatus::Success,
511 );
512
513 let serialized = serde_json::to_string(&event).unwrap();
514 assert!(serialized.contains("mobile.copy"));
515 assert!(serialized.contains("API_TOKEN"));
516 assert!(!serialized.contains("super-secret-value"));
517 }
518}