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