cufflink-cli 0.17.0

CLI for the Cufflink CRUD microservice platform — deploy, init, and manage services
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
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
use crate::config::CliConfig;
use cufflink_types::policy::{PolicyKey, PolicyMode};
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;

/// Keycloak device authorization response
#[derive(Deserialize)]
struct DeviceAuthResponse {
    device_code: String,
    user_code: String,
    verification_uri: Option<String>,
    verification_uri_complete: Option<String>,
    expires_in: u64,
    interval: Option<u64>,
}

/// Keycloak token response (device code + refresh flows)
#[derive(Deserialize)]
struct TokenResponse {
    access_token: String,
    refresh_token: Option<String>,
}

/// Keycloak error response during polling
#[derive(Deserialize)]
struct TokenErrorResponse {
    error: String,
}

/// Cached platform tokens, keyed by api_url
#[derive(Debug, Serialize, Deserialize, Default)]
struct PlatformTokensFile(HashMap<String, PlatformTokens>);

#[derive(Debug, Serialize, Deserialize, Clone)]
struct PlatformTokens {
    access_token: String,
    refresh_token: String,
    keycloak_url: String,
    realm: String,
    client_id: String,
}

fn tokens_path() -> PathBuf {
    let home = std::env::var("HOME").unwrap_or_else(|_| ".".into());
    PathBuf::from(home)
        .join(".config")
        .join("cufflink")
        .join("platform-tokens.json")
}

fn load_tokens(api_url: &str) -> Option<PlatformTokens> {
    let path = tokens_path();
    let json = std::fs::read_to_string(path).ok()?;
    let file: PlatformTokensFile = serde_json::from_str(&json).ok()?;
    file.0.get(api_url).cloned()
}

fn save_tokens(api_url: &str, tokens: &PlatformTokens) {
    let path = tokens_path();
    let mut file: PlatformTokensFile = std::fs::read_to_string(&path)
        .ok()
        .and_then(|json| serde_json::from_str(&json).ok())
        .unwrap_or_default();

    file.0.insert(api_url.to_string(), tokens.clone());

    if let Some(parent) = path.parent() {
        let _ = std::fs::create_dir_all(parent);
    }
    if let Ok(json) = serde_json::to_string_pretty(&file) {
        let _ = std::fs::write(&path, json);
        #[cfg(unix)]
        {
            use std::os::unix::fs::PermissionsExt;
            let _ = std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600));
        }
    }
}

/// Try to refresh the access token using a stored refresh token.
async fn try_refresh(tokens: &PlatformTokens) -> Option<TokenResponse> {
    let client = reqwest::Client::new();
    let token_url = format!(
        "{}/realms/{}/protocol/openid-connect/token",
        tokens.keycloak_url, tokens.realm
    );

    let resp = client
        .post(&token_url)
        .form(&[
            ("grant_type", "refresh_token"),
            ("refresh_token", &tokens.refresh_token),
            ("client_id", &tokens.client_id),
        ])
        .send()
        .await
        .ok()?;

    if resp.status().is_success() {
        resp.json::<TokenResponse>().await.ok()
    } else {
        None
    }
}

/// Discover auth config from the platform API.
/// Returns (keycloak_url, realm, client_id).
async fn discover_auth_config(api_url: &str) -> Option<(String, String, String)> {
    #[derive(Deserialize)]
    struct AuthConfig {
        keycloak_url: String,
        realm: String,
        cli_client_id: Option<String>,
        client_id: Option<String>,
    }

    let client = reqwest::Client::new();
    let resp = client
        .get(format!("{}/api/auth/config", api_url))
        .send()
        .await
        .ok()?;

    if resp.status().is_success() {
        let config: AuthConfig = resp.json().await.ok()?;
        let client_id = config
            .cli_client_id
            .or(config.client_id)
            .unwrap_or_else(|| "cufflink-cli".into());
        Some((config.keycloak_url, config.realm, client_id))
    } else {
        None
    }
}

/// Get a valid platform access token — uses cached refresh token if available,
/// falls back to device code auth only when needed.
async fn platform_auth(config: &CliConfig) -> eyre::Result<String> {
    // Discover auth config from the platform API, fall back to local config/defaults
    let (keycloak_url, realm, client_id) =
        if let Some(discovered) = discover_auth_config(&config.api_url).await {
            discovered
        } else {
            (
                config
                    .keycloak_url
                    .clone()
                    .unwrap_or_else(|| "http://localhost:8180".to_string()),
                config
                    .keycloak_realm
                    .clone()
                    .unwrap_or_else(|| "cufflink".to_string()),
                config
                    .keycloak_client_id
                    .clone()
                    .unwrap_or_else(|| "cufflink-cli".to_string()),
            )
        };
    let keycloak_url = keycloak_url.as_str();
    let realm = realm.as_str();
    let client_id = client_id.as_str();

    // Try refreshing with cached tokens
    if let Some(cached) = load_tokens(&config.api_url) {
        if let Some(refreshed) = try_refresh(&cached).await {
            let new_tokens = PlatformTokens {
                access_token: refreshed.access_token.clone(),
                refresh_token: refreshed
                    .refresh_token
                    .unwrap_or(cached.refresh_token.clone()),
                keycloak_url: cached.keycloak_url,
                realm: cached.realm,
                client_id: cached.client_id,
            };
            save_tokens(&config.api_url, &new_tokens);
            return Ok(refreshed.access_token);
        }
    }

    // No cached tokens or refresh failed — do device code auth
    let client = reqwest::Client::new();

    println!("Authenticating with platform...");
    let device_url = format!(
        "{}/realms/{}/protocol/openid-connect/auth/device",
        keycloak_url, realm
    );

    let resp = client
        .post(&device_url)
        .form(&[("client_id", client_id)])
        .send()
        .await?;

    if !resp.status().is_success() {
        let body = resp.text().await.unwrap_or_default();
        eyre::bail!(
            "Failed to start device auth (is the platform realm '{}' configured?): {}",
            realm,
            body
        );
    }

    let device: DeviceAuthResponse = resp.json().await?;

    let verify_url = device
        .verification_uri_complete
        .as_deref()
        .or(device.verification_uri.as_deref())
        .unwrap_or("(no verification URL)");

    println!();
    println!("  Open this URL in your browser:");
    println!("  {}", verify_url);
    println!();
    println!("  Enter code: {}", device.user_code);
    println!();
    println!("Waiting for authentication...");

    let token_url = format!(
        "{}/realms/{}/protocol/openid-connect/token",
        keycloak_url, realm
    );
    let interval = device.interval.unwrap_or(5);
    let deadline = std::time::Instant::now() + std::time::Duration::from_secs(device.expires_in);

    let token_resp = loop {
        if std::time::Instant::now() > deadline {
            eyre::bail!("Authentication timed out. Please try again.");
        }

        tokio::time::sleep(std::time::Duration::from_secs(interval)).await;

        let resp = client
            .post(&token_url)
            .form(&[
                ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
                ("device_code", &device.device_code),
                ("client_id", client_id),
            ])
            .send()
            .await?;

        if resp.status().is_success() {
            let token: TokenResponse = resp.json().await?;
            break token;
        }

        let err: TokenErrorResponse = resp.json().await?;
        match err.error.as_str() {
            "authorization_pending" => continue,
            "slow_down" => {
                tokio::time::sleep(std::time::Duration::from_secs(5)).await;
                continue;
            }
            other => eyre::bail!("Authentication failed: {}", other),
        }
    };

    // Cache tokens for future commands
    if let Some(ref refresh_token) = token_resp.refresh_token {
        save_tokens(
            &config.api_url,
            &PlatformTokens {
                access_token: token_resp.access_token.clone(),
                refresh_token: refresh_token.clone(),
                keycloak_url: keycloak_url.to_string(),
                realm: realm.to_string(),
                client_id: client_id.to_string(),
            },
        );
    }

    println!("Authenticated.");
    Ok(token_resp.access_token)
}

pub async fn create(
    name: &str,
    slug: &str,
    keycloak_url: Option<&str>,
    keycloak_realm: Option<&str>,
    deploy_role: Option<&str>,
    api_url: Option<&str>,
    env: Option<&str>,
) -> eyre::Result<()> {
    let config = CliConfig::for_platform(api_url, env)?;
    let token = platform_auth(&config).await?;

    let client = reqwest::Client::new();
    let mut body = serde_json::json!({
        "name": name,
        "slug": slug,
    });
    if let Some(url) = keycloak_url {
        body["keycloak_url"] = serde_json::json!(url);
    }
    if let Some(realm) = keycloak_realm {
        body["keycloak_realm"] = serde_json::json!(realm);
    }
    if let Some(role) = deploy_role {
        body["deploy_role"] = serde_json::json!(role);
    }

    let resp = client
        .post(format!("{}/api/tenants", config.api_url))
        .header("Authorization", format!("Bearer {}", token))
        .json(&body)
        .send()
        .await?;

    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        eyre::bail!("Failed to create tenant ({}): {}", status, body);
    }

    let tenant: serde_json::Value = resp.json().await?;
    println!();
    println!("  Tenant created:");
    println!(
        "  Name:           {}",
        tenant["name"].as_str().unwrap_or("")
    );
    println!(
        "  Slug:           {}",
        tenant["slug"].as_str().unwrap_or("")
    );
    println!(
        "  Keycloak URL:   {}",
        tenant["keycloak_url"].as_str().unwrap_or("(not set)")
    );
    println!(
        "  Keycloak Realm: {}",
        tenant["keycloak_realm"].as_str().unwrap_or("(not set)")
    );
    println!(
        "  Deploy Role:    {}",
        tenant["deploy_role"].as_str().unwrap_or("")
    );
    println!();
    println!("Developers can now run `cufflink login` with the tenant's Keycloak credentials.");

    Ok(())
}

/// The fields `cufflink tenants update` may change; `None` leaves a field
/// as it is.
#[derive(Debug, Default)]
pub struct TenantChanges<'a> {
    pub name: Option<&'a str>,
    pub keycloak_url: Option<&'a str>,
    pub keycloak_realm: Option<&'a str>,
    pub deploy_role: Option<&'a str>,
    pub keycloak_ops_client_id: Option<&'a str>,
    pub keycloak_ops_client_secret: Option<&'a str>,
    /// Comma-separated; empty clears the list.
    pub service_account_clients: Option<&'a str>,
    /// Empty clears the override.
    pub keycloak_issuer: Option<&'a str>,
}

impl TenantChanges<'_> {
    fn body(&self) -> serde_json::Map<String, serde_json::Value> {
        let strings = [
            ("name", self.name),
            ("keycloak_url", self.keycloak_url),
            ("keycloak_realm", self.keycloak_realm),
            ("deploy_role", self.deploy_role),
            ("keycloak_ops_client_id", self.keycloak_ops_client_id),
            (
                "keycloak_ops_client_secret",
                self.keycloak_ops_client_secret,
            ),
            ("keycloak_issuer", self.keycloak_issuer),
        ];
        let clients = self.service_account_clients.map(|raw| {
            let ids: Vec<&str> = raw
                .split(',')
                .map(str::trim)
                .filter(|id| !id.is_empty())
                .collect();
            ("service_account_clients", serde_json::json!(ids))
        });
        strings
            .into_iter()
            .filter_map(|(field, value)| value.map(|v| (field, serde_json::json!(v))))
            .chain(clients)
            .map(|(field, value)| (field.to_string(), value))
            .collect()
    }
}

pub async fn update(
    slug: &str,
    changes: &TenantChanges<'_>,
    api_url: Option<&str>,
    env: Option<&str>,
) -> eyre::Result<()> {
    let body = changes.body();
    if body.is_empty() {
        eyre::bail!("Nothing to update. Provide at least one of: --name, --tenant-keycloak-url, --tenant-keycloak-realm, --deploy-role, --keycloak-ops-client-id, --keycloak-ops-client-secret, --service-account-clients, --keycloak-issuer");
    }

    let config = CliConfig::for_platform(api_url, env)?;
    let token = platform_auth(&config).await?;

    let client = reqwest::Client::new();
    let resp = client
        .put(format!("{}/api/tenants/{}", config.api_url, slug))
        .header("Authorization", format!("Bearer {}", token))
        .json(&body)
        .send()
        .await?;

    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        eyre::bail!("Failed to update tenant ({}): {}", status, body);
    }

    let tenant: serde_json::Value = resp.json().await?;
    println!("Tenant '{}' updated:", slug);
    println!(
        "  Name:           {}",
        tenant["name"].as_str().unwrap_or("")
    );
    println!(
        "  Keycloak URL:   {}",
        tenant["keycloak_url"].as_str().unwrap_or("(not set)")
    );
    println!(
        "  Keycloak Realm: {}",
        tenant["keycloak_realm"].as_str().unwrap_or("(not set)")
    );
    println!(
        "  Deploy Role:    {}",
        tenant["deploy_role"].as_str().unwrap_or("")
    );
    println!(
        "  Issuer:         {}",
        tenant["keycloak_issuer"]
            .as_str()
            .unwrap_or("(platform default)")
    );
    let clients: Vec<&str> = tenant["service_account_clients"]
        .as_array()
        .map(|ids| ids.iter().filter_map(|id| id.as_str()).collect())
        .unwrap_or_default();
    println!(
        "  Service accts:  {}",
        if clients.is_empty() {
            "(none)".to_string()
        } else {
            clients.join(", ")
        }
    );

    Ok(())
}

/// Send one policy request as a platform admin and return the resulting
/// policy listing.
async fn policy_request(
    method: reqwest::Method,
    path: &str,
    body: Option<serde_json::Value>,
    api_url: Option<&str>,
    env: Option<&str>,
) -> eyre::Result<serde_json::Value> {
    let config = CliConfig::for_platform(api_url, env)?;
    let auth = match platform_api_auth() {
        Ok(a) => a,
        Err(_) => format!("Bearer {}", platform_auth(&config).await?),
    };
    let request = reqwest::Client::new()
        .request(method, format!("{}{}", config.api_url, path))
        .header("Authorization", &auth);
    let request = match body {
        Some(body) => request.json(&body),
        None => request,
    };
    let resp = request.send().await?;
    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        eyre::bail!("Policy request failed ({}): {}", status, body);
    }
    Ok(resp.json().await?)
}

fn print_policies(listing: &serde_json::Value) {
    use comfy_table::{presets::NOTHING, Table, TableComponent};

    let mut table = Table::new();
    table.load_preset(NOTHING);
    table.set_style(TableComponent::HeaderLines, '-');
    table.set_style(TableComponent::MiddleHeaderIntersections, ' ');
    table.set_header(vec!["KEY", "MODE", "SOURCE", "CONFIG"]);
    if let Some(policies) = listing["policies"].as_object() {
        for (key, policy) in policies {
            table.add_row(vec![
                key.as_str(),
                policy["mode"].as_str().unwrap_or("?"),
                policy["source"].as_str().unwrap_or("?"),
                &policy["config"].to_string(),
            ]);
        }
    }
    println!("{table}");
}

pub async fn policy_get(slug: &str, api_url: Option<&str>, env: Option<&str>) -> eyre::Result<()> {
    let path = format!("/api/tenants/{slug}/policies");
    let listing = policy_request(reqwest::Method::GET, &path, None, api_url, env).await?;
    print_policies(&listing);
    Ok(())
}

pub async fn policy_set(
    slug: &str,
    key: PolicyKey,
    mode: PolicyMode,
    policy_config: Option<serde_json::Value>,
    api_url: Option<&str>,
    env: Option<&str>,
) -> eyre::Result<()> {
    let path = format!("/api/tenants/{slug}/policies");
    let listing = policy_request(
        reqwest::Method::PUT,
        &path,
        Some(policy_body(key, mode, policy_config)),
        api_url,
        env,
    )
    .await?;
    println!("Policy '{key}' for tenant '{slug}' set to {mode}.");
    print_policies(&listing);
    Ok(())
}

fn policy_body(
    key: PolicyKey,
    mode: PolicyMode,
    policy_config: Option<serde_json::Value>,
) -> serde_json::Value {
    let mut entry = serde_json::json!({ "mode": mode });
    if let Some(policy_config) = policy_config {
        entry["config"] = policy_config;
    }
    serde_json::json!({ "policies": { key.as_str(): entry } })
}

pub async fn policy_reset(
    slug: &str,
    key: PolicyKey,
    api_url: Option<&str>,
    env: Option<&str>,
) -> eyre::Result<()> {
    let path = format!("/api/tenants/{slug}/policies/{key}");
    let listing = policy_request(reqwest::Method::DELETE, &path, None, api_url, env).await?;
    println!("Policy '{key}' for tenant '{slug}' reset to the platform default.");
    print_policies(&listing);
    Ok(())
}

pub async fn list(api_url: Option<&str>, env: Option<&str>) -> eyre::Result<()> {
    let config = CliConfig::for_platform(api_url, env)?;
    let token = platform_auth(&config).await?;

    let client = reqwest::Client::new();
    let resp = client
        .get(format!("{}/api/tenants", config.api_url))
        .header("Authorization", format!("Bearer {}", token))
        .send()
        .await?;

    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        eyre::bail!("Failed to list tenants ({}): {}", status, body);
    }

    let tenants: Vec<serde_json::Value> = resp.json().await?;

    if tenants.is_empty() {
        println!("No tenants found.");
        return Ok(());
    }

    use comfy_table::{presets::NOTHING, Table, TableComponent};

    let mut table = Table::new();
    table.load_preset(NOTHING);
    table.set_style(TableComponent::HeaderLines, '-');
    table.set_style(TableComponent::MiddleHeaderIntersections, ' ');
    table.set_header(vec!["SLUG", "NAME", "KEYCLOAK", "DEPLOY ROLE"]);

    for t in &tenants {
        let kc = match (t["keycloak_url"].as_str(), t["keycloak_realm"].as_str()) {
            (Some(url), Some(realm)) => format!("{} / {}", url, realm),
            _ => "(not configured)".to_string(),
        };
        table.add_row(vec![
            t["slug"].as_str().unwrap_or(""),
            t["name"].as_str().unwrap_or(""),
            &kc,
            t["deploy_role"].as_str().unwrap_or(""),
        ]);
    }

    println!("{table}");

    Ok(())
}

pub async fn delete(
    slug: &str,
    yes: bool,
    api_url: Option<&str>,
    env: Option<&str>,
) -> eyre::Result<()> {
    if !yes {
        println!(
            "This will permanently delete tenant '{}' and all its data.",
            slug
        );
        print!("Are you sure? (y/N) ");
        use std::io::Write;
        std::io::stdout().flush()?;
        let mut input = String::new();
        std::io::stdin().read_line(&mut input)?;
        if !input.trim().eq_ignore_ascii_case("y") {
            println!("Cancelled.");
            return Ok(());
        }
    }

    let config = CliConfig::for_platform(api_url, env)?;
    let token = platform_auth(&config).await?;

    let client = reqwest::Client::new();
    let resp = client
        .delete(format!("{}/api/tenants/{}", config.api_url, slug))
        .header("Authorization", format!("Bearer {}", token))
        .send()
        .await?;

    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        eyre::bail!("Failed to delete tenant ({}): {}", status, body);
    }

    println!("Tenant '{}' deleted.", slug);
    Ok(())
}

fn platform_api_auth() -> eyre::Result<String> {
    std::env::var("CUFFLINK_PLATFORM_API_KEY")
        .map(|k| format!("ApiKey {}", k))
        .map_err(|_| eyre::eyre!("CUFFLINK_PLATFORM_API_KEY env var required"))
}

pub async fn create_platform_api_key(
    name: &str,
    api_url: Option<&str>,
    env: Option<&str>,
) -> eyre::Result<()> {
    let config = CliConfig::for_platform(api_url, env)?;
    let auth = match platform_api_auth() {
        Ok(a) => a,
        Err(_) => format!("Bearer {}", platform_auth(&config).await?),
    };

    let client = reqwest::Client::new();
    let resp = client
        .post(format!("{}/api/platform/api-keys", config.api_url))
        .header("Authorization", &auth)
        .json(&serde_json::json!({ "name": name }))
        .send()
        .await?;

    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        eyre::bail!("Failed to create API key ({}): {}", status, body);
    }

    let body: serde_json::Value = resp.json().await?;
    println!("Platform admin API key created:");
    println!("  Name: {}", body["name"].as_str().unwrap_or("?"));
    println!("  ID:   {}", body["id"].as_str().unwrap_or("?"));
    println!("  Key:  {}", body["key"].as_str().unwrap_or("?"));
    println!();
    println!("Save this key — it cannot be retrieved again.");

    Ok(())
}

pub async fn list_platform_api_keys(api_url: Option<&str>, env: Option<&str>) -> eyre::Result<()> {
    let config = CliConfig::for_platform(api_url, env)?;
    let auth = match platform_api_auth() {
        Ok(a) => a,
        Err(_) => format!("Bearer {}", platform_auth(&config).await?),
    };

    let client = reqwest::Client::new();
    let resp = client
        .get(format!("{}/api/platform/api-keys", config.api_url))
        .header("Authorization", &auth)
        .send()
        .await?;

    if !resp.status().is_success() {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        eyre::bail!("Failed to list API keys ({}): {}", status, body);
    }

    let body: serde_json::Value = resp.json().await?;
    let keys = body["keys"].as_array();

    if keys.map(|k| k.is_empty()).unwrap_or(true) {
        println!("No platform admin API keys.");
        return Ok(());
    }

    use comfy_table::{presets::NOTHING, Table, TableComponent};
    let mut table = Table::new();
    table.load_preset(NOTHING);
    table.set_style(TableComponent::HeaderLines, '-');
    table.set_style(TableComponent::MiddleHeaderIntersections, ' ');
    table.set_header(vec!["ID", "NAME", "CREATED", "EXPIRES"]);

    for key in keys.unwrap() {
        table.add_row(vec![
            key["id"].as_str().unwrap_or("?"),
            key["name"].as_str().unwrap_or("?"),
            key["created_at"].as_str().unwrap_or("?"),
            key["expires_at"].as_str().unwrap_or("never"),
        ]);
    }

    println!("{table}");
    Ok(())
}

pub async fn revoke_platform_api_key(
    id: &str,
    api_url: Option<&str>,
    env: Option<&str>,
) -> eyre::Result<()> {
    let config = CliConfig::for_platform(api_url, env)?;
    let auth = match platform_api_auth() {
        Ok(a) => a,
        Err(_) => format!("Bearer {}", platform_auth(&config).await?),
    };

    let client = reqwest::Client::new();
    let resp = client
        .delete(format!("{}/api/platform/api-keys/{}", config.api_url, id))
        .header("Authorization", &auth)
        .send()
        .await?;

    if resp.status().is_success() {
        println!("API key revoked.");
    } else {
        let status = resp.status();
        let body = resp.text().await.unwrap_or_default();
        eyre::bail!("Failed to revoke API key ({}): {}", status, body);
    }

    Ok(())
}

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

    #[test]
    fn update_body_carries_only_the_given_fields() {
        let changes = TenantChanges {
            name: Some("Starmoire"),
            service_account_clients: Some("starmoire-ops, ci-bot"),
            ..Default::default()
        };
        assert_eq!(
            serde_json::Value::Object(changes.body()),
            json!({"name": "Starmoire", "service_account_clients": ["starmoire-ops", "ci-bot"]})
        );
        let clear = TenantChanges {
            service_account_clients: Some(""),
            keycloak_issuer: Some(""),
            ..Default::default()
        };
        assert_eq!(
            serde_json::Value::Object(clear.body()),
            json!({"service_account_clients": [], "keycloak_issuer": ""})
        );
        assert!(TenantChanges::default().body().is_empty());
    }

    #[test]
    fn policy_body_omits_config_unless_given() {
        assert_eq!(
            policy_body(PolicyKey::Egress, PolicyMode::Warn, None),
            json!({"policies": {"egress": {"mode": "warn"}}})
        );
        assert_eq!(
            policy_body(
                PolicyKey::Audience,
                PolicyMode::Enforce,
                Some(json!({"allowed": ["portal"]}))
            ),
            json!({"policies": {"audience": {"mode": "enforce", "config": {"allowed": ["portal"]}}}})
        );
    }
}