mecha10-auth 0.9.0

Authentication services for Mecha10 - shared between CLI and launcher
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
//! Shared auth command orchestration
//!
//! Both `mecha10` (dev machine CLI) and `mecha10-launcher` (robot daemon) expose
//! `auth login` / `auth logout` / `auth whoami` subcommands. They share the exact same
//! underlying [`AuthService`] and [`CredentialsService`], so the orchestration logic
//! (check login state, run the device code flow, save/delete credentials, print a
//! formatted result) lives here once instead of being duplicated per-binary.
//!
//! Each binary keeps its own hint text (e.g. `mecha10 auth logout` vs
//! `mecha10-launcher auth logout`) by passing its own binary name in.

use crate::credentials::CredentialsService;
use crate::service::AuthService;
use crate::types::Credentials;
use crate::{display_device_code_instructions, get_auth_url, open_browser};
use anyhow::Result;

/// Run the device code flow to completion and persist the resulting credentials.
///
/// Shared by [`handle_login`] and [`ensure_authenticated_interactive`] so the device-code-flow +
/// save-credentials mechanics live in exactly one place, rather than being copied alongside
/// `mecha10-launcher`'s `SetupWizard::ensure_authenticated` (`packages/launcher-service/src/setup.rs`).
async fn run_and_save_device_code_flow(
    auth_service: &AuthService,
    credentials_service: &CredentialsService,
) -> Result<Credentials> {
    let credentials = auth_service
        .run_device_code_flow(|device_code| {
            display_device_code_instructions(device_code);
            open_browser(device_code.browser_url());
        })
        .await?;

    credentials_service.save(&credentials)?;

    Ok(credentials)
}

/// Run the login command.
///
/// 1. If already logged in, print current user and a hint to log out first.
/// 2. Otherwise run the device code flow, save the resulting credentials, and print a summary.
///
/// `binary_name` is used to render binary-specific hint text (e.g. `mecha10` vs `mecha10-launcher`).
pub async fn handle_login(auth_url: Option<String>, binary_name: &str) -> Result<()> {
    let credentials_service = CredentialsService::new();

    if credentials_service.is_logged_in() {
        if let Ok(Some((_, email, name))) = credentials_service.get_user_info() {
            let display_name = name.unwrap_or_else(|| email.clone());
            println!();
            println!("Already logged in as {}", display_name);
            println!();
            println!("Run `{} auth logout` to log out first.", binary_name);
            println!();
            return Ok(());
        }
    }

    let auth_service = match auth_url {
        Some(url) => AuthService::with_auth_url(url),
        None => AuthService::with_auth_url(get_auth_url()),
    };

    println!();
    println!("Logging in to mecha10...");
    println!();

    let credentials = run_and_save_device_code_flow(&auth_service, &credentials_service).await?;

    let display_name = credentials.name.as_ref().unwrap_or(&credentials.email);

    println!();
    println!("Successfully logged in as {}", display_name);
    println!();
    println!(
        "Credentials saved to {}",
        credentials_service.credentials_path().display()
    );
    println!();

    Ok(())
}

/// Run the logout command.
///
/// Removes stored credentials from `~/.mecha10/credentials.json` and prints a summary.
pub fn handle_logout() -> Result<()> {
    let credentials_service = CredentialsService::new();

    if !credentials_service.is_logged_in() {
        println!();
        println!("Not currently logged in.");
        println!();
        return Ok(());
    }

    let user_info = credentials_service.get_user_info()?;

    credentials_service.delete()?;

    println!();
    if let Some((_, email, name)) = user_info {
        let display_name = name.unwrap_or(email);
        println!("Logged out from {}", display_name);
    } else {
        println!("Logged out successfully");
    }
    println!();

    Ok(())
}

/// Run the whoami command.
///
/// Displays current authentication status and user info.
///
/// `binary_name` is used to render binary-specific hint text (e.g. `mecha10` vs `mecha10-launcher`).
pub fn handle_whoami(verbose: bool, binary_name: &str) -> Result<()> {
    let credentials_service = CredentialsService::new();

    println!();

    match credentials_service.load()? {
        Some(creds) if creds.is_valid() => {
            let display_name = creds.name.as_ref().unwrap_or(&creds.email);

            println!("Logged in as: {}", display_name);
            println!("Email: {}", creds.email);
            println!("User ID: {}", creds.user_id);

            if verbose {
                println!("API Key: {}", creds.masked_api_key());
            }

            println!(
                "Authenticated: {}",
                creds.authenticated_at.format("%Y-%m-%d %H:%M:%S UTC")
            );
        }
        Some(_) => {
            println!("Credentials found but invalid");
            println!();
            println!("Run `{} auth login` to authenticate", binary_name);
        }
        None => {
            println!("Not logged in");
            println!();
            println!("Run `{} auth login` to authenticate", binary_name);
        }
    }

    println!();

    Ok(())
}

/// One-line authentication status summary, e.g. for use in `config show` output.
///
/// Reuses the same [`CredentialsService`] load/validity check as [`handle_whoami`], just
/// condensed to a single line rather than the full multi-line whoami printout.
pub fn auth_status_line() -> Result<String> {
    let credentials_service = CredentialsService::new();

    let line = match credentials_service.load()? {
        Some(creds) if creds.is_valid() => {
            let display_name = creds.name.as_ref().unwrap_or(&creds.email);
            format!("Logged in as {} ({})", display_name, creds.email)
        }
        Some(_) => "Credentials found but invalid".to_string(),
        None => "Not logged in".to_string(),
    };

    Ok(line)
}

/// Ensure the caller is authenticated, running the interactive device code login flow if not.
///
/// If valid credentials are already on disk (the same "valid" check `CredentialsService`'s
/// `is_logged_in`/`load` + `Credentials::is_valid` already define), returns them immediately
/// with no output. Otherwise walks the user through the same device-code flow `handle_login`
/// uses - and `mecha10-launcher`'s `SetupWizard::ensure_authenticated` mirrors - then saves the
/// result, so callers that need auth can prompt for it in place instead of just telling the user
/// to go run `mecha10 auth login` themselves.
pub async fn ensure_authenticated_interactive(credentials_service: &CredentialsService) -> Result<Credentials> {
    if let Ok(Some(creds)) = credentials_service.load() {
        if creds.is_valid() {
            return Ok(creds);
        }
    }

    println!();
    println!("You're not logged in. Let's get you logged in.");
    println!();

    let auth_service = AuthService::with_auth_url(get_auth_url());
    let credentials = run_and_save_device_code_flow(&auth_service, credentials_service).await?;

    let display_name = credentials.name.as_ref().unwrap_or(&credentials.email);
    println!();
    println!("Successfully logged in as {}", display_name);
    println!();

    Ok(credentials)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::credentials::CredentialsService;
    use crate::types::Credentials;
    use crate::DEFAULT_AUTH_URL;
    use chrono::Utc;
    use serial_test::serial;
    use tempfile::TempDir;

    struct HomeGuard {
        _temp_dir: TempDir,
        original_home: Option<String>,
    }

    impl HomeGuard {
        fn new() -> Self {
            let temp_dir = TempDir::new().unwrap();
            let original_home = std::env::var("HOME").ok();
            std::env::set_var("HOME", temp_dir.path());
            Self {
                _temp_dir: temp_dir,
                original_home,
            }
        }
    }

    impl Drop for HomeGuard {
        fn drop(&mut self) {
            match &self.original_home {
                Some(home) => std::env::set_var("HOME", home),
                None => std::env::remove_var("HOME"),
            }
        }
    }

    fn valid_credentials() -> Credentials {
        Credentials {
            api_key: "mecha_test123abc456def".to_string(),
            user_id: "usr_test123".to_string(),
            email: "test@example.com".to_string(),
            name: Some("Test User".to_string()),
            authenticated_at: Utc::now(),
            auth_url: DEFAULT_AUTH_URL.to_string(),
        }
    }

    fn invalid_credentials() -> Credentials {
        Credentials {
            api_key: "".to_string(),
            user_id: "usr_test123".to_string(),
            email: "invalid@example.com".to_string(),
            name: None,
            authenticated_at: Utc::now(),
            auth_url: DEFAULT_AUTH_URL.to_string(),
        }
    }

    #[tokio::test]
    #[serial]
    async fn handle_login_short_circuits_when_already_logged_in() {
        let _guard = HomeGuard::new();
        CredentialsService::new().save(&valid_credentials()).unwrap();

        let result = handle_login(None, "mecha10").await;
        assert!(result.is_ok());

        assert!(CredentialsService::new().is_logged_in());
    }

    #[tokio::test]
    #[serial]
    async fn handle_login_propagates_network_error_when_device_code_request_fails() {
        let _guard = HomeGuard::new();
        let unreachable_url = "http://127.0.0.1:1".to_string();

        let result = handle_login(Some(unreachable_url), "mecha10").await;
        assert!(result.is_err());

        assert!(!CredentialsService::new().is_logged_in());
    }

    #[tokio::test]
    #[serial]
    async fn handle_login_uses_env_var_auth_url_when_none_provided() {
        let _guard = HomeGuard::new();
        std::env::set_var(crate::AUTH_URL_ENV_VAR, "http://127.0.0.1:1");

        let result = handle_login(None, "mecha10").await;

        std::env::remove_var(crate::AUTH_URL_ENV_VAR);

        assert!(result.is_err());
    }

    #[test]
    #[serial]
    fn handle_logout_is_noop_when_not_logged_in() {
        let _guard = HomeGuard::new();

        let result = handle_logout();
        assert!(result.is_ok());
    }

    #[test]
    #[serial]
    fn handle_logout_deletes_credentials_when_logged_in() {
        let _guard = HomeGuard::new();
        let service = CredentialsService::new();
        service.save(&valid_credentials()).unwrap();
        assert!(service.is_logged_in());

        let result = handle_logout();
        assert!(result.is_ok());

        assert!(!CredentialsService::new().is_logged_in());
        assert!(CredentialsService::new().load().unwrap().is_none());
    }

    #[test]
    #[serial]
    fn handle_logout_succeeds_even_with_invalid_stored_credentials() {
        let _guard = HomeGuard::new();
        let service = CredentialsService::new();
        service.save(&invalid_credentials()).unwrap();

        let result = handle_logout();
        assert!(result.is_ok());
    }

    #[test]
    #[serial]
    fn handle_whoami_succeeds_when_not_logged_in() {
        let _guard = HomeGuard::new();
        let result = handle_whoami(false, "mecha10");
        assert!(result.is_ok());
    }

    #[test]
    #[serial]
    fn handle_whoami_succeeds_with_valid_credentials_and_verbose() {
        let _guard = HomeGuard::new();
        CredentialsService::new().save(&valid_credentials()).unwrap();

        let result = handle_whoami(true, "mecha10");
        assert!(result.is_ok());
    }

    #[test]
    #[serial]
    fn handle_whoami_succeeds_with_invalid_credentials() {
        let _guard = HomeGuard::new();
        CredentialsService::new().save(&invalid_credentials()).unwrap();

        let result = handle_whoami(false, "mecha10");
        assert!(result.is_ok());
    }

    #[test]
    #[serial]
    fn handle_whoami_propagates_corrupt_credentials_error() {
        let _guard = HomeGuard::new();
        let service = CredentialsService::new();
        std::fs::create_dir_all(service.credentials_path().parent().unwrap()).unwrap();
        std::fs::write(service.credentials_path(), "not valid json").unwrap();

        let result = handle_whoami(false, "mecha10");
        assert!(result.is_err());
    }

    #[test]
    #[serial]
    fn auth_status_line_reports_not_logged_in() {
        let _guard = HomeGuard::new();
        let line = auth_status_line().unwrap();
        assert_eq!(line, "Not logged in");
    }

    #[test]
    #[serial]
    fn auth_status_line_reports_logged_in_user() {
        let _guard = HomeGuard::new();
        CredentialsService::new().save(&valid_credentials()).unwrap();

        let line = auth_status_line().unwrap();
        assert_eq!(line, "Logged in as Test User (test@example.com)");
    }

    #[test]
    #[serial]
    fn auth_status_line_falls_back_to_email_without_name() {
        let _guard = HomeGuard::new();
        let mut creds = valid_credentials();
        creds.name = None;
        CredentialsService::new().save(&creds).unwrap();

        let line = auth_status_line().unwrap();
        assert_eq!(line, "Logged in as test@example.com (test@example.com)");
    }

    #[test]
    #[serial]
    fn auth_status_line_reports_invalid_credentials() {
        let _guard = HomeGuard::new();
        CredentialsService::new().save(&invalid_credentials()).unwrap();

        let line = auth_status_line().unwrap();
        assert_eq!(line, "Credentials found but invalid");
    }

    #[tokio::test]
    async fn ensure_authenticated_interactive_short_circuits_when_already_logged_in() {
        let temp_dir = TempDir::new().unwrap();
        let service = CredentialsService::with_path(temp_dir.path().join("credentials.json"));
        let creds = valid_credentials();
        service.save(&creds).unwrap();

        let result = ensure_authenticated_interactive(&service).await;

        let returned = result.unwrap();
        assert_eq!(returned.api_key, creds.api_key);
        assert_eq!(returned.email, creds.email);
    }

    #[tokio::test]
    #[serial]
    async fn ensure_authenticated_interactive_runs_flow_when_invalid_credentials_stored() {
        let temp_dir = TempDir::new().unwrap();
        let service = CredentialsService::with_path(temp_dir.path().join("credentials.json"));
        service.save(&invalid_credentials()).unwrap();

        std::env::set_var(crate::AUTH_URL_ENV_VAR, "http://127.0.0.1:1");
        let result = ensure_authenticated_interactive(&service).await;
        std::env::remove_var(crate::AUTH_URL_ENV_VAR);

        assert!(result.is_err());
    }

    #[tokio::test]
    #[serial]
    async fn ensure_authenticated_interactive_propagates_network_error_when_not_logged_in() {
        let temp_dir = TempDir::new().unwrap();
        let service = CredentialsService::with_path(temp_dir.path().join("credentials.json"));

        std::env::set_var(crate::AUTH_URL_ENV_VAR, "http://127.0.0.1:1");
        let result = ensure_authenticated_interactive(&service).await;
        std::env::remove_var(crate::AUTH_URL_ENV_VAR);

        assert!(result.is_err());
        assert!(service.load().unwrap().is_none());
    }
}