Skip to main content

brows3_lib/commands/
profiles.rs

1use crate::credentials::{Profile, ProfileManager};
2use aws_credential_types::provider::ProvideCredentials;
3use serde::{Deserialize, Serialize};
4use std::collections::HashMap;
5use std::path::PathBuf;
6use std::sync::Arc;
7use std::time::Duration;
8use tauri::State;
9use tokio::sync::RwLock;
10
11pub type ProfileState = Arc<RwLock<ProfileManager>>;
12
13#[derive(Debug, Serialize, Deserialize)]
14pub struct TestConnectionResult {
15    pub success: bool,
16    pub message: String,
17    pub region: Option<String>,
18    pub bucket_count: Option<usize>,
19}
20
21#[tauri::command]
22pub async fn list_profiles(state: State<'_, ProfileState>) -> Result<Vec<Profile>, String> {
23    let manager = state.read().await;
24    manager.list_profiles().await.map_err(|e| e.to_string())
25}
26
27#[tauri::command]
28pub async fn get_profile(id: String, state: State<'_, ProfileState>) -> Result<Profile, String> {
29    let manager = state.read().await;
30    manager.get_profile(&id).await.map_err(|e| e.to_string())
31}
32
33#[tauri::command]
34pub async fn add_profile(
35    profile: Profile,
36    state: State<'_, ProfileState>,
37) -> Result<Profile, String> {
38    let mut manager = state.write().await;
39    manager
40        .add_profile(profile)
41        .await
42        .map_err(|e| e.to_string())
43}
44
45#[tauri::command]
46pub async fn update_profile(
47    id: String,
48    profile: Profile,
49    state: State<'_, ProfileState>,
50) -> Result<Profile, String> {
51    let mut manager = state.write().await;
52    manager
53        .update_profile(&id, profile)
54        .await
55        .map_err(|e| e.to_string())
56}
57
58#[tauri::command]
59pub async fn delete_profile(id: String, state: State<'_, ProfileState>) -> Result<(), String> {
60    let mut manager = state.write().await;
61    manager.delete_profile(&id).await.map_err(|e| e.to_string())
62}
63
64#[tauri::command]
65pub async fn set_active_profile(id: String, state: State<'_, ProfileState>) -> Result<(), String> {
66    let mut manager = state.write().await;
67    manager
68        .set_active_profile(&id)
69        .await
70        .map_err(|e| e.to_string())
71}
72
73#[tauri::command]
74pub async fn get_active_profile(state: State<'_, ProfileState>) -> Result<Option<Profile>, String> {
75    let manager = state.read().await;
76    manager
77        .get_active_profile()
78        .await
79        .map_err(|e| e.to_string())
80}
81
82#[tauri::command]
83pub async fn test_connection(
84    mut profile: Profile,
85    state: State<'_, ProfileState>,
86) -> Result<TestConnectionResult, String> {
87    use aws_sdk_s3::error::ProvideErrorMetadata;
88
89    // Hydrate profile secrets from keychain if they are empty
90    {
91        let manager = state.read().await;
92        let needs_hydration = match &profile.credential_type {
93            crate::credentials::CredentialType::Manual {
94                secret_access_key, ..
95            } => secret_access_key.is_empty(),
96            crate::credentials::CredentialType::CustomEndpoint {
97                secret_access_key, ..
98            } => secret_access_key.is_empty(),
99            _ => false,
100        };
101
102        if needs_hydration && !profile.id.is_empty() {
103            profile = manager.hydrate_profile(profile);
104        }
105    }
106
107    let sdk_config = crate::s3::client::load_sdk_config(&profile, None).await;
108
109    if let Some(provider) = sdk_config.credentials_provider() {
110        if let Err(err) = provider.provide_credentials().await {
111            let message = match &profile.credential_type {
112                crate::credentials::CredentialType::SharedConfig { profile_name } => {
113                    let name = profile_name.as_deref().unwrap_or("default");
114                    format!(
115                        "Could not load credentials for AWS profile '{name}': {err}. If this is an IAM Identity Center (SSO) profile, choose Sign in with AWS SSO or run `aws sso login --profile {name}`, then retry."
116                    )
117                }
118                _ => format!("Could not load AWS credentials: {err}"),
119            };
120
121            return Ok(TestConnectionResult {
122                success: false,
123                message,
124                region: None,
125                bucket_count: None,
126            });
127        }
128    }
129
130    let client = crate::s3::client::client_from_sdk_config(&sdk_config, &profile);
131
132    // Test connection by listing buckets
133    match client.list_buckets().send().await {
134        Ok(response) => {
135            let bucket_count = response.buckets().len();
136            Ok(TestConnectionResult {
137                success: true,
138                message: format!("Connected successfully! Found {} bucket(s)", bucket_count),
139                region: Some(
140                    profile
141                        .region
142                        .clone()
143                        .unwrap_or_else(|| "us-east-1".to_string()),
144                ),
145                bucket_count: Some(bucket_count),
146            })
147        }
148        Err(e) => {
149            let error_string = e.to_string();
150
151            // Check for dispatch failure - common with S3-compatible providers
152            // when the endpoint URL is malformed or unreachable
153            if error_string.contains("dispatch failure") {
154                return Ok(TestConnectionResult {
155                    success: false,
156                    message: "Connection failed: Could not reach the endpoint. Please verify the endpoint URL is correct (e.g., https://us-east-1.linodeobjects.com) and that your network can reach it.".to_string(),
157                    region: None,
158                    bucket_count: None,
159                });
160            }
161
162            let s3_err = e.as_service_error();
163            let code = s3_err.and_then(|s| s.code()).unwrap_or("Unknown");
164            let message = s3_err.and_then(|s| s.message()).unwrap_or("No message");
165
166            // If it's an AccessDenied, it means the CREDENTIALS are correct, but the user
167            // lacks permission to list all buckets. We can still consider this "connected".
168            if code == "AccessDenied" || code == "403" {
169                return Ok(TestConnectionResult {
170                    success: true,
171                    message: "Connected! (Note: You are authenticated, but lack permission to list all buckets. You may need to enter bucket names manually or use a direct link.)".to_string(),
172                    region: Some(profile.region.clone().unwrap_or_else(|| "us-east-1".to_string())),
173                    bucket_count: Some(0),
174                });
175            }
176
177            Ok(TestConnectionResult {
178                success: false,
179                message: format!("Connection failed: {}: {}", code, message),
180                region: None,
181                bucket_count: None,
182            })
183        }
184    }
185}
186
187#[derive(Debug, Serialize, Deserialize, Clone)]
188pub struct DiscoveredProfile {
189    pub name: String,
190    pub region: Option<String>,
191    pub is_sso: bool,
192}
193
194#[derive(Debug, Clone, Copy)]
195enum ProfileFileKind {
196    Credentials,
197    Config,
198}
199
200#[derive(Debug, Default)]
201struct LocalProfileMetadata {
202    region: Option<String>,
203    is_sso: bool,
204}
205
206fn profile_name_from_section(section: &str, kind: ProfileFileKind) -> Option<String> {
207    let section = section.trim();
208    if section.is_empty() {
209        return None;
210    }
211
212    match kind {
213        ProfileFileKind::Credentials => Some(section.to_string()),
214        ProfileFileKind::Config => {
215            if section == "default" {
216                Some(section.to_string())
217            } else if let Some(name) = section.strip_prefix("profile ") {
218                let name = name.trim();
219                (!name.is_empty()).then(|| name.to_string())
220            } else {
221                // Sections such as [sso-session name] and [services name]
222                // configure profiles but are not themselves selectable profiles.
223                None
224            }
225        }
226    }
227}
228
229fn parse_profile_file(
230    content: &str,
231    kind: ProfileFileKind,
232    profiles: &mut HashMap<String, LocalProfileMetadata>,
233) {
234    let mut current_profile: Option<String> = None;
235
236    for raw_line in content.lines() {
237        let line = raw_line.trim();
238        if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
239            continue;
240        }
241
242        if let Some(section) = line
243            .strip_prefix('[')
244            .and_then(|value| value.split_once(']'))
245            .map(|(section, _)| section)
246        {
247            current_profile = profile_name_from_section(section, kind);
248            if let Some(name) = &current_profile {
249                profiles.entry(name.clone()).or_default();
250            }
251            continue;
252        }
253
254        let Some(profile_name) = &current_profile else {
255            continue;
256        };
257        let Some((key, value)) = line.split_once('=') else {
258            continue;
259        };
260        let key = key.trim().to_ascii_lowercase();
261        let value = value.trim();
262        let metadata = profiles.entry(profile_name.clone()).or_default();
263
264        match key.as_str() {
265            "region" if !value.is_empty() => metadata.region = Some(value.to_string()),
266            "sso_session" | "sso_start_url" if !value.is_empty() => metadata.is_sso = true,
267            _ => {}
268        }
269    }
270}
271
272fn local_profile_files() -> Result<Vec<(PathBuf, ProfileFileKind)>, String> {
273    let home = dirs::home_dir().ok_or("Could not find home directory")?;
274    let credentials = std::env::var_os("AWS_SHARED_CREDENTIALS_FILE")
275        .map(PathBuf::from)
276        .unwrap_or_else(|| home.join(".aws").join("credentials"));
277    let config = std::env::var_os("AWS_CONFIG_FILE")
278        .map(PathBuf::from)
279        .unwrap_or_else(|| home.join(".aws").join("config"));
280
281    Ok(vec![
282        (credentials, ProfileFileKind::Credentials),
283        (config, ProfileFileKind::Config),
284    ])
285}
286
287#[tauri::command]
288pub async fn discover_local_profiles() -> Result<Vec<DiscoveredProfile>, String> {
289    let mut profiles: HashMap<String, LocalProfileMetadata> = HashMap::new();
290
291    for (path, kind) in local_profile_files()? {
292        log::info!("Checking AWS credentials path: {:?}", path);
293        if !path.exists() {
294            log::info!("Path does not exist.");
295            continue;
296        }
297
298        log::info!("Path exists, reading content...");
299        match std::fs::read_to_string(&path) {
300            Ok(content) => parse_profile_file(&content, kind, &mut profiles),
301            Err(err) => log::warn!("Could not read AWS profile file {:?}: {}", path, err),
302        }
303    }
304
305    if profiles.is_empty() {
306        log::info!("No profiles found, defaulting to 'default'");
307        profiles.insert("default".to_string(), LocalProfileMetadata::default());
308    }
309
310    let mut result: Vec<DiscoveredProfile> = profiles
311        .into_iter()
312        .map(|(name, metadata)| DiscoveredProfile {
313            name,
314            region: metadata.region,
315            is_sso: metadata.is_sso,
316        })
317        .collect();
318
319    result.sort_by(|a, b| a.name.cmp(&b.name));
320
321    log::info!("Found total of {} profiles", result.len());
322
323    Ok(result)
324}
325
326fn aws_cli_path() -> PathBuf {
327    let mut candidates = Vec::new();
328
329    #[cfg(target_os = "windows")]
330    {
331        for variable in ["ProgramFiles", "ProgramW6432"] {
332            if let Some(root) = std::env::var_os(variable) {
333                candidates.push(PathBuf::from(root).join("Amazon/AWSCLIV2/aws.exe"));
334            }
335        }
336    }
337
338    #[cfg(target_os = "macos")]
339    {
340        candidates.push(PathBuf::from("/opt/homebrew/bin/aws"));
341        candidates.push(PathBuf::from("/usr/local/bin/aws"));
342    }
343
344    #[cfg(target_os = "linux")]
345    {
346        candidates.push(PathBuf::from("/usr/local/bin/aws"));
347        candidates.push(PathBuf::from("/usr/bin/aws"));
348    }
349
350    candidates
351        .into_iter()
352        .find(|path| path.is_file())
353        .unwrap_or_else(|| {
354            PathBuf::from(if cfg!(target_os = "windows") {
355                "aws.exe"
356            } else {
357                "aws"
358            })
359        })
360}
361
362fn concise_cli_error(output: &[u8]) -> String {
363    let message = String::from_utf8_lossy(output).trim().to_string();
364    if message.chars().count() > 2_000 {
365        format!("{}…", message.chars().take(2_000).collect::<String>())
366    } else {
367        message
368    }
369}
370
371#[tauri::command]
372pub async fn login_sso(profile_name: String) -> Result<String, String> {
373    let profile_name = profile_name.trim();
374    if profile_name.is_empty() {
375        return Err("AWS profile name is required".to_string());
376    }
377
378    let mut command = tokio::process::Command::new(aws_cli_path());
379    command
380        .args(["sso", "login", "--profile", profile_name])
381        .stdin(std::process::Stdio::null())
382        .kill_on_drop(true);
383
384    let output = tokio::time::timeout(Duration::from_secs(10 * 60), command.output())
385        .await
386        .map_err(|_| "AWS SSO sign-in timed out after 10 minutes".to_string())?
387        .map_err(|err| {
388            if err.kind() == std::io::ErrorKind::NotFound {
389                "AWS CLI v2 was not found. Install it, then run `aws sso login --profile <name>` or try this button again.".to_string()
390            } else {
391                format!("Could not start AWS CLI: {err}")
392            }
393        })?;
394
395    if output.status.success() {
396        Ok(format!(
397            "AWS SSO sign-in completed for profile '{profile_name}'"
398        ))
399    } else {
400        let stderr = concise_cli_error(&output.stderr);
401        let stdout = concise_cli_error(&output.stdout);
402        let detail = if !stderr.is_empty() { stderr } else { stdout };
403        Err(if detail.is_empty() {
404            format!("AWS SSO sign-in failed with status {}", output.status)
405        } else {
406            format!("AWS SSO sign-in failed: {detail}")
407        })
408    }
409}
410
411#[derive(Debug, Serialize, Deserialize)]
412pub struct EnvironmentCheck {
413    pub has_access_key: bool,
414    pub has_secret_key: bool,
415    pub has_session_token: bool,
416    pub region: Option<String>,
417}
418
419#[tauri::command]
420pub async fn check_aws_environment() -> Result<EnvironmentCheck, String> {
421    Ok(EnvironmentCheck {
422        has_access_key: std::env::var("AWS_ACCESS_KEY_ID").is_ok(),
423        has_secret_key: std::env::var("AWS_SECRET_ACCESS_KEY").is_ok(),
424        has_session_token: std::env::var("AWS_SESSION_TOKEN").is_ok(),
425        region: std::env::var("AWS_REGION")
426            .ok()
427            .or_else(|| std::env::var("AWS_DEFAULT_REGION").ok()),
428    })
429}
430
431#[cfg(test)]
432mod tests {
433    use super::{parse_profile_file, LocalProfileMetadata, ProfileFileKind};
434    use std::collections::HashMap;
435
436    #[test]
437    fn discovery_marks_sso_profiles_and_skips_support_sections() {
438        let config = r#"
439            [profile engineering]
440            sso_session = company
441            sso_account_id = 123456789012
442            sso_role_name = Developer
443            region = ap-southeast-2
444
445            [sso-session company]
446            sso_start_url = https://example.awsapps.com/start
447            sso_region = us-east-1
448
449            [services local]
450            s3 =
451              endpoint_url = http://localhost:9000
452        "#;
453        let mut profiles: HashMap<String, LocalProfileMetadata> = HashMap::new();
454
455        parse_profile_file(config, ProfileFileKind::Config, &mut profiles);
456
457        assert_eq!(profiles.len(), 1);
458        let engineering = profiles.get("engineering").unwrap();
459        assert!(engineering.is_sso);
460        assert_eq!(engineering.region.as_deref(), Some("ap-southeast-2"));
461        assert!(!profiles.contains_key("sso-session company"));
462        assert!(!profiles.contains_key("services local"));
463    }
464
465    #[test]
466    fn discovery_merges_credentials_and_config_profile_data() {
467        let mut profiles: HashMap<String, LocalProfileMetadata> = HashMap::new();
468        parse_profile_file(
469            "[archive]\naws_access_key_id = test",
470            ProfileFileKind::Credentials,
471            &mut profiles,
472        );
473        parse_profile_file(
474            "[profile archive]\nregion = eu-west-1",
475            ProfileFileKind::Config,
476            &mut profiles,
477        );
478
479        assert_eq!(profiles.len(), 1);
480        assert_eq!(
481            profiles.get("archive").unwrap().region.as_deref(),
482            Some("eu-west-1")
483        );
484    }
485}