boxlite-cli 0.10.5

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
//! `boxlite auth login` — top-level dispatcher.
//!
//! Three concrete flows, all sharing the same `Profile` storage:
//!
//! | `--method`  | Backed by                          |
//! |-------------|------------------------------------|
//! | `api-key`   | [`super::api_key::run`]            |
//! | `browser`   | [`super::oidc::auth_code::run`]    |
//! | `device`    | [`super::oidc::device_code::run`]  |
//!
//! When `--method` is omitted we infer it. The inference is split into two
//! helpers — `resolve_target` (which URL + IdP settings to use) and
//! `should_use_device_flow` (browser vs device when both look viable) —
//! both flagged for the user to refine per the plan's §A and §B.

use std::io::IsTerminal;

use anyhow::{Context, Result, anyhow, bail};
use clap::{Args, ValueEnum};
use dialoguer::{Select, theme::ColorfulTheme};

use super::api_key;
use super::oidc::{self, DiscoveryOverrides, OidcConfig, OidcTokens, discovery};
use crate::credentials::{self, CredentialStore, Profile};
use crate::defaults::LOCAL_SERVE_URL;

const URL_ENV: &str = "BOXLITE_REST_URL";

#[derive(Args, Debug, Clone)]
pub struct LoginArgs {
    /// Server URL. Defaults to `BOXLITE_REST_URL`, the selected profile's URL,
    /// then `LOCAL_SERVE_URL` (matching `boxlite serve`).
    #[arg(
        long,
        value_parser = clap::builder::NonEmptyStringValueParser::new()
    )]
    pub url: Option<String>,

    /// Read a long-lived API key from stdin (one line). The flag takes no
    /// value, so the secret never appears on argv. Forces `--method api-key`.
    #[arg(long)]
    pub api_key_stdin: bool,

    /// Which login flow to use. Defaults to `api-key` for `--api-key-stdin`
    /// and a TTY prompt otherwise. On a non-TTY stdin we silently default
    /// to `api-key` so CI scripts keep working.
    #[arg(long, value_enum)]
    pub method: Option<Method>,

    /// Skip the browser; use Device Code (RFC 8628) instead. Useful on
    /// remote / SSH sessions where a callback URL is unreachable.
    /// Implies `--method device`.
    #[arg(long, conflicts_with_all = ["api_key_stdin"])]
    pub no_browser: bool,

    /// OIDC issuer URL. Overrides what `GET /api/config` returns. Useful
    /// for self-hosted Dex instances where the discovery is wrong.
    #[arg(long)]
    pub issuer: Option<String>,

    /// OIDC client_id. Overrides what `GET /api/config` returns.
    #[arg(long)]
    pub client_id: Option<String>,

    /// OIDC audience (Auth0 requires it; Dex tolerates `None`).
    #[arg(long)]
    pub audience: Option<String>,

    /// Local port for the browser-flow callback (`http://127.0.0.1:<PORT>/callback`).
    /// Must match an entry in the IdP's allow-list **byte-for-byte** — a
    /// different port produces the same "callback URL mismatch" failure
    /// as no entry at all. Defaults to 5555.
    #[arg(long, value_parser = clap::value_parser!(u16).range(1..))]
    pub callback_port: Option<u16>,
}

#[derive(ValueEnum, Debug, Clone, Copy, PartialEq, Eq)]
#[value(rename_all = "kebab-case")]
pub enum Method {
    /// Static API key — paste / stdin.
    ApiKey,
    /// OIDC Authorization Code with PKCE; opens a browser.
    Browser,
    /// OIDC Device Code (RFC 8628); headless / SSH friendly.
    Device,
}

pub async fn run(args: LoginArgs, profile_name: &str, store: &CredentialStore) -> Result<()> {
    let method = resolve_method(&args)?;
    let stored_url = store.load_named(profile_name)?.map(|profile| profile.url);
    let url = resolve_target(&args, stored_url.as_deref())?;

    match method {
        Method::ApiKey => api_key::run(Some(&url), args.api_key_stdin, profile_name, store).await,
        Method::Browser => run_browser(&args, &url, profile_name, store).await,
        Method::Device => run_device(&args, &url, profile_name, store).await,
    }
}

/// Browser-based OIDC login.
async fn run_browser(
    args: &LoginArgs,
    url: &str,
    profile_name: &str,
    store: &CredentialStore,
) -> Result<()> {
    let http = discovery::http_client()?;
    let overrides = overrides_from_args(args);
    let cfg = discovery::resolve_config(url, &overrides, &http).await?;
    let port = args
        .callback_port
        .unwrap_or(oidc::auth_code::DEFAULT_CALLBACK_PORT);
    let tokens = oidc::auth_code::run(&cfg, &http, port).await?;
    persist_oidc(url, profile_name, &cfg, tokens, store).await
}

/// Device-code OIDC login.
async fn run_device(
    args: &LoginArgs,
    url: &str,
    profile_name: &str,
    store: &CredentialStore,
) -> Result<()> {
    let http = discovery::http_client()?;
    let overrides = overrides_from_args(args);
    let cfg = discovery::resolve_config(url, &overrides, &http).await?;
    let tokens = oidc::device_code::run(&cfg, &http).await?;
    persist_oidc(url, profile_name, &cfg, tokens, store).await
}

/// Common tail: write tokens into a Profile, save under `profile_name`,
/// confirm with the server. Sharing the helper keeps the on-disk shape in
/// one place so the auth-code and device-code paths cannot drift.
async fn persist_oidc(
    url: &str,
    profile_name: &str,
    cfg: &OidcConfig,
    tokens: OidcTokens,
    store: &CredentialStore,
) -> Result<()> {
    // Confirm against `/v1/me` BEFORE saving — same contract as the API-key
    // flow. A working access token that the server rejects is the kind of
    // misconfiguration we want surfaced loudly.
    let mut profile = Profile {
        url: url.to_string(),
        ..Profile::default()
    };
    oidc::refresh::apply_tokens(&mut profile, cfg, tokens);

    let principal = verify_principal(&profile).await?;
    // Cache the principal's routing-slot value so subsequent
    // box-scoped commands substitute it into `/v1/<prefix>/...`.
    // `None` means the deployment doesn't use a routing slot;
    // URL builder skips the segment (`/v1/boxes/...`).
    profile.path_prefix = principal.path_prefix.clone();
    store
        .save_named(profile_name, &profile)
        .context("saving credentials")?;

    let who = principal.email.as_deref().unwrap_or(principal.sub.as_str());
    match principal.path_prefix.as_deref() {
        Some(path_prefix) => println!("Logged in as {} (path prefix: {})", who, path_prefix),
        None => println!("Logged in as {} (the server returned no path prefix)", who),
    }
    Ok(())
}

/// Hit `/v1/me` with the freshly minted access token. Token field is read
/// once via `expose_secret` at the BoxliteRestOptions boundary.
async fn verify_principal(profile: &Profile) -> Result<boxlite::Principal> {
    use boxlite::BoxliteRuntime;
    let opts = credentials::into_rest_options(profile.clone());
    let runtime = BoxliteRuntime::rest(opts)
        .map_err(|e| anyhow!("failed to construct REST runtime: {}", e))?;
    let auth = runtime
        .auth()
        .map_err(|e| anyhow!("failed to construct REST runtime: {}", e))?;
    auth.whoami()
        .await
        .map_err(|err| anyhow!("server rejected new OIDC session: {err}"))
}

fn overrides_from_args(args: &LoginArgs) -> DiscoveryOverrides {
    DiscoveryOverrides {
        issuer: args.issuer.clone(),
        client_id: args.client_id.clone(),
        audience: args.audience.clone(),
    }
}

/// Pick which of the three flows to run.
///
/// Explicit flags always win. When the user hasn't expressed a preference
/// we read the environment: a non-TTY stdin → `api-key` (CI), `--no-browser`
/// → `device`, otherwise prompt the user with a `dialoguer::Select`.
fn resolve_method(args: &LoginArgs) -> Result<Method> {
    let method = if args.api_key_stdin {
        Method::ApiKey
    } else if let Some(m) = args.method {
        // Honor the explicit choice even on a TTY.
        m
    } else if args.no_browser {
        Method::Device
    } else if !std::io::stdin().is_terminal() {
        // Piped stdin: keep `echo $KEY | boxlite auth login --api-key-stdin`
        // working when callers forget the flag — never block on a prompt.
        Method::ApiKey
    } else {
        prompt_method()?
    };
    validate_method_options(args, method)?;
    Ok(method)
}

fn validate_method_options(args: &LoginArgs, method: Method) -> Result<()> {
    if args.api_key_stdin && args.method.is_some_and(|method| method != Method::ApiKey) {
        bail!("--api-key-stdin cannot be combined with a non-api-key --method");
    }
    if args.no_browser && args.method == Some(Method::Browser) {
        bail!("--no-browser cannot be combined with --method browser");
    }
    if method == Method::ApiKey {
        if args.no_browser {
            bail!("--no-browser cannot be used with --method api-key");
        }
        for (flag, is_set) in [
            ("--issuer", args.issuer.is_some()),
            ("--client-id", args.client_id.is_some()),
            ("--audience", args.audience.is_some()),
        ] {
            if is_set {
                bail!("{flag} applies only to browser or device login");
            }
        }
    }
    if method != Method::Browser && args.callback_port.is_some() {
        bail!("--callback-port applies only to browser login");
    }
    Ok(())
}

/// Interactive picker for the three flows. Lives behind a TTY check so
/// non-interactive callers never hit it.
fn prompt_method() -> Result<Method> {
    let items = [
        "API key (paste)",
        "Browser (OIDC)",
        "Device code (headless / SSH)",
    ];
    let chosen = Select::with_theme(&ColorfulTheme::default())
        .with_prompt("How do you want to log in?")
        .items(&items)
        .default(0)
        .interact()
        .map_err(|e| anyhow!("reading login method choice: {e}"))?;
    Ok(match chosen {
        0 => Method::ApiKey,
        1 => {
            if should_use_device_flow() {
                eprintln!(
                    "no browser available (headless environment detected); using device code"
                );
                Method::Device
            } else {
                Method::Browser
            }
        }
        2 => Method::Device,
        _ => unreachable!("dialoguer::Select returns an index in 0..items.len()"),
    })
}

// =============================================================================
// Decision A — see plan §A.
//
// `resolve_target` decides which server URL the login flow points at. Today
// the precedence is **`--url` > `BOXLITE_REST_URL` env > stored profile's
// `url` > `LOCAL_SERVE_URL` default**, matching what the API-key flow has
// always done. This is a safe baseline — if you have feelings about whether
// `--profile cloud --url http://localhost:8100` should override stored OR
// merge, or whether `BOXLITE_REST_URL` should beat a saved cloud profile
// during a CI run, this is where to encode them.
//
// Things to weigh (do not implement here — change this function instead):
//   - Should `--url` ALWAYS win, including over the active profile's URL?
//     (current answer: yes — flag > anything else.)
//   - Should `BOXLITE_REST_URL` override a stored OIDC profile? (current
//     answer: yes — env beats file. Same precedence the API-key path used.)
//   - Should `--profile` without `--url` reuse the stored URL? (current
//     answer: yes — that's the whole point of saved profiles.)
//   - Anything that's missing? E.g., refusing to mix `--profile cloud` with
//     `--url http://localhost:8100` because the URL clearly belongs to a
//     different profile.
// =============================================================================
fn resolve_target(args: &LoginArgs, stored_url: Option<&str>) -> Result<String> {
    if let Some(url) = args.url.as_deref() {
        return Ok(url.to_string());
    }
    match std::env::var(URL_ENV) {
        Ok(env_url) if !env_url.is_empty() => return Ok(env_url),
        Ok(_) | Err(std::env::VarError::NotPresent) => {}
        Err(std::env::VarError::NotUnicode(_)) => {
            bail!("{URL_ENV} must contain valid UTF-8")
        }
    }
    if let Some(stored_url) = stored_url.filter(|url| !url.is_empty()) {
        return Ok(stored_url.to_string());
    }
    Ok(LOCAL_SERVE_URL.to_string())
}

// =============================================================================
// Decision B — see plan §B.
//
// `should_use_device_flow` decides when to auto-fall-back from browser to
// device code. Today this is **conservative**: only `$SSH_CONNECTION` set
// triggers fallback. That avoids the worst failure mode (`ssh user@host` →
// browser opens nothing → silent hang) without surprising desktop users.
//
// Things to weigh (do not implement here — change this function instead):
//   - `$DISPLAY` unset on Linux + no `$WAYLAND_DISPLAY` → headless?
//     (current answer: NO, because tmux/screen on a workstation can both
//     be unset and a browser still works.)
//   - macOS / Windows: never auto-fall-back; if a user wants device flow
//     they pass `--no-browser`. (current answer matches.)
//   - `webbrowser::open` failure: we already print the URL — should we
//     additionally retry as device? (current answer: NO, would silently
//     change the user's chosen flow.)
//   - `ssh -X` (X forwarding): `$SSH_CONNECTION` is still set even though a
//     browser would work. Cost of false-positive (device flow) is "you
//     typed a code unnecessarily"; cost of false-negative (no fallback) is
//     "the CLI hangs". This is the judgment call.
// =============================================================================
fn should_use_device_flow() -> bool {
    std::env::var_os("SSH_CONNECTION").is_some()
}

#[cfg(test)]
mod tests {
    use super::*;

    /// `--api-key-stdin` selects the API-key flow when no redundant method is
    /// supplied. Contradictory explicit methods are rejected separately.
    #[test]
    fn api_key_stdin_selects_api_key_method() {
        let args = LoginArgs {
            url: None,
            api_key_stdin: true,
            method: None,
            no_browser: false,
            issuer: None,
            client_id: None,
            audience: None,
            callback_port: None,
        };
        assert_eq!(resolve_method(&args).unwrap(), Method::ApiKey);
    }

    /// An explicit browser method contradicts `--no-browser`; neither flag is
    /// silently allowed to override the other.
    #[test]
    fn no_browser_rejects_browser_method() {
        let args = LoginArgs {
            url: None,
            api_key_stdin: false,
            method: Some(Method::Browser),
            no_browser: true,
            issuer: None,
            client_id: None,
            audience: None,
            callback_port: None,
        };
        assert!(resolve_method(&args).is_err());
    }

    #[test]
    fn login_rejects_options_the_selected_method_cannot_use() {
        let cases = [
            LoginArgs {
                url: None,
                api_key_stdin: false,
                method: Some(Method::ApiKey),
                no_browser: true,
                issuer: None,
                client_id: None,
                audience: None,
                callback_port: None,
            },
            LoginArgs {
                url: None,
                api_key_stdin: false,
                method: Some(Method::ApiKey),
                no_browser: false,
                issuer: Some("https://issuer.example.test".to_string()),
                client_id: None,
                audience: None,
                callback_port: None,
            },
            LoginArgs {
                url: None,
                api_key_stdin: false,
                method: Some(Method::Device),
                no_browser: false,
                issuer: None,
                client_id: None,
                audience: None,
                callback_port: Some(5555),
            },
            LoginArgs {
                url: None,
                api_key_stdin: true,
                method: Some(Method::Device),
                no_browser: false,
                issuer: None,
                client_id: None,
                audience: None,
                callback_port: None,
            },
            LoginArgs {
                url: None,
                api_key_stdin: true,
                method: Some(Method::Browser),
                no_browser: false,
                issuer: None,
                client_id: None,
                audience: None,
                callback_port: None,
            },
        ];

        for args in cases {
            assert!(resolve_method(&args).is_err(), "accepted {args:?}");
        }
    }

    /// Today's `resolve_target` falls back to the local serve URL — locks
    /// in that default so a future plan-§A change can prove it's
    /// intentionally different.
    #[test]
    fn resolve_target_defaults_to_local_serve() {
        // SAFETY: tests run on a fresh process by default; no env vars are
        // shared.
        // Note: if a parallel test sets BOXLITE_REST_URL we'd be wrong
        // here, but no other test currently mutates that var.
        unsafe {
            std::env::remove_var(URL_ENV);
        }
        let args = LoginArgs {
            url: None,
            api_key_stdin: false,
            method: None,
            no_browser: false,
            issuer: None,
            client_id: None,
            audience: None,
            callback_port: None,
        };
        assert_eq!(resolve_target(&args, None).unwrap(), LOCAL_SERVE_URL);
    }

    #[test]
    fn resolve_target_reuses_the_selected_profiles_url() {
        let args = LoginArgs {
            url: None,
            api_key_stdin: true,
            method: None,
            no_browser: false,
            issuer: None,
            client_id: None,
            audience: None,
            callback_port: None,
        };

        assert_eq!(
            resolve_target(&args, Some("https://cloud.example.test")).unwrap(),
            "https://cloud.example.test"
        );
    }
}