Skip to main content

bitbucket_cli/auth/
oauth.rs

1use anyhow::{Context, Result};
2use oauth2::basic::BasicClient;
3use oauth2::{
4    AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, RedirectUrl,
5    RefreshToken, Scope, TokenResponse, TokenUrl,
6};
7use std::io::{BufRead, BufReader, Write};
8use std::net::TcpListener;
9use std::time::Duration;
10
11use super::{AuthManager, Credential};
12
13/// Async HTTP client for OAuth2 token exchange
14async fn async_http_client(
15    request: oauth2::HttpRequest,
16) -> Result<oauth2::HttpResponse, reqwest::Error> {
17    let client = reqwest::Client::builder()
18        .redirect(reqwest::redirect::Policy::none())
19        .timeout(Duration::from_secs(30))
20        .connect_timeout(Duration::from_secs(10))
21        .build()?;
22
23    let mut request_builder = client
24        .request(request.method().clone(), request.uri().to_string())
25        .body(request.body().clone());
26
27    for (name, value) in request.headers() {
28        request_builder = request_builder.header(name.as_str(), value.as_bytes());
29    }
30
31    let response = request_builder.send().await?;
32
33    let status_code = response.status();
34    let headers = response.headers().to_owned();
35    let body = response.bytes().await?.to_vec();
36
37    let mut builder = oauth2::http::Response::builder().status(status_code);
38
39    for (name, value) in headers.iter() {
40        builder = builder.header(name, value);
41    }
42
43    // Build the response - this should never fail with valid HTTP data
44    Ok(builder.body(body).expect("Failed to build HTTP response"))
45}
46
47const BITBUCKET_AUTH_URL: &str = "https://bitbucket.org/site/oauth2/authorize";
48const BITBUCKET_TOKEN_URL: &str = "https://bitbucket.org/site/oauth2/access_token";
49
50/// OAuth 2.0 authentication flow
51pub struct OAuthFlow {
52    client_id: String,
53    client_secret: String,
54}
55
56impl OAuthFlow {
57    pub fn new(client_id: String, client_secret: String) -> Self {
58        Self {
59            client_id,
60            client_secret,
61        }
62    }
63
64    /// Try to bind to one of the preferred ports
65    fn bind_to_available_port(ports: &[u16]) -> Result<(TcpListener, u16)> {
66        for &port in ports {
67            match TcpListener::bind(format!("127.0.0.1:{}", port)) {
68                Ok(listener) => {
69                    return Ok((listener, port));
70                }
71                Err(_) => continue,
72            }
73        }
74
75        anyhow::bail!(
76            "Could not bind to any preferred port. Tried: {:?}\n\n\
77            Please ensure at least one of these ports is available:\n\
78            - Close any applications using these ports\n\
79            - Or use API key authentication: bitbucket auth login --api-key",
80            ports
81        )
82    }
83
84    /// Run the OAuth 2.0 authentication flow
85    pub async fn authenticate(&self, auth_manager: &AuthManager) -> Result<Credential> {
86        println!("\nšŸ” Bitbucket OAuth Authentication");
87        println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
88        println!();
89
90        // Use a static port for OAuth callback (required by Bitbucket)
91        // Try common ports in order: 8080, 3000, 8888, 9000
92        const PREFERRED_PORTS: &[u16] = &[8080, 3000, 8888, 9000];
93
94        let (listener, port) = Self::bind_to_available_port(PREFERRED_PORTS)
95            .context("Failed to bind callback server. Please ensure one of these ports is available: 8080, 3000, 8888, or 9000")?;
96
97        let redirect_url = format!("http://127.0.0.1:{}/callback", port);
98
99        println!("šŸ“” Callback server listening on port {}", port);
100        println!("   Make sure your OAuth consumer callback URL is set to:");
101        println!("   {}", redirect_url);
102        println!();
103
104        // Create OAuth client
105        let client = BasicClient::new(ClientId::new(self.client_id.clone()))
106            .set_client_secret(ClientSecret::new(self.client_secret.clone()))
107            .set_auth_uri(AuthUrl::new(BITBUCKET_AUTH_URL.to_string())?)
108            .set_token_uri(TokenUrl::new(BITBUCKET_TOKEN_URL.to_string())?)
109            .set_redirect_uri(RedirectUrl::new(redirect_url.clone())?);
110
111        // Generate PKCE challenge
112        let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();
113
114        // Generate authorization URL
115        let (auth_url, csrf_token) = client
116            .authorize_url(CsrfToken::new_random)
117            .add_scope(Scope::new("repository".to_string()))
118            // Required to upload repository downloads (`repo download upload`).
119            // Existing users must re-run `auth login` to consent.
120            .add_scope(Scope::new("repository:write".to_string()))
121            .add_scope(Scope::new("pullrequest".to_string()))
122            .add_scope(Scope::new("issue".to_string()))
123            .add_scope(Scope::new("pipeline".to_string()))
124            .add_scope(Scope::new("account".to_string()))
125            .set_pkce_challenge(pkce_challenge)
126            .url();
127
128        println!("Opening browser for authentication...");
129        println!();
130
131        // Try to open browser
132        if open::that(auth_url.as_str()).is_err() {
133            println!("Could not open browser automatically.");
134            println!("Please open this URL in your browser:");
135            println!();
136            println!("  {}", auth_url);
137            println!();
138        }
139
140        println!("Waiting for authorization...");
141
142        // Wait for callback
143        let code = Self::wait_for_callback(listener, csrf_token)?;
144
145        println!("Authorization received, exchanging for token...");
146
147        // Exchange code for token
148        let token_response = client
149            .exchange_code(code)
150            .set_pkce_verifier(pkce_verifier)
151            .request_async(&async_http_client)
152            .await
153            .context("Failed to exchange authorization code for token")?;
154
155        let access_token = token_response.access_token().secret().to_string();
156        let refresh_token = token_response
157            .refresh_token()
158            .map(|t| t.secret().to_string());
159        let expires_at = token_response
160            .expires_in()
161            .map(|d| chrono::Utc::now().timestamp() + d.as_secs() as i64);
162
163        let credential = Credential::OAuth {
164            access_token,
165            refresh_token,
166            expires_at,
167            client_id: Some(self.client_id.clone()),
168            client_secret: Some(self.client_secret.clone()),
169        };
170
171        // Store credentials
172        auth_manager.store_credentials(&credential)?;
173
174        println!("\nāœ… Successfully authenticated via OAuth");
175
176        Ok(credential)
177    }
178
179    /// Wait for the OAuth callback and extract the authorization code
180    fn wait_for_callback(
181        listener: TcpListener,
182        expected_csrf: CsrfToken,
183    ) -> Result<AuthorizationCode> {
184        for stream in listener.incoming() {
185            let mut stream = match stream {
186                Ok(s) => s,
187                Err(_) => continue,
188            };
189
190            let mut reader = BufReader::new(&stream);
191            let mut request_line = String::new();
192            if reader.read_line(&mut request_line).is_err() {
193                continue;
194            }
195
196            // Parse the request URL
197            let Some(redirect_url) = request_line.split_whitespace().nth(1) else {
198                continue;
199            };
200
201            let Ok(url) = url::Url::parse(&format!("http://localhost{}", redirect_url)) else {
202                continue;
203            };
204
205            let params: Vec<(String, String)> = url
206                .query_pairs()
207                .map(|(key, value)| (key.into_owned(), value.into_owned()))
208                .collect();
209
210            match interpret_callback(&params, expected_csrf.secret()) {
211                CallbackOutcome::CsrfReject => {
212                    let response = "HTTP/1.1 400 Bad Request\r\n\r\nCSRF token mismatch";
213                    let _ = stream.write_all(response.as_bytes());
214                    continue;
215                }
216                CallbackOutcome::Code(code) => {
217                    // Send success response
218                    let response = r#"HTTP/1.1 200 OK
219Content-Type: text/html
220
221<!DOCTYPE html>
222<html>
223<head><title>Bitbucket CLI</title></head>
224<body style="font-family: system-ui; text-align: center; padding: 50px;">
225<h1>āœ… Authentication Successful</h1>
226<p>You can close this window and return to the terminal.</p>
227</body>
228</html>"#;
229                    let _ = stream.write_all(response.as_bytes());
230
231                    return Ok(AuthorizationCode::new(code));
232                }
233                CallbackOutcome::Failed(description) => {
234                    // No authorization code: the provider denied the request
235                    // or returned an error.
236                    let response = r#"HTTP/1.1 200 OK
237Content-Type: text/html
238
239<!DOCTYPE html>
240<html>
241<head><title>Bitbucket CLI</title></head>
242<body style="font-family: system-ui; text-align: center; padding: 50px;">
243<h1>āŒ Authentication Failed</h1>
244<p>You can close this window and return to the terminal.</p>
245</body>
246</html>"#;
247                    let _ = stream.write_all(response.as_bytes());
248
249                    anyhow::bail!("Authentication failed: {}", description);
250                }
251            }
252        }
253
254        anyhow::bail!("Callback server closed unexpectedly")
255    }
256
257    /// Refresh an expired OAuth token
258    pub async fn refresh_token(
259        &self,
260        auth_manager: &AuthManager,
261        refresh_token: &str,
262    ) -> Result<Credential> {
263        let client = BasicClient::new(ClientId::new(self.client_id.clone()))
264            .set_client_secret(ClientSecret::new(self.client_secret.clone()))
265            .set_auth_uri(AuthUrl::new(BITBUCKET_AUTH_URL.to_string())?)
266            .set_token_uri(TokenUrl::new(BITBUCKET_TOKEN_URL.to_string())?);
267
268        let token_response = client
269            .exchange_refresh_token(&RefreshToken::new(refresh_token.to_string()))
270            .request_async(&async_http_client)
271            .await
272            .context("Failed to refresh token")?;
273
274        let access_token = token_response.access_token().secret().to_string();
275        let new_refresh_token = merged_refresh_token(
276            token_response
277                .refresh_token()
278                .map(|t| t.secret().to_string()),
279            refresh_token,
280        );
281        let expires_at = token_response
282            .expires_in()
283            .map(|d| chrono::Utc::now().timestamp() + d.as_secs() as i64);
284
285        let credential = Credential::OAuth {
286            access_token,
287            refresh_token: Some(new_refresh_token),
288            expires_at,
289            client_id: Some(self.client_id.clone()),
290            client_secret: Some(self.client_secret.clone()),
291        };
292
293        auth_manager.store_credentials(&credential)?;
294
295        Ok(credential)
296    }
297}
298
299/// Use the refresh token from the token response if present, otherwise keep
300/// the old one (Bitbucket does not always return a new refresh token).
301fn merged_refresh_token(new: Option<String>, old: &str) -> String {
302    new.unwrap_or_else(|| old.to_string())
303}
304
305/// Result of interpreting the query parameters of an OAuth callback request.
306#[derive(Debug, PartialEq, Eq)]
307enum CallbackOutcome {
308    /// State matched and an authorization code was returned.
309    Code(String),
310    /// State was missing or did not match the expected CSRF token.
311    CsrfReject,
312    /// State matched but no authorization code was returned; carries the
313    /// failure description.
314    Failed(String),
315}
316
317/// Decide how to handle an OAuth callback based on its query parameters.
318///
319/// A callback with a missing state is rejected exactly like a mismatched
320/// one. When the state matches but no code is present, the failure
321/// description prefers `error_description`, then `error`, then a generic
322/// message.
323fn interpret_callback(params: &[(String, String)], expected_state: &str) -> CallbackOutcome {
324    let mut code = None;
325    let mut state = None;
326    let mut error = None;
327    let mut error_description = None;
328
329    for (key, value) in params {
330        match key.as_str() {
331            "code" => code = Some(value.clone()),
332            "state" => state = Some(value.clone()),
333            "error" => error = Some(value.clone()),
334            "error_description" => error_description = Some(value.clone()),
335            _ => {}
336        }
337    }
338
339    match state {
340        Some(ref state) if state == expected_state => {}
341        _ => return CallbackOutcome::CsrfReject,
342    }
343
344    if let Some(code) = code {
345        return CallbackOutcome::Code(code);
346    }
347
348    CallbackOutcome::Failed(
349        error_description
350            .or(error)
351            .unwrap_or_else(|| "no authorization code returned".to_string()),
352    )
353}
354
355#[cfg(test)]
356mod tests {
357    use super::{CallbackOutcome, interpret_callback, merged_refresh_token};
358
359    #[test]
360    fn new_refresh_token_replaces_old_one() {
361        assert_eq!(
362            merged_refresh_token(Some("new-token".to_string()), "old-token"),
363            "new-token"
364        );
365    }
366
367    #[test]
368    fn old_refresh_token_kept_when_response_has_none() {
369        assert_eq!(merged_refresh_token(None, "old-token"), "old-token");
370    }
371
372    fn params(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
373        pairs
374            .iter()
375            .map(|(key, value)| (key.to_string(), value.to_string()))
376            .collect()
377    }
378
379    #[test]
380    fn callback_with_missing_state_is_csrf_rejected() {
381        let outcome = interpret_callback(&params(&[("code", "abc123")]), "expected-state");
382        assert_eq!(outcome, CallbackOutcome::CsrfReject);
383    }
384
385    #[test]
386    fn callback_with_wrong_state_is_csrf_rejected() {
387        let outcome = interpret_callback(
388            &params(&[("code", "abc123"), ("state", "wrong-state")]),
389            "expected-state",
390        );
391        assert_eq!(outcome, CallbackOutcome::CsrfReject);
392    }
393
394    #[test]
395    fn callback_with_matching_state_and_code_returns_code() {
396        let outcome = interpret_callback(
397            &params(&[("code", "abc123"), ("state", "expected-state")]),
398            "expected-state",
399        );
400        assert_eq!(outcome, CallbackOutcome::Code("abc123".to_string()));
401    }
402
403    #[test]
404    fn callback_error_description_used_when_no_code() {
405        let outcome = interpret_callback(
406            &params(&[
407                ("state", "expected-state"),
408                ("error", "access_denied"),
409                ("error_description", "The user denied access"),
410            ]),
411            "expected-state",
412        );
413        assert_eq!(
414            outcome,
415            CallbackOutcome::Failed("The user denied access".to_string())
416        );
417    }
418
419    #[test]
420    fn callback_error_used_when_no_description() {
421        let outcome = interpret_callback(
422            &params(&[("state", "expected-state"), ("error", "access_denied")]),
423            "expected-state",
424        );
425        assert_eq!(
426            outcome,
427            CallbackOutcome::Failed("access_denied".to_string())
428        );
429    }
430
431    #[test]
432    fn callback_without_code_or_error_reports_generic_failure() {
433        let outcome = interpret_callback(&params(&[("state", "expected-state")]), "expected-state");
434        assert_eq!(
435            outcome,
436            CallbackOutcome::Failed("no authorization code returned".to_string())
437        );
438    }
439}