bitbucket-cli 1.0.1

A powerful command-line interface for Bitbucket Cloud - manage repos, PRs, issues, and pipelines from your terminal with OAuth 2.0
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
use anyhow::{Context, Result};
use oauth2::basic::BasicClient;
use oauth2::{
    AuthUrl, AuthorizationCode, ClientId, ClientSecret, CsrfToken, PkceCodeChallenge, RedirectUrl,
    RefreshToken, Scope, TokenResponse, TokenUrl,
};
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
use std::time::Duration;

use super::{AuthManager, Credential};

/// Async HTTP client for OAuth2 token exchange
async fn async_http_client(
    request: oauth2::HttpRequest,
) -> Result<oauth2::HttpResponse, reqwest::Error> {
    let client = reqwest::Client::builder()
        .redirect(reqwest::redirect::Policy::none())
        .timeout(Duration::from_secs(30))
        .connect_timeout(Duration::from_secs(10))
        .build()?;

    let mut request_builder = client
        .request(request.method().clone(), request.uri().to_string())
        .body(request.body().clone());

    for (name, value) in request.headers() {
        request_builder = request_builder.header(name.as_str(), value.as_bytes());
    }

    let response = request_builder.send().await?;

    let status_code = response.status();
    let headers = response.headers().to_owned();
    let body = response.bytes().await?.to_vec();

    let mut builder = oauth2::http::Response::builder().status(status_code);

    for (name, value) in headers.iter() {
        builder = builder.header(name, value);
    }

    // Build the response - this should never fail with valid HTTP data
    Ok(builder.body(body).expect("Failed to build HTTP response"))
}

const BITBUCKET_AUTH_URL: &str = "https://bitbucket.org/site/oauth2/authorize";
const BITBUCKET_TOKEN_URL: &str = "https://bitbucket.org/site/oauth2/access_token";

/// OAuth 2.0 authentication flow
pub struct OAuthFlow {
    client_id: String,
    client_secret: String,
}

impl OAuthFlow {
    pub fn new(client_id: String, client_secret: String) -> Self {
        Self {
            client_id,
            client_secret,
        }
    }

    /// Try to bind to one of the preferred ports
    fn bind_to_available_port(ports: &[u16]) -> Result<(TcpListener, u16)> {
        for &port in ports {
            match TcpListener::bind(format!("127.0.0.1:{}", port)) {
                Ok(listener) => {
                    return Ok((listener, port));
                }
                Err(_) => continue,
            }
        }

        anyhow::bail!(
            "Could not bind to any preferred port. Tried: {:?}\n\n\
            Please ensure at least one of these ports is available:\n\
            - Close any applications using these ports\n\
            - Or use API key authentication: bitbucket auth login --api-key",
            ports
        )
    }

    /// Run the OAuth 2.0 authentication flow
    pub async fn authenticate(&self, auth_manager: &AuthManager) -> Result<Credential> {
        println!("\n🔐 Bitbucket OAuth Authentication");
        println!("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━");
        println!();

        // Use a static port for OAuth callback (required by Bitbucket)
        // Try common ports in order: 8080, 3000, 8888, 9000
        const PREFERRED_PORTS: &[u16] = &[8080, 3000, 8888, 9000];

        let (listener, port) = Self::bind_to_available_port(PREFERRED_PORTS)
            .context("Failed to bind callback server. Please ensure one of these ports is available: 8080, 3000, 8888, or 9000")?;

        let redirect_url = format!("http://127.0.0.1:{}/callback", port);

        println!("📡 Callback server listening on port {}", port);
        println!("   Make sure your OAuth consumer callback URL is set to:");
        println!("   {}", redirect_url);
        println!();

        // Create OAuth client
        let client = BasicClient::new(ClientId::new(self.client_id.clone()))
            .set_client_secret(ClientSecret::new(self.client_secret.clone()))
            .set_auth_uri(AuthUrl::new(BITBUCKET_AUTH_URL.to_string())?)
            .set_token_uri(TokenUrl::new(BITBUCKET_TOKEN_URL.to_string())?)
            .set_redirect_uri(RedirectUrl::new(redirect_url.clone())?);

        // Generate PKCE challenge
        let (pkce_challenge, pkce_verifier) = PkceCodeChallenge::new_random_sha256();

        // Generate authorization URL
        let (auth_url, csrf_token) = client
            .authorize_url(CsrfToken::new_random)
            .add_scope(Scope::new("repository".to_string()))
            // Required to upload repository downloads (`repo download upload`).
            // Existing users must re-run `auth login` to consent.
            .add_scope(Scope::new("repository:write".to_string()))
            .add_scope(Scope::new("pullrequest".to_string()))
            .add_scope(Scope::new("issue".to_string()))
            .add_scope(Scope::new("pipeline".to_string()))
            .add_scope(Scope::new("account".to_string()))
            .set_pkce_challenge(pkce_challenge)
            .url();

        println!("Opening browser for authentication...");
        println!();

        // Try to open browser
        if open::that(auth_url.as_str()).is_err() {
            println!("Could not open browser automatically.");
            println!("Please open this URL in your browser:");
            println!();
            println!("  {}", auth_url);
            println!();
        }

        println!("Waiting for authorization...");

        // Wait for callback
        let code = Self::wait_for_callback(listener, csrf_token)?;

        println!("Authorization received, exchanging for token...");

        // Exchange code for token
        let token_response = client
            .exchange_code(code)
            .set_pkce_verifier(pkce_verifier)
            .request_async(&async_http_client)
            .await
            .context("Failed to exchange authorization code for token")?;

        let access_token = token_response.access_token().secret().to_string();
        let refresh_token = token_response
            .refresh_token()
            .map(|t| t.secret().to_string());
        let expires_at = token_response
            .expires_in()
            .map(|d| chrono::Utc::now().timestamp() + d.as_secs() as i64);

        let credential = Credential::OAuth {
            access_token,
            refresh_token,
            expires_at,
            client_id: Some(self.client_id.clone()),
            client_secret: Some(self.client_secret.clone()),
        };

        // Store credentials
        auth_manager.store_credentials(&credential)?;

        println!("\n✅ Successfully authenticated via OAuth");

        Ok(credential)
    }

    /// Wait for the OAuth callback and extract the authorization code
    fn wait_for_callback(
        listener: TcpListener,
        expected_csrf: CsrfToken,
    ) -> Result<AuthorizationCode> {
        for stream in listener.incoming() {
            let mut stream = match stream {
                Ok(s) => s,
                Err(_) => continue,
            };

            let mut reader = BufReader::new(&stream);
            let mut request_line = String::new();
            if reader.read_line(&mut request_line).is_err() {
                continue;
            }

            // Parse the request URL
            let Some(redirect_url) = request_line.split_whitespace().nth(1) else {
                continue;
            };

            let Ok(url) = url::Url::parse(&format!("http://localhost{}", redirect_url)) else {
                continue;
            };

            let params: Vec<(String, String)> = url
                .query_pairs()
                .map(|(key, value)| (key.into_owned(), value.into_owned()))
                .collect();

            match interpret_callback(&params, expected_csrf.secret()) {
                CallbackOutcome::CsrfReject => {
                    let response = "HTTP/1.1 400 Bad Request\r\n\r\nCSRF token mismatch";
                    let _ = stream.write_all(response.as_bytes());
                    continue;
                }
                CallbackOutcome::Code(code) => {
                    // Send success response
                    let response = r#"HTTP/1.1 200 OK
Content-Type: text/html

<!DOCTYPE html>
<html>
<head><title>Bitbucket CLI</title></head>
<body style="font-family: system-ui; text-align: center; padding: 50px;">
<h1>✅ Authentication Successful</h1>
<p>You can close this window and return to the terminal.</p>
</body>
</html>"#;
                    let _ = stream.write_all(response.as_bytes());

                    return Ok(AuthorizationCode::new(code));
                }
                CallbackOutcome::Failed(description) => {
                    // No authorization code: the provider denied the request
                    // or returned an error.
                    let response = r#"HTTP/1.1 200 OK
Content-Type: text/html

<!DOCTYPE html>
<html>
<head><title>Bitbucket CLI</title></head>
<body style="font-family: system-ui; text-align: center; padding: 50px;">
<h1>❌ Authentication Failed</h1>
<p>You can close this window and return to the terminal.</p>
</body>
</html>"#;
                    let _ = stream.write_all(response.as_bytes());

                    anyhow::bail!("Authentication failed: {}", description);
                }
            }
        }

        anyhow::bail!("Callback server closed unexpectedly")
    }

    /// Refresh an expired OAuth token
    pub async fn refresh_token(
        &self,
        auth_manager: &AuthManager,
        refresh_token: &str,
    ) -> Result<Credential> {
        let client = BasicClient::new(ClientId::new(self.client_id.clone()))
            .set_client_secret(ClientSecret::new(self.client_secret.clone()))
            .set_auth_uri(AuthUrl::new(BITBUCKET_AUTH_URL.to_string())?)
            .set_token_uri(TokenUrl::new(BITBUCKET_TOKEN_URL.to_string())?);

        let token_response = client
            .exchange_refresh_token(&RefreshToken::new(refresh_token.to_string()))
            .request_async(&async_http_client)
            .await
            .context("Failed to refresh token")?;

        let access_token = token_response.access_token().secret().to_string();
        let new_refresh_token = merged_refresh_token(
            token_response
                .refresh_token()
                .map(|t| t.secret().to_string()),
            refresh_token,
        );
        let expires_at = token_response
            .expires_in()
            .map(|d| chrono::Utc::now().timestamp() + d.as_secs() as i64);

        let credential = Credential::OAuth {
            access_token,
            refresh_token: Some(new_refresh_token),
            expires_at,
            client_id: Some(self.client_id.clone()),
            client_secret: Some(self.client_secret.clone()),
        };

        auth_manager.store_credentials(&credential)?;

        Ok(credential)
    }
}

/// Use the refresh token from the token response if present, otherwise keep
/// the old one (Bitbucket does not always return a new refresh token).
fn merged_refresh_token(new: Option<String>, old: &str) -> String {
    new.unwrap_or_else(|| old.to_string())
}

/// Result of interpreting the query parameters of an OAuth callback request.
#[derive(Debug, PartialEq, Eq)]
enum CallbackOutcome {
    /// State matched and an authorization code was returned.
    Code(String),
    /// State was missing or did not match the expected CSRF token.
    CsrfReject,
    /// State matched but no authorization code was returned; carries the
    /// failure description.
    Failed(String),
}

/// Decide how to handle an OAuth callback based on its query parameters.
///
/// A callback with a missing state is rejected exactly like a mismatched
/// one. When the state matches but no code is present, the failure
/// description prefers `error_description`, then `error`, then a generic
/// message.
fn interpret_callback(params: &[(String, String)], expected_state: &str) -> CallbackOutcome {
    let mut code = None;
    let mut state = None;
    let mut error = None;
    let mut error_description = None;

    for (key, value) in params {
        match key.as_str() {
            "code" => code = Some(value.clone()),
            "state" => state = Some(value.clone()),
            "error" => error = Some(value.clone()),
            "error_description" => error_description = Some(value.clone()),
            _ => {}
        }
    }

    match state {
        Some(ref state) if state == expected_state => {}
        _ => return CallbackOutcome::CsrfReject,
    }

    if let Some(code) = code {
        return CallbackOutcome::Code(code);
    }

    CallbackOutcome::Failed(
        error_description
            .or(error)
            .unwrap_or_else(|| "no authorization code returned".to_string()),
    )
}

#[cfg(test)]
mod tests {
    use super::{CallbackOutcome, interpret_callback, merged_refresh_token};

    #[test]
    fn new_refresh_token_replaces_old_one() {
        assert_eq!(
            merged_refresh_token(Some("new-token".to_string()), "old-token"),
            "new-token"
        );
    }

    #[test]
    fn old_refresh_token_kept_when_response_has_none() {
        assert_eq!(merged_refresh_token(None, "old-token"), "old-token");
    }

    fn params(pairs: &[(&str, &str)]) -> Vec<(String, String)> {
        pairs
            .iter()
            .map(|(key, value)| (key.to_string(), value.to_string()))
            .collect()
    }

    #[test]
    fn callback_with_missing_state_is_csrf_rejected() {
        let outcome = interpret_callback(&params(&[("code", "abc123")]), "expected-state");
        assert_eq!(outcome, CallbackOutcome::CsrfReject);
    }

    #[test]
    fn callback_with_wrong_state_is_csrf_rejected() {
        let outcome = interpret_callback(
            &params(&[("code", "abc123"), ("state", "wrong-state")]),
            "expected-state",
        );
        assert_eq!(outcome, CallbackOutcome::CsrfReject);
    }

    #[test]
    fn callback_with_matching_state_and_code_returns_code() {
        let outcome = interpret_callback(
            &params(&[("code", "abc123"), ("state", "expected-state")]),
            "expected-state",
        );
        assert_eq!(outcome, CallbackOutcome::Code("abc123".to_string()));
    }

    #[test]
    fn callback_error_description_used_when_no_code() {
        let outcome = interpret_callback(
            &params(&[
                ("state", "expected-state"),
                ("error", "access_denied"),
                ("error_description", "The user denied access"),
            ]),
            "expected-state",
        );
        assert_eq!(
            outcome,
            CallbackOutcome::Failed("The user denied access".to_string())
        );
    }

    #[test]
    fn callback_error_used_when_no_description() {
        let outcome = interpret_callback(
            &params(&[("state", "expected-state"), ("error", "access_denied")]),
            "expected-state",
        );
        assert_eq!(
            outcome,
            CallbackOutcome::Failed("access_denied".to_string())
        );
    }

    #[test]
    fn callback_without_code_or_error_reports_generic_failure() {
        let outcome = interpret_callback(&params(&[("state", "expected-state")]), "expected-state");
        assert_eq!(
            outcome,
            CallbackOutcome::Failed("no authorization code returned".to_string())
        );
    }
}