Skip to main content

bitbucket_cli/auth/
api_key.rs

1use anyhow::{Context, Result};
2use dialoguer::Input;
3
4use super::{AuthManager, Credential};
5
6/// Strip bracketed-paste escape markers and control characters that some
7/// terminals inject when a token is pasted, then trim surrounding whitespace.
8fn sanitize_pasted_token(raw: &str) -> String {
9    raw.replace("\x1b[200~", "")
10        .replace("\x1b[201~", "")
11        .chars()
12        .filter(|c| !c.is_control())
13        .collect::<String>()
14        .trim()
15        .to_string()
16}
17
18/// API key authentication flow (fallback method)
19/// Note: Atlassian has deprecated app passwords in favor of OAuth2
20pub struct ApiKeyAuth;
21
22impl ApiKeyAuth {
23    /// Run the API key authentication flow.
24    ///
25    /// `email` and `api_key` may be supplied up front (via CLI flags or env
26    /// vars) to skip the corresponding prompts; when both are present the
27    /// flow is fully non-interactive.
28    pub async fn authenticate(
29        auth_manager: &AuthManager,
30        email: Option<String>,
31        api_key: Option<String>,
32    ) -> Result<Credential> {
33        if email.is_none() || api_key.is_none() {
34            println!("\nšŸ” Bitbucket API Key Authentication");
35            println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
36            println!();
37            println!("āš ļø  Note: OAuth 2.0 is the preferred authentication method.");
38            println!("   API keys are provided for automation/CI scenarios.");
39            println!();
40            println!("To create an API key (HTTP access token):");
41            println!("1. Go to Bitbucket Settings → Personal settings");
42            println!("2. Click 'HTTP access tokens' under 'Access management'");
43            println!("3. Click 'Create token'");
44            println!("4. Give it a label and select required permissions");
45            println!();
46        }
47
48        let username: String = match email {
49            Some(email) => email,
50            None => Input::new()
51                .with_prompt("Atlassian account email / Bitbucket username")
52                .interact_text()
53                .context("Failed to read username")?,
54        };
55
56        let api_key = match api_key {
57            Some(api_key) => api_key,
58            // rpassword reads a full line with echo disabled, so terminal
59            // paste works — dialoguer's Password reads key events and drops
60            // pasted input in many terminals.
61            None => rpassword::prompt_password("API key (HTTP access token): ")
62                .context("Failed to read API key")?,
63        };
64
65        let api_key = sanitize_pasted_token(&api_key);
66
67        if username.trim().is_empty() {
68            anyhow::bail!("Email/username cannot be empty");
69        }
70
71        // Validate token format
72        if api_key.is_empty() {
73            anyhow::bail!("API key cannot be empty");
74        }
75
76        // Check for common Atlassian token prefixes
77        if !api_key.starts_with("ATATT") && !api_key.starts_with("ATCTT") {
78            println!("āš ļø  Warning: Token doesn't start with expected prefix (ATATT or ATCTT)");
79            println!("   This might not be a valid Bitbucket API token.");
80            println!(
81                "   Token starts with: {}",
82                &api_key.chars().take(5).collect::<String>()
83            );
84        }
85
86        let credential = Credential::ApiKey {
87            username: username.clone(),
88            api_key,
89        };
90
91        // Validate credentials by making a test API call
92        Self::validate_credentials(&credential).await?;
93
94        // Store credentials
95        auth_manager.store_credentials(&credential)?;
96
97        println!("\nāœ… Successfully authenticated as {}", username);
98        println!("šŸ’” Tip: Use 'bitbucket auth login --oauth' for a better experience");
99
100        Ok(credential)
101    }
102
103    /// Validate credentials against the Bitbucket API
104    async fn validate_credentials(credential: &Credential) -> Result<()> {
105        let client = reqwest::Client::new();
106
107        println!("šŸ” Validating credentials with Bitbucket API...");
108
109        let response = client
110            .get("https://api.bitbucket.org/2.0/user")
111            .header("Authorization", credential.auth_header())
112            .header("User-Agent", "bitbucket-cli/0.3.0")
113            .send()
114            .await
115            .context("Failed to connect to Bitbucket API")?;
116
117        let status = response.status();
118
119        if status.is_success() {
120            Ok(())
121        } else if status == reqwest::StatusCode::UNAUTHORIZED {
122            anyhow::bail!(
123                "Authentication failed (401 Unauthorized).\n\n\
124                Possible causes:\n\
125                - Incorrect username\n\
126                - Invalid or expired API token\n\
127                - Token doesn't have required permissions\n\n\
128                Please verify:\n\
129                1. Your Bitbucket username is correct\n\
130                2. Your API token is copied completely (should start with 'ATATT' or 'ATCTT')\n\
131                3. Token has 'Read' permission at minimum"
132            )
133        } else {
134            let body = response
135                .text()
136                .await
137                .unwrap_or_else(|_| String::from("<unable to read response>"));
138            anyhow::bail!(
139                "API error ({}):\n{}\n\n\
140                This might indicate:\n\
141                - Network connectivity issues\n\
142                - Bitbucket API is unavailable\n\
143                - Rate limiting",
144                status,
145                body
146            )
147        }
148    }
149}
150
151#[cfg(test)]
152mod tests {
153    use super::sanitize_pasted_token;
154
155    #[test]
156    fn passes_through_clean_token() {
157        assert_eq!(sanitize_pasted_token("ATATT123abc"), "ATATT123abc");
158    }
159
160    #[test]
161    fn trims_surrounding_whitespace_and_newline() {
162        assert_eq!(sanitize_pasted_token("  ATATT123abc\n"), "ATATT123abc");
163    }
164
165    #[test]
166    fn strips_bracketed_paste_markers() {
167        assert_eq!(
168            sanitize_pasted_token("\x1b[200~ATATT123abc\x1b[201~"),
169            "ATATT123abc"
170        );
171    }
172
173    #[test]
174    fn strips_stray_control_characters() {
175        assert_eq!(sanitize_pasted_token("ATATT\x07123\tabc\r"), "ATATT123abc");
176    }
177}