Skip to main content

bitbucket_cli/cli/
auth.rs

1use anyhow::{Context, Result};
2use clap::Subcommand;
3use colored::Colorize;
4use dialoguer::{Input, Select};
5
6use crate::auth::{ApiKeyAuth, AuthManager, OAuthFlow};
7use crate::config::Config;
8
9#[derive(Subcommand)]
10pub enum AuthCommands {
11    /// Authenticate with Bitbucket (OAuth 2.0 or API key)
12    Login {
13        /// Use OAuth 2.0 authentication (interactive browser sign-in)
14        #[arg(long, conflicts_with = "api_key")]
15        oauth: bool,
16
17        /// Use API key authentication (HTTP access token; for automation/CI)
18        #[arg(long, conflicts_with = "oauth")]
19        api_key: bool,
20
21        /// Atlassian account email / Bitbucket username (for API key authentication)
22        #[arg(long, env = "BITBUCKET_EMAIL", conflicts_with = "oauth")]
23        email: Option<String>,
24
25        /// API key (HTTP access token; for API key authentication, implies --api-key)
26        #[arg(long, env = "BITBUCKET_API_TOKEN", conflicts_with = "oauth")]
27        token: Option<String>,
28
29        /// OAuth Client ID (for OAuth authentication)
30        #[arg(long, env = "BITBUCKET_CLIENT_ID")]
31        client_id: Option<String>,
32
33        /// OAuth Client Secret (for OAuth authentication)
34        #[arg(long, env = "BITBUCKET_CLIENT_SECRET")]
35        client_secret: Option<String>,
36    },
37
38    /// Remove stored credentials
39    Logout,
40
41    /// Show authentication status
42    Status,
43}
44
45impl AuthCommands {
46    pub async fn run(self) -> Result<()> {
47        match self {
48            AuthCommands::Login {
49                oauth,
50                api_key,
51                email,
52                token,
53                client_id,
54                client_secret,
55            } => {
56                let auth_manager = AuthManager::new()?;
57
58                let use_api_key = resolve_auth_method(
59                    oauth,
60                    api_key,
61                    email.is_some() || token.is_some(),
62                    client_id.is_some() || client_secret.is_some(),
63                )?;
64
65                if use_api_key {
66                    ApiKeyAuth::authenticate(&auth_manager, email, token).await?;
67                    return Ok(());
68                }
69
70                // OAuth 2.0 authentication.
71                // Resolve consumer credentials from (in priority):
72                // 1. CLI flags / env vars
73                // 2. Previously stored credentials
74                // 3. Interactive prompt (first-time only)
75                let stored_consumer = auth_manager.get_credentials().ok().flatten().and_then(|c| {
76                    c.oauth_consumer_credentials()
77                        .map(|(id, secret)| (id.to_owned(), secret.to_owned()))
78                });
79
80                let client_id = client_id
81                    .or_else(|| stored_consumer.as_ref().map(|(id, _)| id.clone()))
82                    .or_else(|| {
83                        println!();
84                        println!("📋 OAuth Consumer Setup Required");
85                        println!();
86                        println!("To use OAuth authentication, create an OAuth consumer in Bitbucket:");
87                        println!("1. Go to: https://bitbucket.org/[workspace]/workspace/settings/oauth-consumers/new");
88                        println!("2. Set callback URL to ONE of these (pick any available port):");
89                        println!("   • http://127.0.0.1:8080/callback");
90                        println!("   • http://127.0.0.1:3000/callback");
91                        println!("   • http://127.0.0.1:8888/callback");
92                        println!("   • http://127.0.0.1:9000/callback");
93                        println!("3. Select required permissions:");
94                        println!("   ✓ Account (Read)");
95                        println!("   ✓ Repositories (Read)");
96                        println!("   ✓ Pull requests (Read, Write)");
97                        println!("   ✓ Issues (Read, Write)");
98                        println!("   ✓ Pipelines (Read, Write)");
99                        println!("4. Copy the Key (Client ID) and Secret");
100                        println!();
101
102                        Input::<String>::new()
103                            .with_prompt("OAuth Client ID (Key)")
104                            .interact_text()
105                            .ok()
106                    })
107                    .ok_or_else(|| anyhow::anyhow!("OAuth Client ID is required"))?;
108
109                let client_secret = client_secret
110                    .or_else(|| stored_consumer.map(|(_, secret)| secret))
111                    .or_else(|| {
112                        Input::<String>::new()
113                            .with_prompt("OAuth Client Secret")
114                            .interact_text()
115                            .ok()
116                    })
117                    .ok_or_else(|| anyhow::anyhow!("OAuth Client Secret is required"))?;
118
119                let oauth = OAuthFlow::new(client_id, client_secret);
120                oauth.authenticate(&auth_manager).await?;
121
122                Ok(())
123            }
124
125            AuthCommands::Logout => {
126                let auth_manager = AuthManager::new()?;
127                auth_manager.clear_credentials()?;
128
129                let mut config = Config::load()?;
130                config.clear_auth();
131                config.save()?;
132
133                println!("{} Logged out successfully", "✓".green());
134                Ok(())
135            }
136
137            AuthCommands::Status => {
138                let auth_manager = AuthManager::new()?;
139                let config = Config::load()?;
140
141                if auth_manager.is_authenticated() {
142                    println!("{} Authenticated", "✓".green());
143
144                    if let Ok(Some(credential)) = auth_manager.get_credentials() {
145                        println!("  {} {}", "Method:".dimmed(), credential.type_name());
146
147                        // Show username from credential for API keys, or config for OAuth
148                        if let Some(username) = credential.username() {
149                            println!("  {} {}", "Username:".dimmed(), username);
150                        } else if let Some(username) = config.username() {
151                            println!("  {} {}", "Username:".dimmed(), username);
152                        }
153
154                        if credential.needs_refresh() {
155                            println!(
156                                "  {} {}",
157                                "Status:".dimmed(),
158                                "Token needs refresh (will auto-refresh on next use)".yellow()
159                            );
160                        }
161                    }
162
163                    if let Some(workspace) = config.default_workspace() {
164                        println!("  {} {}", "Workspace:".dimmed(), workspace);
165                    }
166
167                    match crate::api::BitbucketClient::from_stored().await {
168                        Ok(client) => match client.get::<serde_json::Value>("/user").await {
169                            Ok(user) => {
170                                if let Some(display_name) = user.get("display_name") {
171                                    println!(
172                                        "  {} {}",
173                                        "Display name:".dimmed(),
174                                        display_name.as_str().unwrap_or("Unknown")
175                                    );
176                                }
177                            }
178                            Err(e) => {
179                                println!("{} Credentials may be invalid: {}", "âš ".yellow(), e);
180                            }
181                        },
182                        Err(e) => {
183                            println!("{} Failed to create client: {}", "✗".red(), e);
184                        }
185                    }
186                } else {
187                    println!("{} Not authenticated", "✗".red());
188                    println!();
189                    println!("Run {} to authenticate", "bitbucket auth login".cyan());
190                }
191
192                Ok(())
193            }
194        }
195    }
196}
197
198/// Resolve which authentication method to use.
199///
200/// Returns `true` for API key, `false` for OAuth 2.0.
201///
202/// Priority: explicit flag > method-implying inputs > interactive prompt.
203fn resolve_auth_method(
204    oauth: bool,
205    api_key: bool,
206    api_key_inputs_present: bool,
207    oauth_inputs_present: bool,
208) -> Result<bool> {
209    if api_key || api_key_inputs_present {
210        return Ok(true);
211    }
212    if oauth || oauth_inputs_present {
213        return Ok(false);
214    }
215
216    println!();
217    println!("{}", "Choose an authentication method".bold());
218    println!();
219    println!(
220        "  {}  Browser-based sign-in. Recommended for interactive use.",
221        "OAuth 2.0".cyan()
222    );
223    println!(
224        "  {}     HTTP access token. For automation, CI, and headless environments.",
225        "API key".cyan()
226    );
227    println!();
228
229    let options = ["OAuth 2.0 (browser sign-in)", "API key (access token)"];
230
231    let selection = Select::new()
232        .with_prompt("Authentication method")
233        .items(&options)
234        .default(0)
235        .interact()
236        .context("Failed to read authentication method selection")?;
237
238    Ok(selection == 1)
239}
240
241#[cfg(test)]
242mod tests {
243    use super::resolve_auth_method;
244
245    #[test]
246    fn explicit_api_key_flag_selects_api_key() {
247        assert!(resolve_auth_method(false, true, false, false).unwrap());
248    }
249
250    #[test]
251    fn explicit_oauth_flag_selects_oauth() {
252        assert!(!resolve_auth_method(true, false, false, false).unwrap());
253    }
254
255    #[test]
256    fn email_or_token_implies_api_key() {
257        assert!(resolve_auth_method(false, false, true, false).unwrap());
258    }
259
260    #[test]
261    fn oauth_inputs_imply_oauth() {
262        assert!(!resolve_auth_method(false, false, false, true).unwrap());
263    }
264
265    #[test]
266    fn api_key_inputs_win_over_oauth_inputs() {
267        assert!(resolve_auth_method(false, false, true, true).unwrap());
268    }
269}