zitadel-tui 0.1.7

A terminal UI for managing Zitadel resources
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
use anyhow::Result;
use serde_json::Value;

use crate::{
    auth::{resolve_access_token, validate_login_session_token},
    cli::{AuthAction, AuthCommand, Cli},
    client::ZitadelClient,
    config::AppConfig,
    oidc, token_cache,
};

use super::shared::{resolved_host, resolved_host_or_cache};

pub async fn execute_auth_command(
    command: &AuthCommand,
    args: &Cli,
    config: &AppConfig,
) -> Result<Value> {
    match &command.action {
        AuthAction::Login(login_args) => {
            let host = resolved_host(args, config)?;
            let client_id = if let Some(id) = &login_args.client_id {
                id.clone()
            } else if let Some(id) = &config.device_client_id {
                id.clone()
            } else {
                let id = prompt_for_client_id()?;
                let mut updated = config.clone();
                updated.device_client_id = Some(id.clone());
                let _ = updated.save_to_canonical_path();
                id
            };

            let http = reqwest::Client::new();
            let auth_resp = oidc::device_authorize(&http, &host, &client_id).await?;

            eprintln!("\nOpen this URL in your browser:");
            eprintln!(
                "  {}",
                auth_resp
                    .verification_uri_complete
                    .as_deref()
                    .unwrap_or(&auth_resp.verification_uri)
            );
            eprintln!(
                "\nOr go to {} and enter code: {}\n",
                auth_resp.verification_uri, auth_resp.user_code
            );

            let mut interval = auth_resp.interval;
            let tokens = loop {
                tokio::time::sleep(std::time::Duration::from_secs(interval)).await;
                match oidc::poll_for_token(&http, &host, &client_id, &auth_resp.device_code).await {
                    Ok(tokens) => break tokens,
                    Err(oidc::PollError::Pending) => {
                        eprint!(".");
                    }
                    Err(oidc::PollError::SlowDown) => {
                        interval += 5;
                        eprint!(".");
                    }
                    Err(oidc::PollError::Fatal(error)) => return Err(error),
                }
            };
            eprintln!("\nAuthenticated.");

            persist_login_session(&http, &host, &client_id, tokens).await?;

            Ok(serde_json::json!({
                "status": "authenticated",
                "host": host,
                "token_cache": token_cache::TokenCache::path()?.display().to_string(),
            }))
        }
        AuthAction::Logout => {
            token_cache::TokenCache::clear()?;
            Ok(serde_json::json!({ "status": "logged out" }))
        }
        AuthAction::Status => {
            let host = resolved_host_or_cache(args, config)?;
            let http = reqwest::Client::new();
            let auth = resolve_access_token(
                &http,
                &host,
                args.token.clone(),
                args.service_account_file.clone(),
                config,
            )
            .await?;
            let (user_id, login_name) = if auth.is_oidc_session() {
                let userinfo = session_userinfo(&http, &host, &auth.token).await?;
                auth_status_userinfo_identity(&userinfo)
            } else {
                let client = ZitadelClient::new(host.clone(), auth.token)?;
                let me = client.whoami().await?;
                auth_status_api_identity(&me)
            };
            Ok(serde_json::json!({
                "host": host,
                "auth_source": auth.source,
                "user_id": user_id,
                "login_name": login_name,
            }))
        }
    }
}

async fn session_userinfo(http: &reqwest::Client, host: &str, access_token: &str) -> Result<Value> {
    let url = format!("{}/oidc/v1/userinfo", host.trim_end_matches('/'));
    let response = http
        .get(url)
        .bearer_auth(access_token)
        .header("Accept", "application/json")
        .send()
        .await?;
    let status = response.status();
    let bytes = response.bytes().await?;

    if !status.is_success() {
        anyhow::bail!("OIDC userinfo request failed ({status})");
    }

    serde_json::from_slice(&bytes)
        .map_err(|error| anyhow::anyhow!("failed to decode OIDC userinfo response: {error}"))
}

fn auth_status_api_identity(me: &Value) -> (Value, Value) {
    let user = me.get("user").unwrap_or(&Value::Null);
    let user_id = user
        .get("userId")
        .or_else(|| user.get("id"))
        .cloned()
        .unwrap_or(Value::Null);
    let login_name = user
        .get("preferredLoginName")
        .or_else(|| user.get("userName"))
        .or_else(|| user.get("loginName"))
        .cloned()
        .unwrap_or(Value::Null);

    (user_id, login_name)
}

fn auth_status_userinfo_identity(userinfo: &Value) -> (Value, Value) {
    let user_id = userinfo.get("sub").cloned().unwrap_or(Value::Null);
    let login_name = userinfo
        .get("preferred_username")
        .or_else(|| userinfo.get("email"))
        .or_else(|| userinfo.get("login_name"))
        .or_else(|| userinfo.get("name"))
        .cloned()
        .unwrap_or(Value::Null);

    (user_id, login_name)
}

fn prompt_for_client_id() -> Result<String> {
    eprint!("Zitadel native app client ID: ");
    let mut input = String::new();
    std::io::stdin().read_line(&mut input)?;
    let id = input.trim().to_string();
    if id.is_empty() {
        anyhow::bail!("client ID cannot be empty");
    }
    Ok(id)
}

pub async fn persist_login_session(
    http: &reqwest::Client,
    host: &str,
    client_id: &str,
    tokens: oidc::OidcTokens,
) -> Result<()> {
    validate_login_session_token(http, host, client_id, &tokens.access_token).await?;

    let cache = token_cache::TokenCache {
        access_token: tokens.access_token,
        refresh_token: tokens.refresh_token,
        expires_at: Some(oidc::expires_at_from_now(tokens.expires_in)),
        client_id: client_id.to_string(),
        host: host.to_string(),
    };
    cache.save()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cli::Cli;
    use clap::Parser;
    use mockito::Server;
    use std::{
        env, fs,
        time::{SystemTime, UNIX_EPOCH},
    };

    fn temp_cache_path() -> std::path::PathBuf {
        let unique = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .expect("System time is before UNIX epoch")
            .as_nanos();
        env::temp_dir().join(format!("zitadel-tui-main-test-tokens-{unique}.json"))
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test]
    async fn persist_login_session_saves_cache_after_successful_userinfo_probe() {
        let _guard = crate::test_support::env_lock();
        let cache_path = temp_cache_path();
        env::set_var("ZITADEL_TUI_TOKEN_CACHE", &cache_path);

        let mut server = Server::new_async().await;
        let userinfo_probe = server
            .mock("GET", "/oidc/v1/userinfo")
            .match_header("authorization", "Bearer header.payload.signature")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"sub":"u1","email":"admin@example.com"}"#)
            .create_async()
            .await;

        let http = reqwest::Client::new();
        persist_login_session(
            &http,
            &server.url(),
            "native-app-id",
            oidc::OidcTokens {
                access_token: "header.payload.signature".to_string(),
                refresh_token: Some("refresh-token".to_string()),
                expires_in: 3600,
            },
        )
        .await
        .unwrap();

        userinfo_probe.assert_async().await;
        let cache = crate::token_cache::TokenCache::load()
            .unwrap()
            .expect("cache entry");
        assert_eq!(cache.access_token, "header.payload.signature");
        assert_eq!(cache.refresh_token.as_deref(), Some("refresh-token"));
        assert_eq!(cache.client_id, "native-app-id");
        assert_eq!(cache.host, server.url());

        env::remove_var("ZITADEL_TUI_TOKEN_CACHE");
        let _ = fs::remove_file(cache_path);
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test]
    async fn persist_login_session_allows_userinfo_valid_jwt_when_auth_api_rejects_it() {
        let _guard = crate::test_support::env_lock();
        let cache_path = temp_cache_path();
        env::set_var("ZITADEL_TUI_TOKEN_CACHE", &cache_path);

        let mut server = Server::new_async().await;
        let userinfo_probe = server
            .mock("GET", "/oidc/v1/userinfo")
            .match_header("authorization", "Bearer header.payload.signature")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"sub":"355235054814759983","email":"dan.m.webb@gmail.com"}"#)
            .create_async()
            .await;

        let auth_api_probe = server
            .mock("GET", "/auth/v1/users/me")
            .match_header("authorization", "Bearer header.payload.signature")
            .with_status(403)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{
                    "code": 7,
                    "message": "authentication required",
                    "details": [{"id": "AUTHZ-Kl3p0"}]
                }"#,
            )
            .expect(0)
            .create_async()
            .await;

        let http = reqwest::Client::new();
        persist_login_session(
            &http,
            &server.url(),
            "native-app-id",
            oidc::OidcTokens {
                access_token: "header.payload.signature".to_string(),
                refresh_token: Some("refresh-token".to_string()),
                expires_in: 3600,
            },
        )
        .await
        .unwrap();

        userinfo_probe.assert_async().await;
        auth_api_probe.assert_async().await;
        assert!(crate::token_cache::TokenCache::load().unwrap().is_some());

        env::remove_var("ZITADEL_TUI_TOKEN_CACHE");
        let _ = fs::remove_file(cache_path);
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test]
    async fn persist_login_session_rejects_unusable_device_tokens_without_writing_cache() {
        let _guard = crate::test_support::env_lock();
        let cache_path = temp_cache_path();
        env::set_var("ZITADEL_TUI_TOKEN_CACHE", &cache_path);

        let http = reqwest::Client::new();
        let error = persist_login_session(
            &http,
            "https://zitadel.example.com",
            "native-app-id",
            oidc::OidcTokens {
                access_token: "opaque-token".to_string(),
                refresh_token: Some("refresh-token".to_string()),
                expires_in: 3600,
            },
        )
        .await
        .unwrap_err()
        .to_string();

        assert!(error.contains("JWT access tokens"));
        assert!(crate::token_cache::TokenCache::load().unwrap().is_none());

        env::remove_var("ZITADEL_TUI_TOKEN_CACHE");
        let _ = fs::remove_file(cache_path);
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test]
    async fn persist_login_session_rejects_userinfo_probe_failures_without_writing_cache() {
        let _guard = crate::test_support::env_lock();
        let cache_path = temp_cache_path();
        env::set_var("ZITADEL_TUI_TOKEN_CACHE", &cache_path);

        let mut server = Server::new_async().await;
        let userinfo_probe = server
            .mock("GET", "/oidc/v1/userinfo")
            .match_header("authorization", "Bearer header.payload.signature")
            .with_status(401)
            .with_header("content-type", "application/json")
            .with_body(r#"{"message":"bad token"}"#)
            .create_async()
            .await;

        let http = reqwest::Client::new();
        let error = persist_login_session(
            &http,
            &server.url(),
            "native-app-id",
            oidc::OidcTokens {
                access_token: "header.payload.signature".to_string(),
                refresh_token: Some("refresh-token".to_string()),
                expires_in: 3600,
            },
        )
        .await
        .unwrap_err()
        .to_string();

        userinfo_probe.assert_async().await;
        assert!(error.contains("OIDC userinfo validation failed"));
        assert!(crate::token_cache::TokenCache::load().unwrap().is_none());

        env::remove_var("ZITADEL_TUI_TOKEN_CACHE");
        let _ = fs::remove_file(cache_path);
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test]
    async fn auth_status_uses_valid_cached_session_tokens() {
        let _guard = crate::test_support::env_lock();
        let original_host = env::var("ZITADEL_URL").ok();
        let original_token = env::var("ZITADEL_TOKEN").ok();
        let original_sa = env::var("ZITADEL_SERVICE_ACCOUNT_FILE").ok();
        env::remove_var("ZITADEL_URL");
        env::remove_var("ZITADEL_TOKEN");
        env::remove_var("ZITADEL_SERVICE_ACCOUNT_FILE");
        let cache_path = temp_cache_path();
        env::set_var("ZITADEL_TUI_TOKEN_CACHE", &cache_path);

        let mut server = Server::new_async().await;
        let userinfo = server
            .mock("GET", "/oidc/v1/userinfo")
            .match_header("authorization", "Bearer header.payload.signature")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(r#"{"sub":"u-123","preferred_username":"admin@example.com"}"#)
            .create_async()
            .await;
        let auth_api = server
            .mock("GET", "/auth/v1/users/me")
            .match_header("authorization", "Bearer header.payload.signature")
            .expect(0)
            .create_async()
            .await;

        let now = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .unwrap()
            .as_secs();
        let cache = crate::token_cache::TokenCache {
            access_token: "header.payload.signature".to_string(),
            refresh_token: None,
            expires_at: Some(now + 3600),
            client_id: "native-app-id".to_string(),
            host: server.url(),
        };
        cache.save().unwrap();

        let args = Cli::parse_from(["zitadel-tui", "--once", "auth", "status"]);
        let command = match &args.command {
            Some(crate::cli::Command::Auth(command)) => command.clone(),
            other => panic!("unexpected command: {other:?}"),
        };

        let result = execute_auth_command(&command, &args, &AppConfig::default())
            .await
            .unwrap();

        userinfo.assert_async().await;
        auth_api.assert_async().await;
        assert_eq!(result["host"], server.url());
        assert_eq!(result["auth_source"], "session token");
        assert_eq!(result["user_id"], "u-123");
        assert_eq!(result["login_name"], "admin@example.com");

        env::remove_var("ZITADEL_TUI_TOKEN_CACHE");
        let _ = fs::remove_file(cache_path);
        if let Some(host) = original_host {
            env::set_var("ZITADEL_URL", host);
        }
        if let Some(token) = original_token {
            env::set_var("ZITADEL_TOKEN", token);
        }
        if let Some(sa) = original_sa {
            env::set_var("ZITADEL_SERVICE_ACCOUNT_FILE", sa);
        }
    }

    #[allow(clippy::await_holding_lock)]
    #[tokio::test]
    async fn auth_status_extracts_machine_user_id_from_id_field() {
        let _guard = crate::test_support::env_lock();
        let original_host = env::var("ZITADEL_URL").ok();
        let original_token = env::var("ZITADEL_TOKEN").ok();
        let original_service_account = env::var("ZITADEL_SERVICE_ACCOUNT_FILE").ok();
        env::remove_var("ZITADEL_TOKEN");
        env::remove_var("ZITADEL_SERVICE_ACCOUNT_FILE");

        let mut server = Server::new_async().await;
        let _whoami = server
            .mock("GET", "/auth/v1/users/me")
            .match_header("authorization", "Bearer service-account-token")
            .with_status(200)
            .with_header("content-type", "application/json")
            .with_body(
                r#"{"user":{"id":"355223427969778852","preferredLoginName":"zitadel-admin-sa","machine":{"name":"Admin"}}}"#,
            )
            .create_async()
            .await;

        env::set_var("ZITADEL_URL", server.url());

        let args = Cli::parse_from([
            "zitadel-tui",
            "--once",
            "--token",
            "service-account-token",
            "auth",
            "status",
        ]);
        let command = match &args.command {
            Some(crate::cli::Command::Auth(command)) => command.clone(),
            other => panic!("unexpected command: {other:?}"),
        };

        let result = execute_auth_command(&command, &args, &AppConfig::default())
            .await
            .unwrap();

        assert_eq!(result["host"], server.url());
        assert_eq!(result["auth_source"], "cli PAT");
        assert_eq!(result["user_id"], "355223427969778852");
        assert_eq!(result["login_name"], "zitadel-admin-sa");

        if let Some(host) = original_host {
            env::set_var("ZITADEL_URL", host);
        } else {
            env::remove_var("ZITADEL_URL");
        }
        if let Some(token) = original_token {
            env::set_var("ZITADEL_TOKEN", token);
        }
        if let Some(path) = original_service_account {
            env::set_var("ZITADEL_SERVICE_ACCOUNT_FILE", path);
        }
    }
}