bbcloud 0.22.0

Bitbucket Cloud CLI — open pull requests, read every comment, write replies, from the shell
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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
#![allow(clippy::unwrap_used)] // test code is exempt from the unwrap/expect ban

use assert_cmd::Command;
use predicates::str::contains;
use tempfile::tempdir;
use wiremock::matchers::{method, path};
use wiremock::{Mock, MockServer, ResponseTemplate};

/// The token must never appear in `bb auth status` output, in either format.
#[test]
fn auth_status_redacts_the_token() {
    for args in [vec!["auth", "status"], vec!["auth", "status", "--json"]] {
        let out = Command::cargo_bin("bb")
            .unwrap()
            .env("BB_NO_UPDATE_CHECK", "1")
            .args(&args)
            .env("BB_EMAIL", "dev@example.com")
            .env("BB_TOKEN", "ATATT3xFfGF0_super_secret_value")
            .env("BB_API_BASE", "http://127.0.0.1:1")
            .output()
            .unwrap();

        let combined = format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(
            !combined.contains("ATATT3xFfGF0"),
            "token leaked for {args:?}: {combined}"
        );
        assert!(
            !combined.contains("super_secret"),
            "token body leaked for {args:?}: {combined}"
        );
    }
}

#[test]
fn auth_status_shows_email_and_redacted_tail() {
    Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args(["auth", "status"])
        .env("BB_EMAIL", "dev@example.com")
        .env("BB_TOKEN", "ATATT3xFfGF0abcd")
        .env("BB_API_BASE", "http://127.0.0.1:1")
        .assert()
        .stdout(contains("dev@example.com"))
        .stdout(contains("****abcd"));
}

#[test]
fn auth_status_without_credentials_exits_two() {
    Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args(["auth", "status"])
        .env("BB_EMAIL", "")
        .env("BB_TOKEN", "")
        .env("BB_KEYRING_DISABLE", "1")
        .assert()
        .code(2)
        .stderr(contains("bb auth login"));
}

/// `--json` must emit parseable JSON on stdout, not the human success line.
#[test]
fn auth_logout_json_emits_parseable_json() {
    let out = Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args(["auth", "logout", "--json"])
        .env("BB_KEYRING_DISABLE", "1")
        .output()
        .unwrap();
    assert!(out.status.success());
    let stdout = String::from_utf8_lossy(&out.stdout);
    let _value: serde_json::Value = serde_json::from_str(stdout.trim())
        .unwrap_or_else(|e| panic!("stdout did not parse as JSON: {e}\nstdout: {stdout}"));
}

/// Non-interactive `auth login` without --email/--token-stdin must name both flags
/// rather than hang waiting on a prompt.
#[test]
fn auth_login_non_tty_names_required_flags() {
    let assert = Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args(["auth", "login"])
        .env("BB_API_BASE", "http://127.0.0.1:1")
        .write_stdin("")
        .assert()
        .failure();
    let output = assert.get_output();
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&output.stdout),
        String::from_utf8_lossy(&output.stderr)
    );
    assert!(combined.contains("--email"), "missing --email: {combined}");
    assert!(
        combined.contains("--token-stdin"),
        "missing --token-stdin: {combined}"
    );
}

/// The secret must never leak, in either human or --json mode, even on this error path.
#[test]
fn auth_login_non_tty_never_leaks_secret() {
    for args in [vec!["auth", "login"], vec!["auth", "login", "--json"]] {
        let out = Command::cargo_bin("bb")
            .unwrap()
            .env("BB_NO_UPDATE_CHECK", "1")
            .args(&args)
            .env("BB_API_BASE", "http://127.0.0.1:1")
            .write_stdin("super-secret-token-value")
            .output()
            .unwrap();
        let combined = format!(
            "{}{}",
            String::from_utf8_lossy(&out.stdout),
            String::from_utf8_lossy(&out.stderr)
        );
        assert!(
            !combined.contains("super-secret-token-value"),
            "secret leaked for {args:?}: {combined}"
        );
    }
}

#[test]
fn auth_help_mentions_api_token_not_app_password() {
    let out = Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args(["auth", "login", "--help"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout).to_lowercase();
    assert!(text.contains("api token"));
    assert!(!text.contains("app password"));
}

/// `login` with --email and --token-stdin never prompts, so the whole verify-then-store
/// path runs without a tty.
#[tokio::test]
async fn login_verifies_the_token_and_reports_the_account() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/user"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(serde_json::json!({"display_name": "Dev Person"})),
        )
        .mount(&server)
        .await;

    let out = Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args([
            "auth",
            "login",
            "--email",
            "dev@example.com",
            "--token-stdin",
        ])
        .env("BB_API_BASE", server.uri())
        .env("BB_KEYRING_DISABLE", "1")
        .env("NO_COLOR", "1")
        .env_remove("BB_EMAIL")
        .env_remove("BB_TOKEN")
        .write_stdin("ATATT3xFfGF0abcd")
        .output()
        .unwrap();

    assert!(out.status.success(), "login failed: {out:?}");
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(stdout.contains("Dev Person"), "no account name: {stdout}");
    assert!(stdout.contains("****abcd"), "no redacted tail: {stdout}");
    assert!(
        !stdout.contains("ATATT3xFfGF0abcd"),
        "token leaked: {stdout}"
    );
}

/// The same path in --json mode must emit pure JSON on stdout and no human lines.
#[tokio::test]
async fn login_json_emits_pure_json() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/user"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(serde_json::json!({"display_name": "Dev Person"})),
        )
        .mount(&server)
        .await;

    let out = Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args([
            "auth",
            "login",
            "--email",
            "dev@example.com",
            "--token-stdin",
            "--json",
        ])
        .env("BB_API_BASE", server.uri())
        .env("BB_KEYRING_DISABLE", "1")
        .env("NO_COLOR", "1")
        .env_remove("BB_EMAIL")
        .env_remove("BB_TOKEN")
        .write_stdin("ATATT3xFfGF0abcd")
        .output()
        .unwrap();

    assert!(out.status.success(), "login failed: {out:?}");
    let stdout = String::from_utf8_lossy(&out.stdout);
    let value: serde_json::Value = serde_json::from_str(stdout.trim())
        .unwrap_or_else(|e| panic!("stdout was not pure JSON: {e}\nstdout: {stdout}"));
    assert_eq!(value["account"], "Dev Person");
    assert_eq!(value["email"], "dev@example.com");
    assert_eq!(value["token"], "****abcd");
}

/// A value that is not an email address is rejected before any network call.
#[test]
fn login_rejects_an_email_without_an_at_sign() {
    Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args(["auth", "login", "--email", "not-an-email", "--token-stdin"])
        .env("BB_API_BASE", "http://127.0.0.1:1")
        .env("BB_KEYRING_DISABLE", "1")
        .env("NO_COLOR", "1")
        .env_remove("BB_EMAIL")
        .env_remove("BB_TOKEN")
        .write_stdin("some-token")
        .assert()
        .failure()
        .stderr(contains("atlassian account email"));
}

/// A leftover plaintext credential file from the PHP-era CLI must be called out on logout.
#[test]
fn logout_warns_about_a_legacy_plaintext_credential_file() {
    let home = tempdir().unwrap();
    std::fs::write(
        home.path().join(".bitbucket-rest-cli-config.json"),
        "{\"token\":\"whatever\"}",
    )
    .unwrap();

    Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args(["auth", "logout"])
        .env("HOME", home.path())
        .env("BB_KEYRING_DISABLE", "1")
        .env("NO_COLOR", "1")
        .assert()
        .success()
        .stderr(contains("legacy plaintext credential file"));
}

/// A failing identity check must not fail the command — the account is simply unknown.
#[tokio::test]
async fn status_reports_an_unverified_account_when_the_identity_check_fails() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/user"))
        .respond_with(ResponseTemplate::new(500))
        .mount(&server)
        .await;

    let out = Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args(["auth", "status", "--json"])
        .env("BB_EMAIL", "dev@example.com")
        .env("BB_TOKEN", "ATATT3xFfGF0abcd")
        .env("BB_API_BASE", server.uri())
        .env("BB_KEYRING_DISABLE", "1")
        .output()
        .unwrap();

    assert!(out.status.success(), "status failed: {out:?}");
    let stdout = String::from_utf8_lossy(&out.stdout);
    let value: serde_json::Value = serde_json::from_str(stdout.trim()).unwrap();
    assert!(
        value["account"].is_null(),
        "expected a null account, got {value}"
    );
}

/// Onboarding: a user who is about to be prompted has to be told where to create
/// the token and which scopes to grant, otherwise verification fails and they
/// cannot guess which of Bitbucket's scopes this tool wanted.
#[test]
fn login_prints_the_token_url_and_every_required_scope() {
    let out = Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args(["auth", "login"])
        .env("BB_API_BASE", "http://127.0.0.1:1")
        .env("BB_KEYRING_DISABLE", "1")
        .env("NO_COLOR", "1")
        .env_remove("BB_EMAIL")
        .env_remove("BB_TOKEN")
        .write_stdin("")
        .output()
        .unwrap();

    assert_eq!(
        out.status.code(),
        Some(1),
        "expected the non-interactive config error: {out:?}"
    );
    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        stdout.contains("https://id.atlassian.com/manage-profile/security/api-tokens"),
        "no token url: {stdout}"
    );
    for (scope, _) in bb_cli::commands::auth::SCOPES {
        assert!(stdout.contains(scope), "scope {scope} missing: {stdout}");
    }
    assert!(
        stdout.contains("Create API token with scopes"),
        "no scoped-token instruction: {stdout}"
    );
}

/// The walkthrough is for someone who will type values. `--email` with
/// `--token-stdin` prompts for nothing, so on a CI runner the lines would be noise
/// in the captured log.
#[tokio::test]
async fn login_with_both_values_supplied_prints_no_walkthrough() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/user"))
        .respond_with(
            ResponseTemplate::new(200)
                .set_body_json(serde_json::json!({"display_name": "Dev Person"})),
        )
        .mount(&server)
        .await;

    let out = Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args([
            "auth",
            "login",
            "--email",
            "dev@example.com",
            "--token-stdin",
        ])
        .env("BB_API_BASE", server.uri())
        .env("BB_KEYRING_DISABLE", "1")
        .env("NO_COLOR", "1")
        .env_remove("BB_EMAIL")
        .env_remove("BB_TOKEN")
        .write_stdin("ATATT3xFfGF0abcd")
        .output()
        .unwrap();

    let stdout = String::from_utf8_lossy(&out.stdout);
    assert!(
        !stdout.contains("Create API token with scopes"),
        "walkthrough printed on the non-interactive path: {stdout}"
    );
}

/// `--help` carries the same guidance, because `--email`/`--token-stdin` skips the
/// interactive walkthrough entirely. Driven off `SCOPES`, so the clap `long_about`
/// cannot drift away from the list the walkthrough prints.
#[test]
fn auth_login_help_lists_the_required_scopes() {
    let out = Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args(["auth", "login", "--help"])
        .output()
        .unwrap();
    let text = String::from_utf8_lossy(&out.stdout);
    assert!(text.contains("id.atlassian.com"), "no token url: {text}");
    for (scope, _) in bb_cli::commands::auth::SCOPES {
        assert!(text.contains(scope), "scope {scope} missing: {text}");
    }
}

/// A 403 on the verification call means the token exists but lacks
/// `read:user:bitbucket`. Saying so beats the generic scope wording `check()` emits.
#[tokio::test]
async fn login_names_the_missing_user_scope_on_a_403() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/user"))
        .respond_with(
            ResponseTemplate::new(403)
                .set_body_json(serde_json::json!({"error": {"message": "Forbidden"}})),
        )
        .mount(&server)
        .await;

    let out = Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args([
            "auth",
            "login",
            "--email",
            "dev@example.com",
            "--token-stdin",
        ])
        .env("BB_API_BASE", server.uri())
        .env("BB_KEYRING_DISABLE", "1")
        .env("NO_COLOR", "1")
        .env_remove("BB_EMAIL")
        .env_remove("BB_TOKEN")
        .write_stdin("ATATT3xFfGF0abcd")
        .output()
        .unwrap();

    assert!(!out.status.success(), "403 must fail login: {out:?}");
    let stderr = String::from_utf8_lossy(&out.stderr);
    assert!(
        stderr.contains("read:user:bitbucket"),
        "no scope hint: {stderr}"
    );
    let combined = format!("{}{stderr}", String::from_utf8_lossy(&out.stdout));
    assert!(
        !combined.contains("ATATT3xFfGF0abcd"),
        "token leaked: {combined}"
    );
}

/// A 401 means the pair itself was rejected — the hint must point at the email and
/// the token, not at scopes, and must not print the secret.
#[tokio::test]
async fn login_explains_a_rejected_email_and_token_pair() {
    let server = MockServer::start().await;
    Mock::given(method("GET"))
        .and(path("/user"))
        .respond_with(ResponseTemplate::new(401))
        .mount(&server)
        .await;

    let out = Command::cargo_bin("bb")
        .unwrap()
        .env("BB_NO_UPDATE_CHECK", "1")
        .args([
            "auth",
            "login",
            "--email",
            "dev@example.com",
            "--token-stdin",
        ])
        .env("BB_API_BASE", server.uri())
        .env("BB_KEYRING_DISABLE", "1")
        .env("NO_COLOR", "1")
        .env_remove("BB_EMAIL")
        .env_remove("BB_TOKEN")
        .write_stdin("ATATT3xFfGF0abcd")
        .output()
        .unwrap();

    assert_eq!(out.status.code(), Some(2), "401 must exit 2: {out:?}");
    let combined = format!(
        "{}{}",
        String::from_utf8_lossy(&out.stdout),
        String::from_utf8_lossy(&out.stderr)
    );
    assert!(
        combined.contains("atlassian account email"),
        "no email hint: {combined}"
    );
    assert!(
        !combined.contains("ATATT3xFfGF0abcd"),
        "token leaked: {combined}"
    );
}

/// The README's scope table and `SCOPES` are two hand-maintained lists of the
/// same facts, and they drifted: the table gained `read:project:bitbucket` and
/// `admin:repository:bitbucket` when `repo create` and `project list` shipped,
/// while the login walkthrough kept printing four scopes. Someone following
/// `bb auth login` then minted a token that 403s on the first `repo create`.
///
/// Every other scope test iterates `SCOPES`, so all of them stayed green through
/// that drift — they can only prove the walkthrough prints what the constant
/// holds. This one is the cross-check: it parses the README table and asserts
/// the two sets are equal, so adding a scope to either place alone fails here.
#[test]
fn the_readme_scope_table_matches_the_login_walkthrough() {
    let readme = include_str!("../README.md");
    let documented: Vec<&str> = readme
        .lines()
        .skip_while(|l| !l.starts_with("### Token scopes"))
        .take_while(|l| !l.starts_with("### CI"))
        .filter_map(|l| l.strip_prefix("| `"))
        .filter_map(|rest| rest.split('`').next())
        .collect();

    assert!(
        !documented.is_empty(),
        "found no scope rows — the README's `### Token scopes` table moved or changed shape"
    );

    let printed: Vec<&str> = bb_cli::commands::auth::SCOPES
        .iter()
        .map(|(s, _)| *s)
        .collect();

    for scope in &documented {
        assert!(
            printed.contains(scope),
            "README documents {scope} but `bb auth login` never tells anyone to grant it"
        );
    }
    for scope in &printed {
        assert!(
            documented.contains(scope),
            "`bb auth login` asks for {scope} but the README scope table does not list it"
        );
    }
}