boxlite-cli 0.10.7

Command-line interface for BoxLite container runtime
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
//! Integration tests for `boxlite auth {login,whoami,status}` against a
//! std-only stub HTTP server (zero new deps). Covers the Phase-1 identity
//! flow: `login` validates via `GET /v1/me` and prints who you are; falls
//! back to `GET /v1/boxes` (empty-prefix shape) when `/v1/me` is 404
//! (zero regression); 401 fails without writing credentials; `whoami`
//! reflects identity.

use std::io::{BufRead, BufReader, Read, Write};
use std::net::TcpListener;
use std::sync::{Arc, Mutex};
use std::time::Duration;

use assert_cmd::Command;
use predicates::prelude::*;
use tempfile::TempDir;

struct RecordedRequest {
    method: String,
    path: String,
    body: String,
}

/// HTTP/1.1 stub that records each request before invoking the handler.
/// One request per connection (`Connection: close`); a daemon thread serves
/// sequential connections for the test's lifetime.
struct Stub {
    port: u16,
    requests: Arc<Mutex<Vec<RecordedRequest>>>,
}

impl Stub {
    fn start<H>(handler: H) -> Self
    where
        H: Fn(&str, &str) -> (u16, String) + Send + Sync + 'static,
    {
        Self::with_url(move |_| move |method: &str, path: &str, _body: &str| handler(method, path))
    }

    fn with_url<F, H>(factory: F) -> Self
    where
        F: FnOnce(String) -> H,
        H: Fn(&str, &str, &str) -> (u16, String) + Send + Sync + 'static,
    {
        let listener = TcpListener::bind("127.0.0.1:0").expect("bind ephemeral port");
        let port = listener.local_addr().unwrap().port();
        let handler = Arc::new(factory(format!("http://127.0.0.1:{port}")));
        let requests = Arc::new(Mutex::new(Vec::new()));
        let recorded_requests = Arc::clone(&requests);
        std::thread::spawn(move || {
            for stream in listener.incoming() {
                let Ok(mut stream) = stream else { continue };
                let Ok(peek) = stream.try_clone() else {
                    continue;
                };
                let mut reader = BufReader::new(peek);

                let mut request_line = String::new();
                if reader.read_line(&mut request_line).is_err() {
                    continue;
                }
                // Consume the form body as well as headers for OAuth requests.
                let mut content_length = 0;
                loop {
                    let mut line = String::new();
                    match reader.read_line(&mut line) {
                        Ok(0) => break,
                        Ok(_) if line == "\r\n" || line == "\n" => break,
                        Ok(_) => {
                            if let Some(value) =
                                line.to_ascii_lowercase().strip_prefix("content-length:")
                            {
                                content_length = value.trim().parse::<usize>().unwrap();
                            }
                        }
                        Err(_) => break,
                    }
                }

                let mut parts = request_line.split_whitespace();
                let method = parts.next().unwrap_or("");
                let raw_path = parts.next().unwrap_or("");
                let path = raw_path.split('?').next().unwrap_or(raw_path);

                let mut request_body = vec![0; content_length];
                reader.read_exact(&mut request_body).unwrap();
                let request_body = String::from_utf8(request_body).unwrap();
                recorded_requests.lock().unwrap().push(RecordedRequest {
                    method: method.to_string(),
                    path: path.to_string(),
                    body: request_body.clone(),
                });
                let (status, body) = handler(method, path, &request_body);
                let reason = match status {
                    200 => "OK",
                    401 => "Unauthorized",
                    404 => "Not Found",
                    _ => "Status",
                };
                let _ = write!(
                    stream,
                    "HTTP/1.1 {status} {reason}\r\nContent-Type: application/json\r\n\
                     Content-Length: {len}\r\nConnection: close\r\n\r\n{body}",
                    len = body.len(),
                );
                let _ = stream.flush();
            }
        });
        Self { port, requests }
    }

    fn url(&self) -> String {
        format!("http://127.0.0.1:{}", self.port)
    }
}

const PRINCIPAL_JSON: &str = r#"{"sub":"usr_1","principal_type":"user","email":"dev@acme.test","display_name":"Dev","path_prefix":"acme","scopes":["box:read","box:write"]}"#;
const NOT_FOUND_JSON: &str =
    r#"{"error":{"message":"no /v1/me here","type":"NotFoundError","code":404}}"#;
const AUTH_ERR_JSON: &str = r#"{"error":{"message":"bad key","type":"AuthError","code":401}}"#;
const EMPTY_BOXES_JSON: &str = r#"{"boxes":[]}"#;

/// `boxlite auth …` command with hermetic env: isolated `BOXLITE_HOME`, and
/// host `BOXLITE_API_KEY`/`BOXLITE_REST_URL` removed so they can't leak in.
fn auth_cmd(home: &TempDir) -> Command {
    let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("boxlite"));
    cmd.env("BOXLITE_HOME", home.path())
        .env_remove("BOXLITE_API_KEY")
        .env_remove("BOXLITE_REST_URL")
        .timeout(Duration::from_secs(30));
    cmd
}

fn creds_path(home: &TempDir) -> std::path::PathBuf {
    home.path().join("credentials.toml")
}

fn write_api_key_profile(home: &TempDir, url: &str) {
    std::fs::write(
        creds_path(home),
        format!("[profiles.default]\nurl = {url:?}\napi_key = \"k_test\"\n"),
    )
    .unwrap();
}

#[test]
fn login_success_prints_identity_and_saves() {
    let stub = Stub::start(|_m, path| match path {
        "/v1/me" => (200, PRINCIPAL_JSON.to_string()),
        _ => (404, NOT_FOUND_JSON.to_string()),
    });
    let home = TempDir::new().unwrap();

    auth_cmd(&home)
        .args(["auth", "login", "--url", &stub.url(), "--api-key-stdin"])
        .write_stdin("k_test\n")
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Logged in as dev@acme.test (path prefix: acme)",
        ));

    assert!(
        creds_path(&home).exists(),
        "credentials.toml must be written"
    );
}

#[test]
fn login_falls_back_to_boxes_when_me_404() {
    // When /v1/me is 404 (older server), the client falls back to the
    // cheapest authenticated call: GET /v1/boxes. Stored profile has
    // no prefix at this point (`/v1/me` failed so nothing to cache),
    // so the URL builder uses the empty-prefix shape `/v1/boxes`.
    let stub = Stub::start(|_m, path| {
        if path == "/v1/me" {
            (404, NOT_FOUND_JSON.to_string())
        } else if path.starts_with("/v1/boxes") {
            (200, EMPTY_BOXES_JSON.to_string())
        } else {
            (404, NOT_FOUND_JSON.to_string())
        }
    });
    let home = TempDir::new().unwrap();

    auth_cmd(&home)
        .args(["auth", "login", "--url", &stub.url(), "--api-key-stdin"])
        .write_stdin("k_test\n")
        .assert()
        .success()
        .stdout(predicate::str::contains("Logged in (API key)"));

    assert!(
        creds_path(&home).exists(),
        "fallback validation must still save credentials"
    );
}

#[test]
fn login_fails_and_does_not_save_on_401() {
    let stub = Stub::start(|_m, _path| (401, AUTH_ERR_JSON.to_string()));
    let home = TempDir::new().unwrap();

    auth_cmd(&home)
        .args(["auth", "login", "--url", &stub.url(), "--api-key-stdin"])
        .write_stdin("bad_key\n")
        .assert()
        .failure()
        .stderr(predicate::str::contains("authentication failed"));

    assert!(
        !creds_path(&home).exists(),
        "credentials must NOT be written on auth failure"
    );
}

#[test]
fn whoami_prints_identity_after_login() {
    let stub = Stub::start(|_m, path| match path {
        "/v1/me" => (200, PRINCIPAL_JSON.to_string()),
        _ => (404, NOT_FOUND_JSON.to_string()),
    });
    let home = TempDir::new().unwrap();

    auth_cmd(&home)
        .args(["auth", "login", "--url", &stub.url(), "--api-key-stdin"])
        .write_stdin("k_test\n")
        .assert()
        .success();

    auth_cmd(&home)
        .args(["auth", "whoami"])
        .assert()
        .success()
        .stdout(
            predicate::str::contains("Logged in as:    dev@acme.test")
                .and(predicate::str::contains("Path prefix:     acme")),
        );
}

#[test]
fn whoami_not_logged_in_with_no_credentials() {
    let home = TempDir::new().unwrap();
    auth_cmd(&home)
        .args(["auth", "whoami"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Not logged in"));
}

#[test]
fn status_is_offline_and_reports_source() {
    // No creds → "Not logged in." with no network at all (no stub running).
    let home = TempDir::new().unwrap();
    auth_cmd(&home)
        .args(["auth", "status"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Not logged in"));
}

#[test]
fn status_applies_an_explicit_url_to_a_stored_profile() {
    let home = TempDir::new().unwrap();
    write_api_key_profile(&home, "https://stored.example.test");

    auth_cmd(&home)
        .args(["auth", "status", "--url", "https://override.example.test"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Logged in to:    https://override.example.test",
        ));
}

#[test]
fn whoami_applies_an_explicit_url_to_a_stored_profile() {
    let stub = Stub::start(|_m, path| match path {
        "/v1/me" => (200, PRINCIPAL_JSON.to_string()),
        _ => (404, NOT_FOUND_JSON.to_string()),
    });
    let home = TempDir::new().unwrap();
    write_api_key_profile(&home, "http://127.0.0.1:1");

    auth_cmd(&home)
        .args(["auth", "whoami", "--url", &stub.url()])
        .assert()
        .success()
        .stdout(predicate::str::contains(format!(
            "Server:          {}",
            stub.url()
        )));
}

#[test]
fn malformed_credentials_never_fall_back_to_the_local_runtime() {
    let home = TempDir::new().unwrap();
    std::fs::write(creds_path(&home), "[profiles.default\n").unwrap();

    auth_cmd(&home)
        .args(["list"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("parsing credentials file"));
}

#[test]
fn logout_reports_a_malformed_credential_store() {
    let home = TempDir::new().unwrap();
    std::fs::write(creds_path(&home), "[profiles.default\n").unwrap();

    auth_cmd(&home)
        .args(["auth", "logout", "--yes"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("parsing credentials file"));
}

/// Regression: `BOXLITE_API_KEY=""` (an empty-but-set env var, easy to
/// produce from `export BOXLITE_API_KEY=$VAR_THAT_IS_UNSET`) used to make
/// `auth status` report "Logged in (env)" while every actual authenticated
/// call would fall back to the stored profile — `whoami` and the runtime
/// in cli.rs treat empty as "not set". The three views must agree.
#[test]
fn status_treats_empty_env_api_key_as_not_logged_in() {
    let home = TempDir::new().unwrap();
    let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("boxlite"));
    cmd.env("BOXLITE_HOME", home.path())
        .env("BOXLITE_API_KEY", "") // set-but-empty
        .env_remove("BOXLITE_REST_URL")
        .timeout(Duration::from_secs(30));
    cmd.args(["auth", "status"])
        .assert()
        .success()
        .stdout(predicate::str::contains("Not logged in"));
}

#[test]
fn status_treats_an_empty_url_environment_value_as_unset() {
    let home = TempDir::new().unwrap();
    let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("boxlite"));
    cmd.env("BOXLITE_HOME", home.path())
        .env("BOXLITE_API_KEY", "k_test")
        .env("BOXLITE_REST_URL", "")
        .timeout(Duration::from_secs(30));
    cmd.args(["auth", "status"])
        .assert()
        .success()
        .stdout(predicate::str::contains(
            "Logged in to:    http://localhost:8100",
        ));
}

#[test]
fn relative_home_environment_value_is_rejected_for_auth_too() {
    let working = TempDir::new().unwrap();

    let mut cmd = Command::new(assert_cmd::cargo::cargo_bin!("boxlite"));
    cmd.current_dir(working.path())
        .env("BOXLITE_HOME", "relative-home")
        .env_remove("BOXLITE_API_KEY")
        .env_remove("BOXLITE_REST_URL")
        .timeout(Duration::from_secs(30));
    cmd.args(["auth", "status"])
        .assert()
        .failure()
        .stderr(predicate::str::contains("must be an absolute path"));
}

fn device_stub(
    advertised: bool,
    device_error: Option<&'static str>,
    token_error: Option<&'static str>,
) -> Stub {
    device_stub_with_refresh(advertised, device_error, token_error, false)
}

fn device_stub_with_refresh(
    advertised: bool,
    device_error: Option<&'static str>,
    token_error: Option<&'static str>,
    refresh: bool,
) -> Stub {
    Stub::with_url(move |base| {
        move |method, path, body: &str| {
            let device_path = if advertised {
                "/oauth/device/code"
            } else {
                "/device/code"
            };
            match (method, path) {
                ("GET", "/config") => (
                    200,
                    serde_json::json!({"oidc": {
                        "issuer": format!("{base}/"), "clientId": "cli-test", "audience": "test-api"
                    }})
                    .to_string(),
                ),
                ("GET", "/.well-known/openid-configuration") => {
                    let mut metadata = serde_json::json!({
                        "issuer": format!("{base}/"), "authorization_endpoint": format!("{base}/authorize"),
                        "token_endpoint": format!("{base}/oauth/token"), "jwks_uri": format!("{base}/jwks"),
                        "response_types_supported": ["code"], "subject_types_supported": ["public"],
                        "id_token_signing_alg_values_supported": ["RS256"]
                    });
                    if advertised {
                        metadata["device_authorization_endpoint"] =
                            format!("{base}{device_path}").into();
                    }
                    (200, metadata.to_string())
                }
                ("GET", "/jwks") => (200, r#"{"keys":[]}"#.into()),
                ("POST", p) if p == device_path => {
                    if let Some(error) = device_error {
                        (403, serde_json::json!({"error": error, "error_description": "SENSITIVE_SERVER_DESCRIPTION"}).to_string())
                    } else {
                        (200, serde_json::json!({"device_code": "PRIVATE_DEVICE_CODE", "user_code": "TEST-1234",
                        "verification_uri": format!("{base}/activate"), "expires_in": 30, "interval": 1}).to_string())
                    }
                }
                ("POST", "/oauth/token") => {
                    if let Some(error) = token_error {
                        (400, serde_json::json!({"error": error, "error_description": "SENSITIVE_SERVER_DESCRIPTION"}).to_string())
                    } else {
                        let refreshing = body.contains("grant_type=refresh_token");
                        if refreshing && !body.contains("refresh_token=PRIVATE_REFRESH_TOKEN") {
                            return (400, r#"{"error":"invalid_grant"}"#.into());
                        }
                        (200, serde_json::json!({
                            "access_token": if refreshing { "ROTATED_ACCESS_TOKEN" } else { "PRIVATE_ACCESS_TOKEN" },
                            "refresh_token": if refreshing { "ROTATED_REFRESH_TOKEN" } else { "PRIVATE_REFRESH_TOKEN" },
                            "token_type": "Bearer", "expires_in": if refresh && !refreshing { 1 } else { 3600 }
                        }).to_string())
                    }
                }
                ("GET", "/v1/me") => (200, PRINCIPAL_JSON.into()),
                _ => (404, "wrong device endpoint".into()),
            }
        }
    })
}

#[test]
fn device_login_uses_discovered_endpoint_and_persists_session() {
    let stub = device_stub(true, None, None);
    let home = TempDir::new().unwrap();
    auth_cmd(&home)
        .args(["auth", "login", "--url", &stub.url(), "--method", "device"])
        .assert()
        .success()
        .stderr(predicate::str::contains("TEST-1234"));
    let credentials = std::fs::read_to_string(creds_path(&home)).unwrap();
    assert!(credentials.contains("PRIVATE_REFRESH_TOKEN"));
    auth_cmd(&home)
        .args(["auth", "whoami"])
        .assert()
        .success()
        .stdout(predicate::str::contains("dev@acme.test"));
}

#[test]
fn device_login_request_encodes_public_client_once() {
    // Legacy discovery lets this reach the request-body check on pre-fix code.
    let stub = device_stub(false, None, None);
    let home = TempDir::new().unwrap();
    auth_cmd(&home)
        .args(["auth", "login", "--url", &stub.url(), "--method", "device"])
        .assert()
        .success();
    let requests = stub.requests.lock().unwrap();
    let request = requests
        .iter()
        .find(|request| request.method == "POST" && request.path == "/device/code")
        .expect("CLI must request device authorization");
    let form: Vec<_> = url::form_urlencoded::parse(request.body.as_bytes()).collect();
    let values = |key: &str| {
        form.iter()
            .filter(|(name, _)| name == key)
            .map(|(_, value)| value.as_ref())
            .collect::<Vec<_>>()
    };
    assert_eq!(values("client_id"), ["cli-test"]);
    assert_eq!(values("audience"), ["test-api"]);
    let scopes = values("scope");
    assert_eq!(scopes.len(), 1);
    assert!(
        scopes[0]
            .split_whitespace()
            .any(|scope| scope == "offline_access")
    );
    assert!(values("client_secret").is_empty());
}

#[test]
fn device_login_keeps_legacy_dex_endpoint_when_not_advertised() {
    let stub = device_stub(false, None, None);
    let home = TempDir::new().unwrap();
    auth_cmd(&home)
        .args(["auth", "login", "--url", &stub.url(), "--method", "device"])
        .assert()
        .success();
}

#[test]
fn device_login_reports_client_and_grant_checks_without_server_description() {
    let stub = device_stub(true, Some("unauthorized_client"), None);
    let home = TempDir::new().unwrap();
    auth_cmd(&home)
        .args(["auth", "login", "--url", &stub.url(), "--method", "device"])
        .assert()
        .failure()
        .stderr(
            predicate::str::contains("unauthorized_client")
                .and(predicate::str::contains("public CLI client ID"))
                .and(predicate::str::contains("Device Code grant"))
                .and(predicate::str::contains("SENSITIVE_SERVER_DESCRIPTION").not()),
        );
    assert!(!creds_path(&home).exists());
}

#[test]
fn device_login_denied_or_expired_does_not_save_or_leak_secrets() {
    for error in ["access_denied", "expired_token"] {
        let stub = device_stub(true, None, Some(error));
        let home = TempDir::new().unwrap();
        auth_cmd(&home)
            .args(["auth", "login", "--url", &stub.url(), "--method", "device"])
            .assert()
            .failure()
            .stderr(
                predicate::str::contains(error)
                    .and(predicate::str::contains("PRIVATE_DEVICE_CODE").not())
                    .and(predicate::str::contains("SENSITIVE_SERVER_DESCRIPTION").not()),
            );
        assert!(!creds_path(&home).exists());
    }
}

#[cfg(unix)]
#[test]
fn device_login_ctrl_c_cancels_without_saving() {
    let stub = device_stub(false, None, Some("authorization_pending"));
    let home = TempDir::new().unwrap();
    let mut child = std::process::Command::new(assert_cmd::cargo::cargo_bin!("boxlite"))
        .env("BOXLITE_HOME", home.path())
        .env_remove("BOXLITE_API_KEY")
        .env_remove("BOXLITE_REST_URL")
        .args(["auth", "login", "--url", &stub.url(), "--method", "device"])
        .stderr(std::process::Stdio::piped())
        .stdout(std::process::Stdio::null())
        .spawn()
        .unwrap();
    let mut stderr = BufReader::new(child.stderr.take().unwrap());
    let mut output = String::new();
    loop {
        let mut line = String::new();
        assert!(
            stderr.read_line(&mut line).unwrap() > 0,
            "login ended before instructions: {output}"
        );
        output.push_str(&line);
        if line.contains("TEST-1234") {
            break;
        }
    }
    // Signal the actual CLI, after its user instructions have crossed stderr.
    std::thread::sleep(Duration::from_millis(100));
    assert!(
        std::process::Command::new("kill")
            .args(["-INT", &child.id().to_string()])
            .status()
            .unwrap()
            .success()
    );
    stderr.read_to_string(&mut output).unwrap();
    assert!(!child.wait().unwrap().success());
    assert!(output.contains("device login cancelled"), "{output}");
    assert!(!creds_path(&home).exists());
}

#[test]
fn device_session_refreshes_and_persists_rotated_tokens() {
    let stub = device_stub_with_refresh(true, None, None, true);
    let home = TempDir::new().unwrap();
    auth_cmd(&home)
        .args(["auth", "login", "--url", &stub.url(), "--method", "device"])
        .assert()
        .success();
    auth_cmd(&home)
        .args(["auth", "whoami"])
        .assert()
        .success()
        .stdout(predicate::str::contains("dev@acme.test"));
    let credentials = std::fs::read_to_string(creds_path(&home)).unwrap();
    assert!(credentials.contains("ROTATED_ACCESS_TOKEN"));
    assert!(credentials.contains("ROTATED_REFRESH_TOKEN"));
    assert!(!credentials.contains("PRIVATE_REFRESH_TOKEN"));
}