bitbucket_cli/auth/
api_key.rs1use anyhow::{Context, Result};
2use dialoguer::Input;
3
4use super::{AuthManager, Credential};
5
6fn 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
18pub struct ApiKeyAuth;
21
22impl ApiKeyAuth {
23 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 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 if api_key.is_empty() {
73 anyhow::bail!("API key cannot be empty");
74 }
75
76 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 Self::validate_credentials(&credential).await?;
93
94 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 async fn validate_credentials(credential: &Credential) -> Result<()> {
105 let client = reqwest::Client::builder()
106 .timeout(std::time::Duration::from_secs(30))
107 .connect_timeout(std::time::Duration::from_secs(10))
108 .user_agent(crate::api::client::USER_AGENT)
109 .build()
110 .context("Failed to create HTTP client")?;
111
112 println!("š Validating credentials with Bitbucket API...");
113
114 let response = client
115 .get("https://api.bitbucket.org/2.0/user")
116 .header("Authorization", credential.auth_header())
117 .send()
118 .await
119 .context("Failed to connect to Bitbucket API")?;
120
121 let status = response.status();
122
123 if status.is_success() {
124 Ok(())
125 } else if status == reqwest::StatusCode::UNAUTHORIZED {
126 anyhow::bail!(
127 "Authentication failed (401 Unauthorized).\n\n\
128 Possible causes:\n\
129 - Incorrect username\n\
130 - Invalid or expired API token\n\
131 - Token doesn't have required permissions\n\n\
132 Please verify:\n\
133 1. Your Bitbucket username is correct\n\
134 2. Your API token is copied completely (should start with 'ATATT' or 'ATCTT')\n\
135 3. Token has 'Read' permission at minimum"
136 )
137 } else {
138 let body = response
139 .text()
140 .await
141 .unwrap_or_else(|_| String::from("<unable to read response>"));
142 anyhow::bail!(
143 "API error ({}):\n{}\n\n\
144 This might indicate:\n\
145 - Network connectivity issues\n\
146 - Bitbucket API is unavailable\n\
147 - Rate limiting",
148 status,
149 body
150 )
151 }
152 }
153}
154
155#[cfg(test)]
156mod tests {
157 use super::sanitize_pasted_token;
158
159 #[test]
160 fn passes_through_clean_token() {
161 assert_eq!(sanitize_pasted_token("ATATT123abc"), "ATATT123abc");
162 }
163
164 #[test]
165 fn trims_surrounding_whitespace_and_newline() {
166 assert_eq!(sanitize_pasted_token(" ATATT123abc\n"), "ATATT123abc");
167 }
168
169 #[test]
170 fn strips_bracketed_paste_markers() {
171 assert_eq!(
172 sanitize_pasted_token("\x1b[200~ATATT123abc\x1b[201~"),
173 "ATATT123abc"
174 );
175 }
176
177 #[test]
178 fn strips_stray_control_characters() {
179 assert_eq!(sanitize_pasted_token("ATATT\x07123\tabc\r"), "ATATT123abc");
180 }
181}