zilliz 1.4.0

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
use std::io::{self, BufRead, Write};
use std::time::{Duration, Instant};

use anyhow::{bail, Context, Result};
use serde::Deserialize;

use crate::config::manager::ConfigManager;
use crate::model::types::{
    AuthConfig, DEFAULT_CN_CONTROL_PLANE_ENDPOINT, DEFAULT_DEV_CONTROL_PLANE_ENDPOINT,
};

// ---------------------------------------------------------------------------
// OAuth Device Code Flow types
// ---------------------------------------------------------------------------

#[derive(Debug, Deserialize)]
struct DeviceCodeResponse {
    device_code: String,
    user_code: String,
    verification_uri_complete: String,
    expires_in: u64,
    #[serde(default = "default_interval")]
    interval: u64,
}

fn default_interval() -> u64 {
    5
}

#[derive(Debug, Deserialize)]
struct TokenResponse {
    access_token: String,
}

#[derive(Debug, Deserialize)]
struct TokenErrorResponse {
    error: String,
    #[serde(default)]
    error_description: String,
}

// ---------------------------------------------------------------------------
// Login
// ---------------------------------------------------------------------------

pub async fn login(
    config_mgr: &ConfigManager,
    auth_config: Option<&AuthConfig>,
    no_browser: bool,
    api_key_value: Option<&str>,
    cn: bool,
    dev: bool,
) -> Result<()> {
    if cn && dev {
        bail!("--cn and --dev cannot be combined");
    }

    // Check existing login
    if let Some(user) = config_mgr.get_user_info() {
        println!("Already logged in as {}", user.email);
        if !confirm("Do you want to re-authenticate?")? {
            return Ok(());
        }
    } else if config_mgr.get_credential("api_key").is_some() {
        println!("Already logged in with API key");
        if !confirm("Do you want to re-authenticate?")? {
            return Ok(());
        }
    }

    config_mgr.clear_context()?;

    if let Some((endpoint, label)) = named_cloud(cn, dev) {
        // CN / dev cloud: API-key only, never browser / Auth0.
        match api_key_value {
            Some(key) if !key.is_empty() => {
                config_mgr.save_api_key_only(key)?;
                config_mgr.set_control_plane_endpoint(endpoint)?;
                println!("Successfully configured API key for {} cloud!", label);
                println!("  Endpoint: {}", endpoint);
                println!("  API Key:  {}", mask_api_key(key));
                Ok(())
            }
            _ => {
                // `--cn`/`--dev` alone or with `--api-key` (no value): interactive prompt.
                login_with_api_key_named(config_mgr, endpoint, label).await
            }
        }
    } else {
        match api_key_value {
            Some("") => {
                // --api-key with no value: interactive prompt
                let result = login_with_api_key(config_mgr).await;
                if result.is_ok() {
                    config_mgr.clear_control_plane_endpoint()?;
                }
                result
            }
            Some(key) => {
                // --api-key <value>: store directly
                config_mgr.save_api_key_only(key)?;
                config_mgr.clear_control_plane_endpoint()?;
                println!("Successfully configured API key!");
                println!("  API Key: {}", mask_api_key(key));
                Ok(())
            }
            None => {
                // No --api-key: browser OAuth (requires auth_config)
                let auth_config = auth_config.ok_or_else(|| {
                    anyhow::anyhow!("Browser login is unavailable: missing auth config")
                })?;
                let result = login_with_browser(config_mgr, auth_config, no_browser).await;
                if result.is_ok() {
                    config_mgr.clear_control_plane_endpoint()?;
                }
                result
            }
        }
    }
}

/// Map `(cn, dev)` flag pair to an endpoint+label. Caller must have already
/// validated that the flags are not both set.
fn named_cloud(cn: bool, dev: bool) -> Option<(&'static str, &'static str)> {
    debug_assert!(!(cn && dev), "named_cloud called with both cn and dev set");
    if cn {
        Some((DEFAULT_CN_CONTROL_PLANE_ENDPOINT, "CN"))
    } else if dev {
        Some((DEFAULT_DEV_CONTROL_PLANE_ENDPOINT, "Dev (UAT)"))
    } else {
        None
    }
}

async fn login_with_api_key_named(
    config_mgr: &ConfigManager,
    endpoint: &str,
    label: &str,
) -> Result<()> {
    println!("\n{} Cloud — API Key Authentication", label);
    println!("Endpoint: {}", endpoint);
    println!("You can find your API key in the Zilliz Cloud console under API Keys.");
    println!();

    print!("Please paste your API key: ");
    io::stdout().flush()?;

    let mut api_key = String::new();
    io::stdin().lock().read_line(&mut api_key)?;
    let api_key = api_key.trim().to_string();

    if api_key.is_empty() {
        bail!("API key cannot be empty");
    }

    config_mgr.save_api_key_only(&api_key)?;
    config_mgr.set_control_plane_endpoint(endpoint)?;

    println!("\nSuccessfully configured API key for {} cloud!", label);
    println!("  Endpoint: {}", endpoint);
    println!("  API Key:  {}", mask_api_key(&api_key));

    Ok(())
}

async fn login_with_api_key(config_mgr: &ConfigManager) -> Result<()> {
    println!("\nAPI Key Authentication");
    println!("You can find your API key in the Zilliz Cloud console under API Keys.");
    println!();

    print!("Please paste your API key: ");
    io::stdout().flush()?;

    let mut api_key = String::new();
    io::stdin().lock().read_line(&mut api_key)?;
    let api_key = api_key.trim().to_string();

    if api_key.is_empty() {
        bail!("API key cannot be empty");
    }

    config_mgr.save_api_key_only(&api_key)?;

    println!("\nSuccessfully configured API key!");
    println!("  API Key: {}", mask_api_key(&api_key));
    println!("\nNote: You're using API key authentication. Some features may be limited.");

    Ok(())
}

async fn login_with_browser(
    config_mgr: &ConfigManager,
    auth_config: &AuthConfig,
    no_browser: bool,
) -> Result<()> {
    println!("Starting browser-based login...");

    // Step 1: Request device code
    let client = reqwest::Client::builder()
        .user_agent(format!("zilliz-cli/{}", env!("CARGO_PKG_VERSION")))
        .build()
        .context("Failed to build HTTP client")?;
    let device_resp: DeviceCodeResponse = client
        .post(format!("{}/oauth/device/code", auth_config.auth0_domain))
        .form(&[
            ("client_id", auth_config.client_id.as_str()),
            ("scope", "openid email profile"),
        ])
        .send()
        .await
        .context("Failed to request device code")?
        .json()
        .await
        .context("Invalid device code response")?;

    println!("\nYour verification code: {}", device_resp.user_code);
    println!("Please visit: {}", device_resp.verification_uri_complete);

    // Step 2: Open browser
    if !no_browser {
        println!("\nOpening browser to complete login...");
        if open_browser(&device_resp.verification_uri_complete).is_err() {
            println!("Could not open browser. Please visit the URL above manually.");
        }
    } else {
        println!("\nPlease visit the URL above to complete login.");
    }

    println!("\nWaiting for authentication...");

    // Step 3: Poll for token
    let token = poll_for_token(
        &client,
        auth_config,
        &device_resp.device_code,
        device_resp.interval,
        device_resp.expires_in,
    )
    .await?;

    println!("\nExchanging token for credentials...");

    // Step 4: Exchange token for CLI credentials
    let cli_login_url = format!("{}/account/v1/cli/login", auth_config.login_api);

    let resp = client
        .post(&cli_login_url)
        .header("Authorization", format!("Bearer {}", token.access_token))
        .send()
        .await
        .context("Failed to exchange token")?;

    let status = resp.status();
    let body_text = resp.text().await.context("Failed to read login response")?;
    let body: serde_json::Value = serde_json::from_str(&body_text).with_context(|| {
        format!(
            "Invalid login response (HTTP {}): {}",
            status.as_u16(),
            if body_text.len() > 200 {
                &body_text[..200]
            } else {
                &body_text
            }
        )
    })?;

    let code = body
        .get("code")
        .or_else(|| body.get("Code"))
        .and_then(|v| v.as_i64())
        .unwrap_or(-1);

    if !status.is_success() || (code != 0 && code != 200) {
        let msg = body
            .get("msg")
            .or_else(|| body.get("Message"))
            .and_then(|v| v.as_str())
            .unwrap_or("Login failed");
        bail!("Login failed ({}): {}", status.as_u16(), msg);
    }

    let result = body
        .get("data")
        .or_else(|| body.get("Data"))
        .cloned()
        .unwrap_or_default();

    let user = result.get("user").cloned().unwrap_or_default();
    let orgs = result
        .get("orgs")
        .and_then(|v| v.as_array())
        .cloned()
        .unwrap_or_default();

    // Save login data
    config_mgr.save_login_data(
        user.get("userId").and_then(|v| v.as_str()).unwrap_or(""),
        user.get("email").and_then(|v| v.as_str()).unwrap_or(""),
        user.get("name").and_then(|v| v.as_str()).unwrap_or(""),
        &orgs,
    )?;

    let user_name = user.get("name").and_then(|v| v.as_str()).unwrap_or("");
    let user_email = user.get("email").and_then(|v| v.as_str()).unwrap_or("");

    println!("\nSuccessfully logged in!");
    println!("  User: {} ({})", user_name, user_email);

    if let Some(first_org) = orgs.first() {
        let org_name = first_org.get("name").and_then(|v| v.as_str()).unwrap_or("");
        let org_id = first_org
            .get("orgId")
            .and_then(|v| v.as_str())
            .unwrap_or("");
        println!("  Organization: {} ({})", org_name, org_id);

        if orgs.len() > 1 {
            println!(
                "\n{} organizations available. Use 'zilliz switch <org-id>' to change.",
                orgs.len()
            );
        }
    }

    Ok(())
}

async fn poll_for_token(
    client: &reqwest::Client,
    auth_config: &AuthConfig,
    device_code: &str,
    mut interval: u64,
    timeout_secs: u64,
) -> Result<TokenResponse> {
    let url = format!("{}/oauth/token", auth_config.auth0_domain);
    let start = Instant::now();
    let timeout = Duration::from_secs(timeout_secs);

    loop {
        if start.elapsed() > timeout {
            bail!("Authentication timed out. Please try again.");
        }

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

        let resp = client
            .post(&url)
            .form(&[
                ("grant_type", "urn:ietf:params:oauth:grant-type:device_code"),
                ("device_code", device_code),
                ("client_id", auth_config.client_id.as_str()),
            ])
            .send()
            .await
            .context("Token poll request failed")?;

        if resp.status().is_success() {
            return resp
                .json::<TokenResponse>()
                .await
                .context("Invalid token response");
        }

        let error_resp: TokenErrorResponse = resp.json().await.unwrap_or(TokenErrorResponse {
            error: "unknown".to_string(),
            error_description: "Unknown error".to_string(),
        });

        match error_resp.error.as_str() {
            "authorization_pending" => continue,
            "slow_down" => {
                interval = (interval + 5).min(60);
                continue;
            }
            "expired_token" => bail!("Authentication timed out. Please try again."),
            "access_denied" => bail!("Authentication was denied."),
            _ => bail!("Authentication failed: {}", error_resp.error_description),
        }
    }
}

// ---------------------------------------------------------------------------
// Logout
// ---------------------------------------------------------------------------

pub fn logout(config_mgr: &ConfigManager) -> Result<()> {
    let result = if let Some(user) = config_mgr.get_user_info() {
        config_mgr.clear_login_data()?;
        config_mgr.clear_context()?;
        println!("Logged out from {}", user.email);
        Ok(())
    } else if config_mgr.get_credential("api_key").is_some() {
        config_mgr.clear_login_data()?;
        config_mgr.clear_context()?;
        println!("Cleared API key credentials.");
        Ok(())
    } else {
        println!("Not logged in.");
        Ok(())
    };

    // Always clear the persisted control-plane endpoint so the next `login`
    // is unambiguous. Safe no-op when not set.
    config_mgr.clear_control_plane_endpoint()?;

    result
}

// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------

fn mask_api_key(key: &str) -> String {
    let chars: Vec<char> = key.chars().collect();
    if chars.len() >= 16 {
        let prefix: String = chars[..4].iter().collect();
        let suffix: String = chars[chars.len() - 4..].iter().collect();
        format!("{}****{}", prefix, suffix)
    } else {
        "****".to_string()
    }
}

fn confirm(prompt: &str) -> Result<bool> {
    print!("{} [y/N] ", prompt);
    io::stdout().flush()?;
    let mut input = String::new();
    io::stdin().lock().read_line(&mut input)?;
    Ok(input.trim().eq_ignore_ascii_case("y"))
}

fn open_browser(url: &str) -> Result<()> {
    #[cfg(target_os = "macos")]
    {
        std::process::Command::new("open").arg(url).spawn()?;
    }
    #[cfg(target_os = "linux")]
    {
        std::process::Command::new("xdg-open").arg(url).spawn()?;
    }
    #[cfg(target_os = "windows")]
    {
        std::process::Command::new("cmd")
            .args(["/c", "start", url])
            .spawn()?;
    }
    Ok(())
}