zilliz 1.4.3

TUI and CLI tool for managing Zilliz Cloud clusters and Milvus operations
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
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
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::{Context, Result};
use ini::Ini;

const ORG_SECTION_PREFIX: &str = "org.";

/// Extract API key from an org JSON object.
/// The API returns `apiKeys: [{key: "sk_..."}]` (array), not `apiKey` (string).
fn extract_api_key(org: &serde_json::Value) -> String {
    // Try apiKeys array first (login API response format)
    if let Some(keys) = org.get("apiKeys").and_then(|v| v.as_array()) {
        if let Some(first) = keys.first() {
            if let Some(key) = first.get("key").and_then(|v| v.as_str()) {
                return key.to_string();
            }
        }
    }
    // Fallback: try apiKey as a plain string
    org.get("apiKey")
        .and_then(|v| v.as_str())
        .unwrap_or("")
        .to_string()
}

/// Manages ~/.zilliz/config and ~/.zilliz/credentials files.
/// Compatible with the Python zilliz-cli INI format.
#[derive(Clone)]
pub struct ConfigManager {
    #[allow(dead_code)]
    pub config_dir: PathBuf,
    credentials_path: PathBuf,
    config_path: PathBuf,
}

impl ConfigManager {
    pub fn new(config_dir: Option<PathBuf>) -> Result<Self> {
        let config_dir = match config_dir {
            Some(d) => d,
            None => {
                if let Ok(env_dir) = std::env::var("ZILLIZ_CONFIG_DIR") {
                    PathBuf::from(env_dir)
                } else {
                    dirs::home_dir()
                        .context("Cannot determine home directory")?
                        .join(".zilliz")
                }
            }
        };

        fs::create_dir_all(&config_dir)
            .with_context(|| format!("Failed to create config dir: {}", config_dir.display()))?;

        let credentials_path = config_dir.join("credentials");
        let config_path = config_dir.join("config");

        Ok(Self {
            config_dir,
            credentials_path,
            config_path,
        })
    }

    // --- Credentials ---

    pub fn get_credential(&self, key: &str) -> Option<String> {
        let ini = self.read_ini(&self.credentials_path);
        ini.get_from(Some("default"), key).map(|s| {
            // Strip quotes and whitespace that INI parsers may preserve
            s.trim().trim_matches('"').trim_matches('\'').to_string()
        })
    }

    pub fn set_credential(&self, key: &str, value: &str) -> Result<()> {
        let mut ini = self.read_ini(&self.credentials_path);
        ini.with_section(Some("default")).set(key, value);
        self.write_ini(&self.credentials_path, &ini)?;
        Ok(())
    }

    /// Remove the credentials file entirely.
    pub fn clear_credentials(&self) -> Result<()> {
        if self.credentials_path.exists() {
            fs::remove_file(&self.credentials_path)
                .with_context(|| format!("Failed to remove {}", self.credentials_path.display()))?;
        }
        Ok(())
    }

    /// Return all credentials and config key-value pairs.
    #[allow(clippy::type_complexity)]
    pub fn list_all(&self) -> (Vec<(String, String)>, Vec<(String, String)>) {
        let mut credentials = Vec::new();
        let mut config = Vec::new();

        let cred_ini = self.read_ini(&self.credentials_path);
        if let Some(props) = cred_ini.section(Some("default")) {
            for (k, v) in props.iter() {
                credentials.push((k.to_string(), v.to_string()));
            }
        }

        let cfg_ini = self.read_ini(&self.config_path);
        if let Some(props) = cfg_ini.section(Some("default")) {
            for (k, v) in props.iter() {
                config.push((k.to_string(), v.to_string()));
            }
        }

        (credentials, config)
    }

    // --- Config ---

    pub fn get_config(&self, section: &str, key: &str) -> Option<String> {
        let ini = self.read_ini(&self.config_path);
        ini.get_from(Some(section), key).map(|s| s.to_string())
    }

    pub fn set_config(&self, section: &str, key: &str, value: &str) -> Result<()> {
        let mut ini = self.read_ini(&self.config_path);
        ini.with_section(Some(section)).set(key, value);
        self.write_ini(&self.config_path, &ini)?;
        Ok(())
    }

    // --- Persisted control-plane endpoint ---
    //
    // Stored as `[default].endpoint` in `~/.zilliz/config`. Written by
    // `zilliz login --cn`, cleared by `zilliz logout` and by `zilliz login`
    // without `--cn`. Distinct from the per-cluster `[context].endpoint`.

    pub fn get_control_plane_endpoint(&self) -> Option<String> {
        let ini = self.read_ini(&self.config_path);
        ini.get_from(Some("default"), "endpoint")
            .map(|s| s.trim().trim_matches('"').trim_matches('\'').to_string())
    }

    pub fn set_control_plane_endpoint(&self, url: &str) -> Result<()> {
        self.set_config("default", "endpoint", url)
    }

    pub fn clear_control_plane_endpoint(&self) -> Result<()> {
        let mut ini = self.read_ini(&self.config_path);
        if ini.delete_from(Some("default"), "endpoint").is_none() {
            return Ok(());
        }
        self.write_ini(&self.config_path, &ini)?;
        Ok(())
    }

    // --- Context ---

    pub fn get_context(&self) -> super::context::ClusterContext {
        let ini = self.read_ini(&self.config_path);
        super::context::ClusterContext {
            cluster_id: ini
                .get_from(Some("context"), "cluster_id")
                .map(|s| s.to_string()),
            endpoint: ini
                .get_from(Some("context"), "endpoint")
                .map(|s| s.to_string()),
            database: ini
                .get_from(Some("context"), "database")
                .map(|s| s.to_string())
                .unwrap_or_else(|| "default".to_string()),
            plan: ini.get_from(Some("context"), "plan").map(|s| s.to_string()),
        }
    }

    pub fn set_context(&self, ctx: &super::context::ClusterContext) -> Result<()> {
        let mut ini = self.read_ini(&self.config_path);
        let mut section = ini.with_section(Some("context"));
        if let Some(ref id) = ctx.cluster_id {
            section.set("cluster_id", id);
        }
        if let Some(ref ep) = ctx.endpoint {
            section.set("endpoint", ep);
        }
        section.set("database", &ctx.database);
        if let Some(ref plan) = ctx.plan {
            section.set("plan", plan);
        }
        self.write_ini(&self.config_path, &ini)?;
        Ok(())
    }

    pub fn clear_context(&self) -> Result<()> {
        let mut ini = self.read_ini(&self.config_path);
        ini.delete(Some("context"));
        self.write_ini(&self.config_path, &ini)?;
        Ok(())
    }

    // --- Org management ---

    #[allow(dead_code)]
    pub fn get_all_orgs(&self) -> Vec<OrgInfo> {
        let ini = self.read_ini(&self.credentials_path);
        let mut orgs = Vec::new();
        for (section, _) in &ini {
            if let Some(name) = section {
                if let Some(org_id) = name.strip_prefix(ORG_SECTION_PREFIX) {
                    let org_name = ini
                        .get_from(Some(name), "org_name")
                        .unwrap_or("")
                        .to_string();
                    let api_key = ini.get_from(Some(name), "api_key").map(|s| s.to_string());
                    orgs.push(OrgInfo {
                        org_id: org_id.to_string(),
                        name: org_name,
                        api_key,
                    });
                }
            }
        }
        orgs
    }

    pub fn get_current_org(&self) -> Option<OrgInfo> {
        let ini = self.read_ini(&self.credentials_path);
        let org_id = ini.get_from(Some("default"), "org_id")?;
        Some(OrgInfo {
            org_id: org_id.to_string(),
            name: ini
                .get_from(Some("default"), "org_name")
                .unwrap_or("")
                .to_string(),
            api_key: ini
                .get_from(Some("default"), "api_key")
                .map(|s| s.to_string()),
        })
    }

    // --- User info (from OAuth login) ---

    pub fn get_user_info(&self) -> Option<UserInfo> {
        let ini = self.read_ini(&self.credentials_path);
        let email = ini.get_from(Some("user"), "email")?.to_string();
        Some(UserInfo {
            user_id: ini
                .get_from(Some("user"), "user_id")
                .unwrap_or("")
                .to_string(),
            email,
            name: ini.get_from(Some("user"), "name").unwrap_or("").to_string(),
        })
    }

    /// Save login data from CLI login API response.
    /// Compatible with zilliz-cli INI format.
    pub fn save_login_data(
        &self,
        user_id: &str,
        email: &str,
        name: &str,
        orgs: &[serde_json::Value],
    ) -> Result<()> {
        let mut ini = self.read_ini(&self.credentials_path);

        // Clear old org sections
        let old_sections: Vec<String> = ini
            .iter()
            .filter_map(|(s, _)| s.map(|s| s.to_string()))
            .filter(|s| s.starts_with(ORG_SECTION_PREFIX) || s == "orgs")
            .collect();
        for section in &old_sections {
            ini.delete(Some(section.as_str()));
        }

        // Save user info
        ini.with_section(Some("user"))
            .set("user_id", user_id)
            .set("email", email)
            .set("name", name);

        // Save orgs and set first org as default
        if let Some(first_org) = orgs.first() {
            let org_id = first_org
                .get("orgId")
                .and_then(|v| v.as_str())
                .unwrap_or("");
            let org_name = first_org.get("name").and_then(|v| v.as_str()).unwrap_or("");
            let api_key = extract_api_key(first_org);

            let mut section = ini.with_section(Some("default"));
            section.set("org_id", org_id).set("org_name", org_name);
            if !api_key.is_empty() {
                section.set("api_key", &api_key);
            }
        }

        for org in orgs {
            let org_id = org
                .get("orgId")
                .and_then(|v| v.as_str())
                .unwrap_or_default();
            let org_name = org.get("name").and_then(|v| v.as_str()).unwrap_or_default();
            let api_key = extract_api_key(org);

            if !org_id.is_empty() {
                let section_name = format!("{}{}", ORG_SECTION_PREFIX, org_id);
                let mut section = ini.with_section(Some(section_name));
                section.set("org_name", org_name);
                if !api_key.is_empty() {
                    section.set("api_key", &api_key);
                }
            }
        }

        self.write_ini(&self.credentials_path, &ini)?;
        Ok(())
    }

    /// Save only an API key (manual login without OAuth).
    pub fn save_api_key_only(&self, api_key: &str) -> Result<()> {
        let mut ini = self.read_ini(&self.credentials_path);

        // Clear user and org sections
        ini.delete(Some("user"));
        let old_sections: Vec<String> = ini
            .iter()
            .filter_map(|(s, _)| s.map(|s| s.to_string()))
            .filter(|s| s.starts_with(ORG_SECTION_PREFIX) || s == "orgs")
            .collect();
        for section in &old_sections {
            ini.delete(Some(section.as_str()));
        }

        ini.with_section(Some("default")).set("api_key", api_key);
        self.write_ini(&self.credentials_path, &ini)?;
        Ok(())
    }

    /// Clear all login data (user info, orgs, api key).
    pub fn clear_login_data(&self) -> Result<()> {
        let mut ini = self.read_ini(&self.credentials_path);

        ini.delete(Some("user"));
        ini.delete(Some("default"));

        let old_sections: Vec<String> = ini
            .iter()
            .filter_map(|(s, _)| s.map(|s| s.to_string()))
            .filter(|s| s.starts_with(ORG_SECTION_PREFIX) || s == "orgs")
            .collect();
        for section in &old_sections {
            ini.delete(Some(section.as_str()));
        }

        self.write_ini(&self.credentials_path, &ini)?;
        Ok(())
    }

    // --- Internal ---

    fn read_ini(&self, path: &Path) -> Ini {
        if path.exists() {
            Ini::load_from_file(path).unwrap_or_default()
        } else {
            Ini::new()
        }
    }

    fn write_ini(&self, path: &Path, ini: &Ini) -> Result<()> {
        ini.write_to_file(path)
            .with_context(|| format!("Failed to write {}", path.display()))?;

        // Restrict credentials file permissions (owner read/write only)
        #[cfg(unix)]
        if path == self.credentials_path {
            use std::os::unix::fs::PermissionsExt;
            fs::set_permissions(path, fs::Permissions::from_mode(0o600))?;
        }

        Ok(())
    }
}

/// Snapshot of the active session, used by the TUI to render auth-aware views.
///
/// Built from the `[default]` and `[user]` sections of `~/.zilliz/credentials`
/// and the `[default].endpoint` value in `~/.zilliz/config`. Any parse error
/// is treated as "no active session" (logged via `tracing::warn!`).
#[derive(Debug, Clone)]
pub struct SessionInfo {
    pub user: Option<String>,
    pub email: Option<String>,
    pub org: Option<String>,
    pub endpoint: Option<String>,
    pub credentials_path: PathBuf,
    pub has_active_credentials: bool,
    /// True when the credentials file has a non-empty `[user]` section,
    /// which only happens for Auth0 sign-ins (`save_login_data` writes it,
    /// `save_api_key_only` clears it).
    pub has_user_section: bool,
    /// Raw API key, when present. Callers MUST NOT persist this beyond the
    /// snapshot construction site — convert to a masked form immediately.
    pub raw_api_key: Option<String>,
}

impl ConfigManager {
    pub fn credentials_path(&self) -> &Path {
        &self.credentials_path
    }

    /// Build a `SessionInfo` snapshot from the on-disk credentials/config files.
    ///
    /// Never returns an error; malformed files are surfaced as a "no session"
    /// snapshot with a `tracing::warn!` so the TUI can render gracefully.
    pub fn current_session(&self) -> SessionInfo {
        let cred_ini = match Ini::load_from_file(&self.credentials_path) {
            Ok(ini) => Some(ini),
            Err(ini::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => {
                tracing::warn!(
                    "credentials file at {} could not be parsed: {}",
                    self.credentials_path.display(),
                    e
                );
                None
            }
        };

        let cfg_ini = match Ini::load_from_file(&self.config_path) {
            Ok(ini) => Some(ini),
            Err(ini::Error::Io(e)) if e.kind() == std::io::ErrorKind::NotFound => None,
            Err(e) => {
                tracing::warn!(
                    "config file at {} could not be parsed: {}",
                    self.config_path.display(),
                    e
                );
                None
            }
        };

        let (mut user, mut email, mut org, mut has_api_key) = (None, None, None, false);
        let mut has_user_section = false;
        let mut raw_api_key: Option<String> = None;
        if let Some(ref ini) = cred_ini {
            if let Some(em) = ini.get_from(Some("user"), "email") {
                let s = em.trim();
                if !s.is_empty() {
                    email = Some(s.to_string());
                    has_user_section = true;
                }
            }
            if let Some(name) = ini.get_from(Some("user"), "name") {
                let s = name.trim();
                if !s.is_empty() {
                    user = Some(s.to_string());
                    has_user_section = true;
                }
            }
            if user.is_none() {
                user = email.clone();
            }
            if let Some(org_name) = ini.get_from(Some("default"), "org_name") {
                let s = org_name.trim();
                if !s.is_empty() {
                    org = Some(s.to_string());
                }
            }
            if let Some(key) = ini.get_from(Some("default"), "api_key") {
                let s = key.trim();
                if !s.is_empty() {
                    has_api_key = true;
                    raw_api_key = Some(s.to_string());
                }
            }
        }

        // Env var override mirrors how the API client resolves credentials.
        if let Ok(env_key) = std::env::var("ZILLIZ_API_KEY") {
            let s = env_key.trim();
            if !s.is_empty() {
                has_api_key = true;
                if raw_api_key.is_none() {
                    raw_api_key = Some(s.to_string());
                }
            }
        }

        let endpoint = cfg_ini
            .as_ref()
            .and_then(|ini| ini.get_from(Some("default"), "endpoint"))
            .map(|s| s.trim().trim_matches('"').trim_matches('\'').to_string())
            .filter(|s| !s.is_empty());

        SessionInfo {
            user,
            email,
            org,
            endpoint,
            credentials_path: self.credentials_path.clone(),
            has_active_credentials: has_api_key,
            has_user_section,
            raw_api_key,
        }
    }
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct OrgInfo {
    pub org_id: String,
    pub name: String,
    pub api_key: Option<String>,
}

#[derive(Debug, Clone)]
#[allow(dead_code)]
pub struct UserInfo {
    pub user_id: String,
    pub email: String,
    pub name: String,
}