Skip to main content

crates_docs/cli/
api_key_cmd.rs

1//! API key command implementation
2
3#[cfg(feature = "api-key")]
4use crate::server::auth::ApiKeyConfig;
5
6/// Generate a new API key and corresponding hash for secure storage.
7///
8/// Prints the plain-text key once for the operator to copy, along with the
9/// stable key ID and the Argon2 PHC hash that should be stored in config or
10/// secret storage.
11///
12/// # Errors
13///
14/// Returns an error if key generation fails or if the prefix is invalid.
15#[cfg(feature = "api-key")]
16pub fn run_generate_api_key_command(prefix: &str) -> Result<(), Box<dyn std::error::Error>> {
17    let config = ApiKeyConfig {
18        key_prefix: prefix.to_string(),
19        ..Default::default()
20    };
21
22    let generated = config
23        .generate_key()
24        .map_err(|e| format!("Failed to generate API key: {e}"))?;
25
26    println!("Generated API key successfully.");
27    println!();
28    println!("Plain-text key (show once and store securely):");
29    println!("{}", generated.key);
30    println!();
31    println!("Key ID:");
32    println!("{}", generated.key_id);
33    println!();
34    println!("Store this hash in configuration or secret storage:");
35    println!("{}", generated.hash);
36    println!();
37    println!("Example config:");
38    println!("[api_key]");
39    println!("enabled = true");
40    println!("keys = [\"{}\"]", generated.hash);
41    println!("header_name = \"X-API-Key\"");
42    println!("query_param_name = \"api_key\"");
43    println!("allow_query_param = false");
44    println!("key_prefix = \"{prefix}\"");
45
46    Ok(())
47}
48
49/// Fallback implementation when the `api-key` feature is disabled.
50///
51/// # Errors
52///
53/// Always returns an error because API key support is not compiled in.
54#[cfg(not(feature = "api-key"))]
55pub fn run_generate_api_key_command(_prefix: &str) -> Result<(), Box<dyn std::error::Error>> {
56    Err("API key support is not enabled in this build".into())
57}