use anyhow::{anyhow, bail, Context, Result};
use clap::{Args, Subcommand};
use serde_json::json;
use crate::api::types::ApiKeyRecord;
use crate::commands::provision::{client_from_config, developer_session, resolve_app_id};
use crate::config::CliConfig;
use crate::output;
#[derive(Subcommand)]
pub enum KeysCommand {
List(ListArgs),
Create(CreateArgs),
Revoke(RevokeArgs),
Rotate(RotateArgs),
}
#[derive(Args)]
pub struct ListArgs {
#[arg(long)]
pub app_id: Option<String>,
#[arg(long)]
pub json: bool,
}
#[derive(Args)]
pub struct CreateArgs {
pub alias: String,
#[arg(long, default_value = "all")]
pub product: String,
#[arg(long, default_value = "full_access")]
pub permissions: String,
#[arg(long)]
pub app_id: Option<String>,
#[arg(long)]
pub json: bool,
#[arg(long)]
pub set_default: bool,
}
#[derive(Args)]
pub struct RevokeArgs {
pub key: String,
#[arg(long)]
pub app_id: Option<String>,
#[arg(long, short = 'y')]
pub yes: bool,
#[arg(long)]
pub json: bool,
}
#[derive(Args)]
pub struct RotateArgs {
pub key: String,
#[arg(long)]
pub app_id: Option<String>,
#[arg(long, short = 'y')]
pub yes: bool,
#[arg(long)]
pub json: bool,
#[arg(long)]
pub set_default: bool,
}
pub async fn run(command: KeysCommand) -> Result<()> {
match command {
KeysCommand::List(list) => list_keys(list).await,
KeysCommand::Create(create) => create_key(create).await,
KeysCommand::Revoke(revoke) => revoke_key(revoke).await,
KeysCommand::Rotate(rotate) => rotate_key(rotate).await,
}
}
async fn list_keys(args: ListArgs) -> Result<()> {
let mut config = CliConfig::load()?;
let token = developer_session(&mut config, "keys").await?;
let app_id = resolve_app_id(&config, args.app_id.as_deref())?;
let client = client_from_config(&config).await?;
let keys = client.list_api_keys(&token, &app_id).await?;
if args.json {
output::json(&json!({ "appId": app_id, "keys": keys }))?;
return Ok(());
}
output::heading(&format!("api keys for {app_id}"));
if keys.is_empty() {
output::note("no keys — run `offline keys create \"CLI default\"`");
return Ok(());
}
for key in &keys {
let name = key.name.as_deref().unwrap_or("(unnamed)");
let product = key.product.as_deref().unwrap_or("?");
let status = key.status.as_deref().unwrap_or("?");
let preview = key.key_preview.as_deref().unwrap_or("");
let id = key.id.as_deref().unwrap_or("?");
let this_machine = if is_stored_key(&config, &app_id, key) {
" (used by this CLI)"
} else {
""
};
println!(" {name} {preview} product={product} status={status} id={id}{this_machine}");
}
output::note("revoke with `offline keys revoke <id or name>`, replace with `offline keys rotate <id or name>`");
Ok(())
}
async fn create_key(args: CreateArgs) -> Result<()> {
let mut config = CliConfig::load()?;
let token = developer_session(&mut config, "keys").await?;
let app_id = resolve_app_id(&config, args.app_id.as_deref())?;
let client = client_from_config(&config).await?;
let product = match args.product.as_str() {
"all" | "offline_id" | "mesh_sdk" | "proof_of_location" => args.product.clone(),
other => bail!(
"unsupported product `{other}` — use all, offline_id, mesh_sdk, or proof_of_location"
),
};
let key = client
.create_api_key(&token, &app_id, &args.alias, &product, &args.permissions)
.await?;
let api_key = secret_of(&key)?;
if args.set_default {
store_as_default(&mut config, &app_id, &api_key)?;
}
if args.json {
output::json(&json!({
"appId": app_id,
"key": key,
"setDefault": args.set_default,
}))?;
return Ok(());
}
output::success(&format!(
"created API key `{}` for application `{app_id}`",
args.alias
));
output::warn("Copy this key now — it will not be shown again:");
println!(" {api_key}");
if !args.set_default {
output::note("Run with --set-default to store it as the active CLI credential");
}
Ok(())
}
async fn revoke_key(args: RevokeArgs) -> Result<()> {
let mut config = CliConfig::load()?;
let token = developer_session(&mut config, "keys").await?;
let app_id = resolve_app_id(&config, args.app_id.as_deref())?;
let client = client_from_config(&config).await?;
let keys = client.list_api_keys(&token, &app_id).await?;
let key = find_key(&keys, &args.key)?;
let key_id = key
.id
.clone()
.ok_or_else(|| anyhow!("the server listed this key without an id"))?;
let label = describe(key);
let was_stored = is_stored_key(&config, &app_id, key);
let mut prompt =
format!("Revoke {label} on `{app_id}`? Apps and servers using it stop working.");
if was_stored {
prompt.push_str(" This CLI uses this key too.");
}
confirm(&prompt, args.yes)?;
client.revoke_api_key(&token, &app_id, &key_id).await?;
if was_stored {
forget_stored_key(&mut config, &app_id)?;
}
if args.json {
output::json(&json!({
"appId": app_id,
"revoked": { "id": key_id, "name": key.name },
"removedFromCliConfig": was_stored,
}))?;
return Ok(());
}
output::success(&format!("revoked {label} on `{app_id}`"));
if was_stored {
output::warn("This CLI was using that key, so it was removed from your local config.");
output::note(
"Run `offline setup` or `offline keys create <name> --set-default` to get a new one",
);
}
Ok(())
}
async fn rotate_key(args: RotateArgs) -> Result<()> {
let mut config = CliConfig::load()?;
let token = developer_session(&mut config, "keys").await?;
let app_id = resolve_app_id(&config, args.app_id.as_deref())?;
let client = client_from_config(&config).await?;
let keys = client.list_api_keys(&token, &app_id).await?;
let old = find_key(&keys, &args.key)?;
let old_id = old
.id
.clone()
.ok_or_else(|| anyhow!("the server listed this key without an id"))?;
let label = describe(old);
let name = old
.name
.clone()
.unwrap_or_else(|| "rotated key".to_string());
let product = old.product.clone().unwrap_or_else(|| "all".to_string());
let permissions = old
.permissions
.clone()
.unwrap_or_else(|| "full_access".to_string());
let was_stored = is_stored_key(&config, &app_id, old);
confirm(
&format!(
"Rotate {label} on `{app_id}`? A new key replaces it and the old one is revoked right away."
),
args.yes,
)?;
let new_key = client
.create_api_key(&token, &app_id, &name, &product, &permissions)
.await
.context("creating the replacement key; the old key was not changed")?;
let secret = secret_of(&new_key)?;
let store = args.set_default || was_stored;
if store {
store_as_default(&mut config, &app_id, &secret)?;
}
if let Err(err) = client.revoke_api_key(&token, &app_id, &old_id).await {
if !args.json {
output::warn(
"Created the new key, but revoking the old one failed. Copy the new key now:",
);
println!(" {secret}");
}
return Err(err.context(format!(
"the old key {label} is still active; revoke it with `offline keys revoke {old_id}`"
)));
}
if args.json {
output::json(&json!({
"appId": app_id,
"revoked": { "id": old_id, "name": old.name },
"key": new_key,
"setDefault": store,
}))?;
return Ok(());
}
output::success(&format!(
"rotated {label} on `{app_id}`: the old key is revoked"
));
output::warn("Copy the new key now — it will not be shown again:");
println!(" {secret}");
if store {
output::note("Stored as the active CLI credential");
}
Ok(())
}
fn find_key<'a>(keys: &'a [ApiKeyRecord], wanted: &str) -> Result<&'a ApiKeyRecord> {
let wanted = wanted.trim();
if let Some(key) = keys.iter().find(|k| k.id.as_deref() == Some(wanted)) {
return Ok(key);
}
let by_name: Vec<&ApiKeyRecord> = keys
.iter()
.filter(|k| k.name.as_deref() == Some(wanted))
.collect();
match by_name.as_slice() {
[key] => Ok(key),
[] => bail!("no API key with id or name `{wanted}` — run `offline keys list` to see them"),
many => {
let ids: Vec<&str> = many.iter().filter_map(|k| k.id.as_deref()).collect();
bail!(
"{} keys are named `{wanted}`; pass one of their ids instead: {}",
many.len(),
ids.join(", ")
)
}
}
}
fn describe(key: &ApiKeyRecord) -> String {
let name = key.name.as_deref().unwrap_or("(unnamed)");
match key.key_preview.as_deref() {
Some(preview) if !preview.is_empty() => format!("key `{name}` ({preview})"),
_ => format!("key `{name}`"),
}
}
fn is_stored_key(config: &CliConfig, app_id: &str, key: &ApiKeyRecord) -> bool {
let Some(preview) = key.key_preview.as_deref() else {
return false;
};
let last4: String = preview.chars().filter(|c| *c != '\u{2026}').collect();
if last4.len() != 4 {
return false;
}
config
.app_keys
.get(app_id)
.or(if config.app_id.as_deref() == Some(app_id) {
config.api_key.as_ref()
} else {
None
})
.is_some_and(|secret| secret.ends_with(&last4))
}
fn secret_of(key: &ApiKeyRecord) -> Result<String> {
key.key
.clone()
.filter(|k| !k.is_empty())
.ok_or_else(|| anyhow!("create API key response missing key value"))
}
fn store_as_default(config: &mut CliConfig, app_id: &str, api_key: &str) -> Result<()> {
config
.app_keys
.insert(app_id.to_string(), api_key.to_string());
config.api_key = Some(api_key.to_string());
config.app_id = Some(app_id.to_string());
config.save()
}
fn forget_stored_key(config: &mut CliConfig, app_id: &str) -> Result<()> {
let removed = config.app_keys.remove(app_id);
if config.app_id.as_deref() == Some(app_id) && (removed.is_none() || config.api_key == removed)
{
config.api_key = None;
}
config.save()
}
fn confirm(prompt: &str, yes: bool) -> Result<()> {
use std::io::IsTerminal;
if yes {
return Ok(());
}
if !std::io::stdin().is_terminal() {
bail!("refusing to change keys without confirmation; pass --yes to run non-interactively");
}
let go = dialoguer::Confirm::new()
.with_prompt(prompt)
.default(false)
.interact()
.context("reading confirmation")?;
if !go {
bail!("cancelled; no key was changed");
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn key(id: &str, name: &str, preview: &str) -> ApiKeyRecord {
ApiKeyRecord {
key: None,
name: Some(name.into()),
id: Some(id.into()),
application_id: Some("app_1".into()),
product: Some("all".into()),
permissions: Some("full_access".into()),
status: Some("active".into()),
key_preview: Some(preview.into()),
created_at: None,
}
}
#[test]
fn find_key_prefers_id_then_unique_name() {
let keys = vec![
key("id-1", "server", "\u{2026}aaaa"),
key("id-2", "ci", "\u{2026}bbbb"),
];
assert_eq!(find_key(&keys, "id-2").unwrap().id.as_deref(), Some("id-2"));
assert_eq!(
find_key(&keys, "server").unwrap().id.as_deref(),
Some("id-1")
);
assert!(find_key(&keys, "missing").is_err());
}
#[test]
fn find_key_refuses_ambiguous_names() {
let keys = vec![
key("id-1", "dup", "\u{2026}aaaa"),
key("id-2", "dup", "\u{2026}bbbb"),
];
let err = find_key(&keys, "dup").unwrap_err().to_string();
assert!(err.contains("id-1") && err.contains("id-2"), "{err}");
}
#[test]
fn stored_key_matches_on_last_four() {
let mut config = CliConfig::default();
config
.app_keys
.insert("app_1".into(), "op_secret_abcd".into());
assert!(is_stored_key(
&config,
"app_1",
&key("id-1", "k", "\u{2026}abcd")
));
assert!(!is_stored_key(
&config,
"app_1",
&key("id-1", "k", "\u{2026}wxyz")
));
assert!(!is_stored_key(
&config,
"app_2",
&key("id-1", "k", "\u{2026}abcd")
));
}
#[test]
fn stored_key_falls_back_to_active_credential() {
let config = CliConfig {
api_key: Some("op_secret_abcd".into()),
app_id: Some("app_1".into()),
..CliConfig::default()
};
assert!(is_stored_key(
&config,
"app_1",
&key("id-1", "k", "\u{2026}abcd")
));
}
}