1use crate::error::{AppError, Result};
2use serde::{Deserialize, Serialize};
3use std::collections::HashMap;
4use std::path::PathBuf;
5use uuid::Uuid;
6
7const PROFILES_FILE: &str = "profiles.json";
8
9#[derive(Debug, Clone, Serialize, Deserialize)]
10#[serde(tag = "type")]
11pub enum CredentialType {
12 Environment,
14
15 SharedConfig { profile_name: Option<String> },
17
18 Manual {
20 access_key_id: String,
21 #[serde(default, skip_serializing)]
22 secret_access_key: String,
23 },
24
25 CustomEndpoint {
27 endpoint_url: String,
28 access_key_id: String,
29 #[serde(default, skip_serializing)]
30 secret_access_key: String,
31 },
32}
33
34#[derive(Debug, Clone, Serialize, Deserialize)]
35pub struct Profile {
36 #[serde(default)]
37 pub id: String,
38 #[serde(default)]
39 pub secret_ref: Option<String>,
40 pub name: String,
41 pub credential_type: CredentialType,
42 pub region: Option<String>,
43 pub is_default: bool,
44 #[serde(default)]
45 pub created_at: Option<chrono::DateTime<chrono::Utc>>,
46 #[serde(default)]
47 pub updated_at: Option<chrono::DateTime<chrono::Utc>>,
48}
49
50impl Profile {
51 pub fn cache_identity(&self) -> String {
52 format!(
53 "{}:{}",
54 self.id,
55 self.updated_at
56 .map(|date| date.to_rfc3339())
57 .unwrap_or_default()
58 )
59 }
60
61 pub fn new(name: String, credential_type: CredentialType, region: Option<String>) -> Self {
62 let now = chrono::Utc::now();
63 Self {
64 id: Uuid::new_v4().to_string(),
65 name,
66 secret_ref: None,
67 credential_type,
68 region,
69 is_default: false,
70 created_at: Some(now),
71 updated_at: Some(now),
72 }
73 }
74}
75
76#[derive(Debug, Clone, Serialize, Deserialize, Default)]
77#[serde(default)]
78struct ProfilesData {
79 profiles: HashMap<String, Profile>,
80 active_profile_id: Option<String>,
81 pending_secret_deletions: Vec<String>,
82}
83
84pub struct ProfileManager {
85 config_dir: PathBuf,
86 data: ProfilesData,
87 keychain: super::KeychainStorage,
88}
89
90impl ProfileManager {
91 pub fn new(config_dir: PathBuf, force_secret_fallback: bool) -> Result<Self> {
92 let profiles_path = config_dir.join(PROFILES_FILE);
93 log::info!(
94 "Initializing ProfileManager. Storage path: {:?}",
95 profiles_path
96 );
97
98 let data = if profiles_path.exists() {
99 log::info!("Found existing profiles file.");
100 let content = std::fs::read_to_string(&profiles_path)?;
101 match Self::load_profiles_data(&content) {
102 Ok(d) => {
103 log::info!("Successfully loaded profiles data.");
104 d
105 }
106 Err(e) => {
107 use std::io::Write;
108 let backup_path =
109 config_dir.join(format!("profiles.invalid-{}.json", Uuid::new_v4()));
110 let mut options = std::fs::OpenOptions::new();
111 options.write(true).create_new(true);
112 #[cfg(unix)]
113 {
114 use std::os::unix::fs::OpenOptionsExt;
115 options.mode(0o600);
116 }
117 let mut backup = options.open(&backup_path)?;
118 backup.write_all(content.as_bytes())?;
119 backup.sync_all()?;
120 log::error!(
121 "Failed to parse profiles.json: {}. Original saved to {:?}.",
122 e,
123 backup_path
124 );
125 ProfilesData::default()
126 }
127 }
128 } else {
129 log::info!("No profiles file found. Creating new.");
130 ProfilesData::default()
131 };
132
133 let keychain = super::KeychainStorage::new("brows3", &config_dir, force_secret_fallback);
134
135 let mut manager = Self {
136 config_dir,
137 data,
138 keychain,
139 };
140 manager.cleanup_pending_secrets();
141 Ok(manager)
142 }
143
144 fn load_profiles_data(content: &str) -> std::result::Result<ProfilesData, serde_json::Error> {
145 let value: serde_json::Value = serde_json::from_str(content)?;
146 if value.is_array() {
147 let profiles: Vec<Profile> = serde_json::from_value(value)?;
148 return Ok(Self::normalize_profiles_data(ProfilesData {
149 profiles: profiles
150 .into_iter()
151 .map(|profile| (profile.id.clone(), profile))
152 .collect(),
153 active_profile_id: None,
154 pending_secret_deletions: Vec::new(),
155 }));
156 }
157
158 if value.get("profiles").is_some() || value.get("active_profile_id").is_some() {
159 if let Ok(data) = serde_json::from_value::<ProfilesData>(value.clone()) {
160 return Ok(Self::normalize_profiles_data(data));
161 }
162 }
163
164 let profiles = serde_json::from_value::<HashMap<String, Profile>>(value)?;
165 Ok(Self::normalize_profiles_data(ProfilesData {
166 profiles,
167 active_profile_id: None,
168 pending_secret_deletions: Vec::new(),
169 }))
170 }
171
172 fn normalize_profiles_data(mut data: ProfilesData) -> ProfilesData {
173 let mut normalized_profiles = HashMap::with_capacity(data.profiles.len());
174 let mut first_profile_id: Option<String> = None;
175 let mut default_profile_id: Option<String> = None;
176
177 for (key, mut profile) in data.profiles.drain() {
178 if profile.id.is_empty() {
179 profile.id = if !key.is_empty() {
180 key
181 } else {
182 Uuid::new_v4().to_string()
183 };
184 }
185
186 if first_profile_id.is_none() {
187 first_profile_id = Some(profile.id.clone());
188 }
189 if profile.is_default && default_profile_id.is_none() {
190 default_profile_id = Some(profile.id.clone());
191 }
192
193 normalized_profiles.insert(profile.id.clone(), profile);
194 }
195
196 let mut active_profile_id = data
197 .active_profile_id
198 .filter(|id| normalized_profiles.contains_key(id));
199
200 if active_profile_id.is_none() {
201 active_profile_id = default_profile_id.or(first_profile_id.clone());
202 }
203
204 for profile in normalized_profiles.values_mut() {
205 profile.is_default = active_profile_id.as_ref() == Some(&profile.id);
206 }
207
208 ProfilesData {
209 profiles: normalized_profiles,
210 active_profile_id,
211 pending_secret_deletions: data.pending_secret_deletions,
212 }
213 }
214
215 fn sync_default_flags(&mut self) {
216 let active_profile_id = self.data.active_profile_id.clone();
217 for profile in self.data.profiles.values_mut() {
218 profile.is_default = active_profile_id.as_ref() == Some(&profile.id);
219 }
220 }
221
222 fn commit(&mut self, previous: ProfilesData) -> Result<()> {
223 if let Err(error) = self.save() {
224 self.data = previous;
225 return Err(error);
226 }
227 Ok(())
228 }
229
230 fn save(&self) -> Result<()> {
231 let profiles_path = self.config_dir.join(PROFILES_FILE);
232 log::info!("Saving profiles atomically to {:?}", profiles_path);
233 let content = serde_json::to_string_pretty(&self.data)?;
234 super::write_private_file(&profiles_path, content.as_bytes())
235 }
236
237 pub async fn list_profiles(&self) -> Result<Vec<Profile>> {
238 let mut profiles: Vec<Profile> = self.data.profiles.values().cloned().collect();
239 profiles.sort_by(|a, b| a.name.cmp(&b.name));
240 Ok(profiles)
241 }
242
243 pub async fn get_profile(&self, id: &str) -> Result<Profile> {
244 let profile = self
245 .data
246 .profiles
247 .get(id)
248 .cloned()
249 .ok_or_else(|| AppError::ProfileNotFound(id.to_string()))?;
250 Ok(self.hydrate_profile(profile))
251 }
252
253 pub async fn add_profile(&mut self, mut profile: Profile) -> Result<Profile> {
254 if profile.id.is_empty() {
256 profile.id = Uuid::new_v4().to_string();
257 }
258 if self.data.profiles.values().any(|p| p.name == profile.name) {
260 return Err(AppError::ProfileExists(profile.name.clone()));
261 }
262
263 if self.data.profiles.contains_key(&profile.id) {
264 return Err(AppError::ProfileExists(profile.id));
265 }
266 let previous = self.data.clone();
267 profile.secret_ref = Some(Uuid::new_v4().to_string());
268 self.store_secret(&profile)?;
269
270 let now = chrono::Utc::now();
272 profile.created_at = Some(now);
273 profile.updated_at = Some(now);
274
275 if self.data.profiles.is_empty() {
277 profile.is_default = true;
278 self.data.active_profile_id = Some(profile.id.clone());
279 }
280
281 self.data
282 .profiles
283 .insert(profile.id.clone(), profile.clone());
284 self.sync_default_flags();
285 if let Err(error) = self.commit(previous) {
286 self.remove_secret(&profile);
287 return Err(error);
288 }
289
290 Ok(self.hydrate_profile(
291 self.data
292 .profiles
293 .get(&profile.id)
294 .cloned()
295 .ok_or_else(|| AppError::ProfileNotFound(profile.id.clone()))?,
296 ))
297 }
298
299 pub async fn update_profile(&mut self, id: &str, mut profile: Profile) -> Result<Profile> {
300 let existing_profile = self
301 .data
302 .profiles
303 .get(id)
304 .cloned()
305 .ok_or_else(|| AppError::ProfileNotFound(id.to_string()))?;
306 let hydrated_existing_profile = self.hydrate_profile(existing_profile.clone());
307
308 if self
309 .data
310 .profiles
311 .values()
312 .any(|p| p.id != id && p.name == profile.name)
313 {
314 return Err(AppError::ProfileExists(profile.name.clone()));
315 }
316
317 profile.id = id.to_string();
318 profile.created_at = existing_profile.created_at;
319 profile.is_default = self.data.active_profile_id.as_deref() == Some(id);
320 profile.updated_at = Some(chrono::Utc::now());
321
322 match (
324 &hydrated_existing_profile.credential_type,
325 &mut profile.credential_type,
326 ) {
327 (
328 CredentialType::Manual {
329 secret_access_key: old_secret,
330 ..
331 },
332 CredentialType::Manual {
333 secret_access_key, ..
334 },
335 ) if secret_access_key.is_empty() => {
336 *secret_access_key = old_secret.clone();
337 }
338 (
339 CredentialType::CustomEndpoint {
340 secret_access_key: old_secret,
341 ..
342 },
343 CredentialType::CustomEndpoint {
344 secret_access_key, ..
345 },
346 ) if secret_access_key.is_empty() => {
347 *secret_access_key = old_secret.clone();
348 }
349 (
350 CredentialType::Manual {
351 secret_access_key: old_secret,
352 ..
353 },
354 CredentialType::CustomEndpoint {
355 secret_access_key, ..
356 },
357 ) if secret_access_key.is_empty() && !old_secret.is_empty() => {
358 *secret_access_key = old_secret.clone();
359 }
360 (
361 CredentialType::CustomEndpoint {
362 secret_access_key: old_secret,
363 ..
364 },
365 CredentialType::Manual {
366 secret_access_key, ..
367 },
368 ) if secret_access_key.is_empty() && !old_secret.is_empty() => {
369 *secret_access_key = old_secret.clone();
370 }
371 _ => {}
372 }
373
374 let previous = self.data.clone();
375 profile.secret_ref = Some(Uuid::new_v4().to_string());
376 self.store_secret(&profile)?;
377
378 self.queue_secret_cleanup(&existing_profile);
379 self.data.profiles.insert(id.to_string(), profile.clone());
380 self.sync_default_flags();
381 if let Err(error) = self.commit(previous) {
382 self.remove_secret(&profile);
383 return Err(error);
384 }
385
386 self.cleanup_pending_secrets();
387 Ok(self.hydrate_profile(profile))
388 }
389
390 pub async fn delete_profile(&mut self, id: &str) -> Result<()> {
391 let previous = self.data.clone();
392 let profile = self
393 .data
394 .profiles
395 .remove(id)
396 .ok_or_else(|| AppError::ProfileNotFound(id.to_string()))?;
397
398 self.queue_secret_cleanup(&profile);
399 if self.data.active_profile_id.as_deref() == Some(id) {
401 self.data.active_profile_id = self.data.profiles.keys().next().cloned();
402 }
403
404 self.sync_default_flags();
405
406 self.commit(previous)?;
407 self.cleanup_pending_secrets();
408 Ok(())
409 }
410
411 pub async fn set_active_profile(&mut self, id: &str) -> Result<()> {
412 if !self.data.profiles.contains_key(id) {
413 return Err(AppError::ProfileNotFound(id.to_string()));
414 }
415
416 let previous = self.data.clone();
417 self.data.active_profile_id = Some(id.to_string());
418 self.sync_default_flags();
419 self.commit(previous)?;
420 Ok(())
421 }
422
423 pub async fn get_active_profile(&self) -> Result<Option<Profile>> {
424 match &self.data.active_profile_id {
425 Some(id) => {
426 let profile = self.data.profiles.get(id).cloned();
427 Ok(profile.map(|p| self.hydrate_profile(p)))
428 }
429 None => Ok(None),
430 }
431 }
432
433 pub fn hydrate_profile(&self, mut profile: Profile) -> Profile {
435 let stored = self.data.profiles.get(&profile.id).unwrap_or(&profile);
436 if let Some(secret) = self.load_secret(stored).ok().flatten() {
437 match &mut profile.credential_type {
438 CredentialType::Manual {
439 secret_access_key, ..
440 } => {
441 *secret_access_key = secret;
442 }
443 CredentialType::CustomEndpoint {
444 secret_access_key, ..
445 } => {
446 *secret_access_key = secret;
447 }
448 _ => {}
449 }
450 }
451 profile
452 }
453
454 fn store_secret(&self, profile: &Profile) -> Result<()> {
455 match &profile.credential_type {
456 CredentialType::Manual {
457 secret_access_key, ..
458 }
459 | CredentialType::CustomEndpoint {
460 secret_access_key, ..
461 } => {
462 if secret_access_key.is_empty() {
463 return Err(AppError::InvalidCredentials(
464 "Enter a secret access key; the stored secret could not be read.".into(),
465 ));
466 }
467 self.keychain.store(
468 profile.secret_ref.as_deref().unwrap_or(&profile.id),
469 secret_access_key,
470 )?;
471 }
472 _ => {}
473 }
474 Ok(())
475 }
476
477 fn queue_secret_cleanup(&mut self, profile: &Profile) {
478 if matches!(
479 profile.credential_type,
480 CredentialType::Manual { .. } | CredentialType::CustomEndpoint { .. }
481 ) {
482 self.data.pending_secret_deletions.push(
483 profile
484 .secret_ref
485 .clone()
486 .unwrap_or_else(|| profile.id.clone()),
487 );
488 }
489 }
490
491 fn cleanup_pending_secrets(&mut self) {
492 if self.data.pending_secret_deletions.is_empty() {
493 return;
494 }
495 self.data.pending_secret_deletions.retain(|key| {
496 if let Err(error) = self.keychain.delete(key) {
497 log::error!("Secret cleanup pending; will retry on next startup: {error}");
498 true
499 } else {
500 false
501 }
502 });
503 if let Err(error) = self.save() {
504 log::warn!("Could not persist secret cleanup progress: {error}");
505 }
506 }
507
508 fn remove_secret(&self, profile: &Profile) {
509 match &profile.credential_type {
510 CredentialType::Manual { .. } | CredentialType::CustomEndpoint { .. } => {
511 if let Err(error) = self
512 .keychain
513 .delete(profile.secret_ref.as_deref().unwrap_or(&profile.id))
514 {
515 log::error!("Profile secret cleanup failed: {error}");
516 }
517 }
518 _ => {}
519 }
520 }
521
522 pub fn load_secret(&self, profile: &Profile) -> Result<Option<String>> {
523 match &profile.credential_type {
524 CredentialType::Manual { .. } | CredentialType::CustomEndpoint { .. } => Ok(self
525 .keychain
526 .get(profile.secret_ref.as_deref().unwrap_or(&profile.id))
527 .ok()),
528 _ => Ok(None),
529 }
530 }
531}
532
533#[cfg(test)]
534mod tests {
535 use super::{CredentialType, Profile, ProfileManager};
536 use std::collections::HashMap;
537
538 #[tokio::test]
539 async fn failed_metadata_commit_preserves_selection_profile_and_secret() {
540 let dir = tempfile::tempdir().unwrap();
541 let mut manager = ProfileManager::new(dir.path().to_path_buf(), true).unwrap();
542 let first = manager
543 .add_profile(Profile::new(
544 "first".into(),
545 CredentialType::Manual {
546 access_key_id: "key".into(),
547 secret_access_key: "original".into(),
548 },
549 None,
550 ))
551 .await
552 .unwrap();
553 let second = manager
554 .add_profile(Profile::new(
555 "second".into(),
556 CredentialType::Environment,
557 None,
558 ))
559 .await
560 .unwrap();
561 std::fs::rename(
563 dir.path().join("profiles.json"),
564 dir.path().join("saved.json"),
565 )
566 .unwrap();
567 std::fs::create_dir(dir.path().join("profiles.json")).unwrap();
568 assert!(manager.set_active_profile(&second.id).await.is_err());
569 assert_eq!(
570 manager.get_active_profile().await.unwrap().unwrap().id,
571 first.id
572 );
573 let mut edited = first.clone();
574 edited.name = "changed".into();
575 edited.credential_type = CredentialType::Manual {
576 access_key_id: "new-key".into(),
577 secret_access_key: "new-secret".into(),
578 };
579 assert!(manager.update_profile(&first.id, edited).await.is_err());
580 assert_eq!(manager.get_profile(&first.id).await.unwrap().name, "first");
581 assert_eq!(
582 manager.load_secret(&first).unwrap().as_deref(),
583 Some("original")
584 );
585 assert!(manager.delete_profile(&first.id).await.is_err());
586 assert!(manager.get_profile(&first.id).await.is_ok());
587 assert_eq!(
588 manager.load_secret(&first).unwrap().as_deref(),
589 Some("original")
590 );
591 assert!(manager
592 .add_profile(Profile::new(
593 "third".into(),
594 CredentialType::Environment,
595 None
596 ))
597 .await
598 .is_err());
599 assert_eq!(manager.list_profiles().await.unwrap().len(), 2);
600 }
601 use std::path::PathBuf;
602
603 fn temp_config_dir(name: &str) -> PathBuf {
604 let dir =
605 std::env::temp_dir().join(format!("brows3-test-{}-{}", name, uuid::Uuid::new_v4()));
606 std::fs::create_dir_all(&dir).expect("temp config dir should be created");
607 dir
608 }
609
610 #[test]
611 fn legacy_profile_maps_keep_their_entries_and_ids() {
612 let json = r#"{"legacy-id":{"name":"Legacy","credential_type":{"type":"Environment"},"region":"us-east-1","is_default":true}}"#;
613 let data = ProfileManager::load_profiles_data(json).unwrap();
614 assert_eq!(data.profiles.len(), 1);
615 assert_eq!(data.profiles["legacy-id"].id, "legacy-id");
616 assert_eq!(data.active_profile_id.as_deref(), Some("legacy-id"));
617 assert!(ProfileManager::load_profiles_data(r#"{"unexpected":42}"#).is_err());
618 }
619
620 #[tokio::test]
621 async fn malformed_profiles_are_backed_up_before_new_profiles_are_saved() {
622 let directory = temp_config_dir("invalid-profile-backup");
623 let original = "{incomplete";
624 std::fs::write(directory.join(super::PROFILES_FILE), original).unwrap();
625 let mut manager = ProfileManager::new(directory.clone(), true).unwrap();
626 manager
627 .add_profile(Profile::new(
628 "New".into(),
629 CredentialType::Environment,
630 None,
631 ))
632 .await
633 .unwrap();
634 let backup = std::fs::read_dir(&directory)
635 .unwrap()
636 .filter_map(|entry| entry.ok())
637 .find(|entry| {
638 entry
639 .file_name()
640 .to_string_lossy()
641 .starts_with("profiles.invalid-")
642 })
643 .unwrap();
644 assert_eq!(std::fs::read_to_string(backup.path()).unwrap(), original);
645 std::fs::remove_dir_all(directory).unwrap();
646 }
647
648 #[test]
649 fn manual_profile_deserializes_without_secret_in_json() {
650 let json = r#"{
651 "id": "manual-1",
652 "name": "Manual",
653 "credential_type": {
654 "type": "Manual",
655 "access_key_id": "AKIA123"
656 },
657 "region": "us-east-1",
658 "is_default": true
659 }"#;
660
661 let profile: Profile = serde_json::from_str(json).expect("profile should deserialize");
662 match profile.credential_type {
663 CredentialType::Manual {
664 access_key_id,
665 secret_access_key,
666 } => {
667 assert_eq!(access_key_id, "AKIA123");
668 assert!(secret_access_key.is_empty());
669 }
670 _ => panic!("expected manual credentials"),
671 }
672 }
673
674 #[test]
675 fn custom_endpoint_profile_deserializes_without_secret_in_json() {
676 let json = r#"{
677 "id": "custom-1",
678 "name": "MinIO",
679 "credential_type": {
680 "type": "CustomEndpoint",
681 "endpoint_url": "http://localhost:9000",
682 "access_key_id": "minio"
683 },
684 "region": "us-east-1",
685 "is_default": false
686 }"#;
687
688 let profile: Profile = serde_json::from_str(json).expect("profile should deserialize");
689 match profile.credential_type {
690 CredentialType::CustomEndpoint {
691 endpoint_url,
692 access_key_id,
693 secret_access_key,
694 } => {
695 assert_eq!(endpoint_url, "http://localhost:9000");
696 assert_eq!(access_key_id, "minio");
697 assert!(secret_access_key.is_empty());
698 }
699 _ => panic!("expected custom endpoint credentials"),
700 }
701 }
702
703 #[test]
704 fn profiles_data_deserializes_without_active_profile_id() {
705 let json = r#"{
706 "profiles": {
707 "profile-1": {
708 "id": "profile-1",
709 "name": "MinIO",
710 "credential_type": {
711 "type": "CustomEndpoint",
712 "endpoint_url": "http://localhost:9000",
713 "access_key_id": "minio"
714 },
715 "region": "us-east-1",
716 "is_default": true
717 }
718 }
719 }"#;
720
721 let data =
722 ProfileManager::load_profiles_data(json).expect("profiles data should deserialize");
723 assert_eq!(data.active_profile_id.as_deref(), Some("profile-1"));
724 assert_eq!(data.profiles.len(), 1);
725 }
726
727 #[test]
728 fn profiles_data_deserializes_from_legacy_array() {
729 let json = r#"[
730 {
731 "id": "profile-1",
732 "name": "Legacy",
733 "credential_type": {
734 "type": "Manual",
735 "access_key_id": "AKIA123"
736 },
737 "region": "us-east-1",
738 "is_default": false
739 }
740 ]"#;
741
742 let data =
743 ProfileManager::load_profiles_data(json).expect("legacy array should deserialize");
744 assert_eq!(data.active_profile_id.as_deref(), Some("profile-1"));
745 assert!(data.profiles.contains_key("profile-1"));
746 }
747
748 #[test]
749 fn normalize_profiles_data_repairs_missing_ids_and_default_flag() {
750 let mut profiles = HashMap::new();
751 profiles.insert(
752 "legacy-key".to_string(),
753 Profile {
754 secret_ref: None,
755 id: String::new(),
756 name: "Legacy".to_string(),
757 credential_type: CredentialType::Environment,
758 region: None,
759 is_default: false,
760 created_at: None,
761 updated_at: None,
762 },
763 );
764
765 let data = ProfileManager::normalize_profiles_data(super::ProfilesData {
766 profiles,
767 active_profile_id: None,
768 pending_secret_deletions: Vec::new(),
769 });
770
771 assert_eq!(data.profiles.len(), 1);
772 assert_eq!(data.active_profile_id.as_deref(), Some("legacy-key"));
773 let profile = data
774 .profiles
775 .get("legacy-key")
776 .expect("profile should exist");
777 assert_eq!(profile.id, "legacy-key");
778 assert!(profile.is_default);
779 }
780
781 #[tokio::test]
782 async fn update_preserves_secret_when_switching_manual_to_custom_endpoint() {
783 let config_dir = temp_config_dir("manual-to-custom");
784 let mut manager = ProfileManager::new(config_dir, true).expect("manager should initialize");
785
786 let created = manager
787 .add_profile(Profile::new(
788 "Manual".to_string(),
789 CredentialType::Manual {
790 access_key_id: "access".to_string(),
791 secret_access_key: "secret".to_string(),
792 },
793 Some("us-east-1".to_string()),
794 ))
795 .await
796 .expect("profile should be added");
797
798 let updated = manager
799 .update_profile(
800 &created.id,
801 Profile::new(
802 "Custom".to_string(),
803 CredentialType::CustomEndpoint {
804 endpoint_url: "https://example.com".to_string(),
805 access_key_id: "access".to_string(),
806 secret_access_key: String::new(),
807 },
808 Some("auto".to_string()),
809 ),
810 )
811 .await
812 .expect("profile should be updated");
813
814 match updated.credential_type {
815 CredentialType::CustomEndpoint {
816 secret_access_key, ..
817 } => assert_eq!(secret_access_key, "secret"),
818 _ => panic!("expected custom endpoint credentials"),
819 }
820 }
821
822 #[tokio::test]
823 async fn update_preserves_secret_when_switching_custom_endpoint_to_manual() {
824 let config_dir = temp_config_dir("custom-to-manual");
825 let mut manager = ProfileManager::new(config_dir, true).expect("manager should initialize");
826
827 let created = manager
828 .add_profile(Profile::new(
829 "Custom".to_string(),
830 CredentialType::CustomEndpoint {
831 endpoint_url: "https://example.com".to_string(),
832 access_key_id: "access".to_string(),
833 secret_access_key: "secret".to_string(),
834 },
835 Some("auto".to_string()),
836 ))
837 .await
838 .expect("profile should be added");
839
840 let updated = manager
841 .update_profile(
842 &created.id,
843 Profile::new(
844 "Manual".to_string(),
845 CredentialType::Manual {
846 access_key_id: "access".to_string(),
847 secret_access_key: String::new(),
848 },
849 Some("us-east-1".to_string()),
850 ),
851 )
852 .await
853 .expect("profile should be updated");
854
855 match updated.credential_type {
856 CredentialType::Manual {
857 secret_access_key, ..
858 } => assert_eq!(secret_access_key, "secret"),
859 _ => panic!("expected manual credentials"),
860 }
861 }
862
863 #[tokio::test]
864 async fn update_removes_secret_when_leaving_keychain_backed_credentials() {
865 let config_dir = temp_config_dir("leave-keychain");
866 let mut manager = ProfileManager::new(config_dir, true).expect("manager should initialize");
867
868 let created = manager
869 .add_profile(Profile::new(
870 "Manual".to_string(),
871 CredentialType::Manual {
872 access_key_id: "access".to_string(),
873 secret_access_key: "secret".to_string(),
874 },
875 Some("us-east-1".to_string()),
876 ))
877 .await
878 .expect("profile should be added");
879
880 manager
881 .update_profile(
882 &created.id,
883 Profile::new(
884 "Shared".to_string(),
885 CredentialType::SharedConfig {
886 profile_name: Some("default".to_string()),
887 },
888 Some("us-east-1".to_string()),
889 ),
890 )
891 .await
892 .expect("profile should be updated");
893
894 let manual_again = manager
895 .update_profile(
896 &created.id,
897 Profile::new(
898 "Manual Again".to_string(),
899 CredentialType::Manual {
900 access_key_id: "access".to_string(),
901 secret_access_key: String::new(),
902 },
903 Some("us-east-1".to_string()),
904 ),
905 )
906 .await
907 .expect_err("a removed secret must not be reused");
908
909 assert!(manual_again
910 .to_string()
911 .contains("Enter a secret access key"));
912 assert!(manager.load_secret(&created).unwrap().is_none());
913 }
914}