diff --git a/Cargo.toml b/Cargo.toml index 00b30b2..403e677 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -26,6 +26,7 @@ comfy-table = "7.2.2" webbrowser = "1" console = "0.16.2" chrono = "0.4" +uuid = "1" axoupdater = { version = "0.10.2", default-features = false, features = ["blocking", "github_releases"] } [dev-dependencies] diff --git a/README.md b/README.md index 51d47ab..ddb9551 100644 --- a/README.md +++ b/README.md @@ -191,7 +191,7 @@ API keys remain restricted to their bound cluster regardless of which selector s Top-level commands: - `login`, `logout` -- `database`, `organization`, `integration`, `service-account`, `federation-issuer`, `federation-rule`, `cluster`, `key`, `table`, `workflow` +- `database`, `organization`, `integration`, `service-account`, `federation-issuer`, `federation-rule`, `cluster`, `api-key`, `table`, `workflow` - `query`, `insert` - `ping`, `docs`, `status`, `open`, `completions` @@ -411,10 +411,10 @@ With `--json`, the result is ### Keys and tables ```sh -rtree key list -rtree key create --name ci --permission read_write -rtree key create --name temporary-ci --permission read_only --expires-at 2027-01-01T00:00:00Z -rtree key create --database analytics --name analytics-ci --permission read_write +rtree api-key list +rtree api-key create --name ci --permission read_write +rtree api-key create --name temporary-ci --permission read_only --expires-at 2027-01-01T00:00:00Z +rtree api-key create --database analytics --name analytics-ci --permission read_write rtree table list --database analytics rtree table describe --database analytics events @@ -424,16 +424,19 @@ rtree table update --database analytics events --sorting-key 'region, toStartOfH Omit `--sorting-key` when creating a table to choose a key automatically per part. `table describe` shows the current sorting key as a string. Updating the key affects new parts and later merges; existing parts may keep their previous key until they are merged. A custom sorting key cannot be reset to automatic. -API keys belong to a cluster. `key list` and `key delete` do not accept `--database`; -listing includes each key's default database. `key create --database` selects the +Use `rtree api-key delete ` to revoke a key by its UUID from `api-key list`. +Deletion requires the UUID; full API key tokens are not accepted. + +API keys belong to a cluster. `api-key list` and `api-key delete` do not accept `--database`; +listing includes each key's default database. `api-key create --database` selects the new key's default database, using `RAWTREE_DATABASE` or the saved selection when omitted. If none is selected, the server uses `default`. -`key create --expires-at` accepts a future RFC 3339 timestamp with a timezone. +`api-key create --expires-at` accepts a future RFC 3339 timestamp with a timezone. The server validates and normalizes it to UTC. Omit the flag for a key that never expires. Create/list output includes expiration (`never` in text, `null` in JSON); older servers that omit the field are also supported. Expiration is fixed at -creation; create a replacement key to change it. There is no `key update` command. +creation; create a replacement key to change it. There is no `api-key update` command. ### Workflows diff --git a/src/cli.rs b/src/cli.rs index 5b507e6..5da4400 100644 --- a/src/cli.rs +++ b/src/cli.rs @@ -125,10 +125,9 @@ pub enum Command { action: DatabaseCommand, }, /// Manage API keys - #[command(name = "key")] - Key { + ApiKey { #[command(subcommand)] - action: KeyCommand, + action: ApiKeyCommand, }, /// Manage organizations Organization { @@ -444,7 +443,7 @@ pub enum ClusterCommand { } #[derive(Subcommand)] -pub enum KeyCommand { +pub enum ApiKeyCommand { /// List API keys for a cluster List, /// Create a new API key @@ -464,8 +463,8 @@ pub enum KeyCommand { }, /// Delete an API key Delete { - /// Key ID or full API key token to delete - id_or_token: String, + /// API key UUID to delete + id: uuid::Uuid, }, } diff --git a/src/cli/tests.rs b/src/cli/tests.rs index 8e0bc17..86dab63 100644 --- a/src/cli/tests.rs +++ b/src/cli/tests.rs @@ -1,5 +1,5 @@ use super::{ - Cli, ClusterCommand, ClusterSizeArg, Command, KeyCommand, TableCommand, WorkflowCommand, + ApiKeyCommand, Cli, ClusterCommand, ClusterSizeArg, Command, TableCommand, WorkflowCommand, }; use clap::{error::ErrorKind, CommandFactory, Parser}; @@ -414,12 +414,12 @@ fn query_format_flag_is_rejected() { } #[test] -fn key_command_is_singular() { - let cli = Cli::try_parse_from(["rtree", "key", "list"]).unwrap(); +fn api_key_command_is_singular() { + let cli = Cli::try_parse_from(["rtree", "api-key", "list"]).unwrap(); assert!(matches!( cli.command, - Command::Key { - action: KeyCommand::List + Command::ApiKey { + action: ApiKeyCommand::List } )); } @@ -427,12 +427,12 @@ fn key_command_is_singular() { #[test] fn cluster_scoped_commands_reject_obsolete_database_flags() { for args in [ - vec!["rtree", "key", "list", "--database", "analytics"], + vec!["rtree", "api-key", "list", "--database", "analytics"], vec![ "rtree", - "key", + "api-key", "delete", - "key-id", + "11111111-1111-4111-8111-111111111111", "--database", "analytics", ], @@ -450,16 +450,23 @@ fn cluster_scoped_commands_reject_obsolete_database_flags() { } #[test] -fn keys_command_is_rejected() { - let result = Cli::try_parse_from(["rtree", "keys", "list", "--database", "analytics"]); - assert!(result.is_err(), "keys should not be accepted as a command"); +fn obsolete_key_commands_are_rejected() { + for name in ["key", "keys", "api-keys"] { + assert_eq!( + Cli::try_parse_from(["rtree", name, "list"]) + .err() + .expect("obsolete command must fail") + .kind(), + ErrorKind::InvalidSubcommand, + ); + } } #[test] fn key_create_uses_name_flag() { let cli = Cli::try_parse_from([ "rtree", - "key", + "api-key", "create", "--database", "analytics", @@ -468,16 +475,16 @@ fn key_create_uses_name_flag() { "--permission", "read_write", ]) - .expect("key create with --name should parse"); + .expect("api-key create with --name should parse"); match cli.command { - Command::Key { action } => match action { - KeyCommand::Create { name, .. } => { + Command::ApiKey { action } => match action { + ApiKeyCommand::Create { name, .. } => { assert_eq!(name, "ci"); } - _ => panic!("expected key create command"), + _ => panic!("expected api-key create command"), }, - _ => panic!("expected key command"), + _ => panic!("expected api-key command"), } } @@ -485,7 +492,7 @@ fn key_create_uses_name_flag() { fn key_create_label_flag_is_rejected() { let result = Cli::try_parse_from([ "rtree", - "key", + "api-key", "create", "--database", "analytics", @@ -494,7 +501,10 @@ fn key_create_label_flag_is_rejected() { "--permission", "read_write", ]); - assert!(result.is_err(), "key create should use --name, not --label"); + assert!( + result.is_err(), + "api-key create should use --name, not --label" + ); } #[test] diff --git a/src/commands/auth.rs b/src/commands/auth.rs index e876d96..619f96c 100644 --- a/src/commands/auth.rs +++ b/src/commands/auth.rs @@ -191,8 +191,8 @@ fn api_key_context_paths( cli_database: Option<&str>, ) -> (String, String) { let keys_path = cli_database - .map(|database| org::database_scoped_path(database, "/keys", cli_org, cli_cluster)) - .unwrap_or_else(|| org::scoped_path("/v1/keys", cli_org, cli_cluster)); + .map(|database| org::database_scoped_path(database, "/api-keys", cli_org, cli_cluster)) + .unwrap_or_else(|| org::scoped_path("/v1/api-keys", cli_org, cli_cluster)); let tables_path = cli_database .map(|database| org::database_scoped_path(database, "/tables", cli_org, cli_cluster)) .unwrap_or_else(|| org::scoped_path("/v1/tables", cli_org, cli_cluster)); @@ -714,7 +714,7 @@ mod tests { fn api_key_context_paths_do_not_invent_organization() { let (keys_path, tables_path) = api_key_context_paths(None, None, Some("analytics")); - assert_eq!(keys_path, "/v1/keys?database=analytics"); + assert_eq!(keys_path, "/v1/api-keys?database=analytics"); assert_eq!(tables_path, "/v1/tables?database=analytics"); } @@ -725,7 +725,7 @@ mod tests { assert_eq!( keys_path, - "/v1/keys?database=analytics&organization=team%20alpha&cluster=prod%2Feu" + "/v1/api-keys?database=analytics&organization=team%20alpha&cluster=prod%2Feu" ); assert_eq!( tables_path, diff --git a/src/commands/keys.rs b/src/commands/keys.rs index 9995086..1d0805c 100644 --- a/src/commands/keys.rs +++ b/src/commands/keys.rs @@ -65,7 +65,7 @@ pub fn list( cluster: Option<&str>, json_mode: bool, ) -> Result<()> { - let path = org::scoped_path("/v1/keys", organization, cluster); + let path = org::scoped_path("/v1/api-keys", organization, cluster); let resp: ListApiKeysResponse = client.get(&path)?; output::print_result(&resp, json_mode, |_| { if resp.keys.is_empty() { @@ -105,8 +105,8 @@ pub fn create( json_mode: bool, ) -> Result<()> { let path = match database { - Some(database) => org::database_scoped_path(database, "/keys", organization, cluster), - None => org::scoped_path("/v1/keys", organization, cluster), + Some(database) => org::database_scoped_path(database, "/api-keys", organization, cluster), + None => org::scoped_path("/v1/api-keys", organization, cluster), }; let resp: CreateApiKeyResponse = client.post(&path, &serde_json::to_value(request)?)?; output::print_result(&resp, json_mode, |_| { @@ -127,18 +127,17 @@ pub fn delete( client: &ApiClient, organization: Option<&str>, cluster: Option<&str>, - id_or_token: &str, + id: uuid::Uuid, json_mode: bool, ) -> Result<()> { - let encoded_key = urlencoding::encode(id_or_token); - let path = org::scoped_path(&format!("/v1/keys/{encoded_key}"), organization, cluster); + let path = org::scoped_path(&format!("/v1/api-keys/{id}"), organization, cluster); let resp: DeleteApiKeyResponse = client.delete(&path)?; output::print_result( - &json!({"deleted": resp.deleted, "id_or_token": id_or_token}), + &json!({"deleted": resp.deleted, "id": id.to_string()}), json_mode, |_| { if resp.deleted { - println!("API key '{}' deleted.", id_or_token); + println!("API key '{}' deleted.", id); } }, ); diff --git a/src/main.rs b/src/main.rs index ae248a7..c32f33b 100644 --- a/src/main.rs +++ b/src/main.rs @@ -17,9 +17,9 @@ use clap::{CommandFactory, Parser}; use clap_complete::generate; use cli::{ - Cli, ClusterCommand, Command, DatabaseCommand, IntegrationCommand, IntegrationKind, KeyCommand, - OrganizationCommand, ServiceAccountCommand, ShellType, TableCommand, WorkflowCommand, - WorkflowSinkCommand, + ApiKeyCommand, Cli, ClusterCommand, Command, DatabaseCommand, IntegrationCommand, + IntegrationKind, OrganizationCommand, ServiceAccountCommand, ShellType, TableCommand, + WorkflowCommand, WorkflowSinkCommand, }; use client::ApiClient; use constants::DEFAULT_API_URL; @@ -412,16 +412,16 @@ fn run(cli: Cli) -> Result { } } } - Command::Key { action } => { + Command::ApiKey { action } => { let effective_org = resolve_effective_org(&client, cli_org.clone()); match action { - KeyCommand::List => commands::keys::list( + ApiKeyCommand::List => commands::keys::list( &client, effective_org.as_deref(), effective_cluster.as_deref(), json, ), - KeyCommand::Create { + ApiKeyCommand::Create { database, name, permission, @@ -441,11 +441,11 @@ fn run(cli: Cli) -> Result { json, ) } - KeyCommand::Delete { id_or_token } => commands::keys::delete( + ApiKeyCommand::Delete { id } => commands::keys::delete( &client, effective_org.as_deref(), effective_cluster.as_deref(), - &id_or_token, + id, json, ), } diff --git a/tests/api_contracts.rs b/tests/api_contracts.rs index 229b2b0..3bb6549 100644 --- a/tests/api_contracts.rs +++ b/tests/api_contracts.rs @@ -102,21 +102,24 @@ fn key_list_and_delete_are_cluster_scoped_even_with_a_saved_database() { ]}); for config in [json!({}), config] { let (result, _, _) = run( - &["key", "list"], + &["api-key", "list"], "GET", - "/v1/keys?organization=team%20alpha&cluster=prod%2Feu", + "/v1/api-keys?organization=team%20alpha&cluster=prod%2Feu", response.clone(), config.clone(), ); assert_eq!(result, response); let (result, _, _) = run( - &["key", "delete", "key-1"], + &["api-key", "delete", "11111111-1111-4111-8111-111111111111"], "DELETE", - "/v1/keys/key-1?organization=team%20alpha&cluster=prod%2Feu", + "/v1/api-keys/11111111-1111-4111-8111-111111111111?organization=team%20alpha&cluster=prod%2Feu", json!({"deleted": true}), config, ); - assert_eq!(result["deleted"], true); + assert_eq!( + result, + json!({"deleted": true, "id": "11111111-1111-4111-8111-111111111111"}) + ); } } @@ -144,7 +147,7 @@ fn key_create_uses_server_default_or_an_explicit_or_saved_database() { ] { let response = json!({"id": "key-1", "token": "rt_fixture", "name": "ci", "permission": "read_write", "expires_at": null, "database": {"name": database}}); let mut args = vec![ - "key", + "api-key", "create", "--name", "ci", @@ -155,7 +158,7 @@ fn key_create_uses_server_default_or_an_explicit_or_saved_database() { let (result, _, body) = run( &args, "POST", - &format!("/v1/keys?{query}"), + &format!("/v1/api-keys?{query}"), response.clone(), config, ); diff --git a/tests/api_key_commands.rs b/tests/api_key_commands.rs new file mode 100644 index 0000000..b1ebac5 --- /dev/null +++ b/tests/api_key_commands.rs @@ -0,0 +1,35 @@ +mod common; + +use serde_json::json; + +#[test] +fn delete_rejects_tokens_and_malformed_ids_before_authentication() { + for id in [ + "rt_secret_token", + "key-1", + "", + "abcdef0123456789abcdef0123456789abcdef0123456789abcdef0123456789", + ] { + let (output, config, bodies) = common::run_cli(&[], &["api-key", "delete", id], &json!({})); + assert_eq!(output.status.code(), Some(2)); + let error = String::from_utf8(output.stderr).unwrap(); + assert!(error.contains("invalid value"), "{error}"); + assert!(error.contains(""), "{error}"); + assert!(output.stdout.is_empty()); + assert_eq!(config, json!({})); + assert!(bodies.is_empty()); + } +} + +#[test] +fn delete_help_documents_uuid_input() { + let (output, _, _) = common::run_cli(&[], &["api-key", "delete", "--help"], &json!({})); + assert!(output.status.success()); + let help = String::from_utf8(output.stdout).unwrap(); + assert!( + help.contains("rtree api-key delete [OPTIONS] "), + "{help}" + ); + assert!(help.contains("API key UUID to delete"), "{help}"); + assert!(!help.contains("ID_OR_TOKEN"), "{help}"); +} diff --git a/tests/api_key_expiration.rs b/tests/api_key_expiration.rs index 23918a4..9794672 100644 --- a/tests/api_key_expiration.rs +++ b/tests/api_key_expiration.rs @@ -16,13 +16,13 @@ fn create_sends_expiration_and_preserves_normalized_response() { let expected = key(Some(json!("2027-01-01T00:00:00Z"))); let (output, _, bodies) = common::run_cli( &[( - "POST /v1/keys?organization=team&cluster=prod".into(), + "POST /v1/api-keys?organization=team&cluster=prod".into(), "200 OK", expected.clone(), )], &[ "--json", - "key", + "api-key", "create", "--name", "ci", @@ -58,13 +58,20 @@ fn create_and_list_display_expiration_or_never_in_text_and_json() { response_key["created_at"] = json!("2026-10-01T00:00:00Z"); ( "GET", - vec!["key", "list"], + vec!["api-key", "list"], json!({"keys": [response_key.clone()]}), ) } else { ( "POST", - vec!["key", "create", "--name", "ci", "--permission", "read_only"], + vec![ + "api-key", + "create", + "--name", + "ci", + "--permission", + "read_only", + ], response_key.clone(), ) }; @@ -73,7 +80,7 @@ fn create_and_list_display_expiration_or_never_in_text_and_json() { } let (output, _, bodies) = common::run_cli( &[( - format!("{method} /v1/keys?organization=team&cluster=prod"), + format!("{method} /v1/api-keys?organization=team&cluster=prod"), "200 OK", response, )], @@ -118,12 +125,12 @@ fn create_and_list_display_expiration_or_never_in_text_and_json() { fn create_surfaces_backend_expiration_validation_errors() { let (output, _, bodies) = common::run_cli( &[( - "POST /v1/keys?organization=team&cluster=prod".into(), + "POST /v1/api-keys?organization=team&cluster=prod".into(), "400 Bad Request", json!({"error":"bad_request", "message":"Invalid expiration date.", "hint":"expires_at must be in the future."}), )], &[ - "key", + "api-key", "create", "--name", "ci", @@ -146,10 +153,10 @@ fn list_preserves_database_role_keys_and_expiration() { "database_roles": ["reader", "writer"], "database": {"name": "default"}, "created_at": "2026-10-01T00:00:00Z", "expires_at": "2027-01-01T00:00:00Z" }]}); - for args in [vec!["--json", "key", "list"], vec!["key", "list"]] { + for args in [vec!["--json", "api-key", "list"], vec!["api-key", "list"]] { let (output, _, _) = common::run_cli( &[( - "GET /v1/keys?organization=team&cluster=prod".into(), + "GET /v1/api-keys?organization=team&cluster=prod".into(), "200 OK", response.clone(), )], diff --git a/tests/api_key_login.rs b/tests/api_key_login.rs index b899422..0fbf920 100644 --- a/tests/api_key_login.rs +++ b/tests/api_key_login.rs @@ -27,7 +27,7 @@ fn api_key_login_accepts_current_responses_and_replaces_stale_defaults() { } else { "" }; - let keys = format!("/v1/keys{query}"); + let keys = format!("/v1/api-keys{query}"); let tables = format!("/v1/tables{query}"); let responses = if fallback { vec![ @@ -92,7 +92,7 @@ fn api_key_login_failures_preserve_saved_credentials() { ] { let (output, saved, original) = login( &[ - ("/v1/keys?cluster=other", status, body.clone()), + ("/v1/api-keys?cluster=other", status, body.clone()), ("/v1/tables?cluster=other", status, body), ], &["--cluster", "other"], @@ -107,7 +107,7 @@ fn api_key_login_failures_preserve_saved_credentials() { fn api_key_login_preserves_legacy_response_metadata() { let (output, saved, _) = login( &[( - "/v1/keys", + "/v1/api-keys", "200 OK", json!({ "keys": [], "organization": {"name": "team"}, "database": {"name": "analytics"} diff --git a/tests/browser_login.rs b/tests/browser_login.rs index 2e3e213..577a6a4 100644 --- a/tests/browser_login.rs +++ b/tests/browser_login.rs @@ -380,7 +380,7 @@ fn device_authentication_errors_preserve_config() { #[test] fn api_key_login_defaults_to_json_without_device_approval() { - let responses = [("GET /v1/keys".into(), "200 OK", json!({"keys": []}))]; + let responses = [("GET /v1/api-keys".into(), "200 OK", json!({"keys": []}))]; let (output, saved, _) = common::run_cli( &responses, &["login", "--api-key", "rt_test_fixture"], diff --git a/tests/live_platform.rs b/tests/live_platform.rs index 81e05e4..1e50ef5 100644 --- a/tests/live_platform.rs +++ b/tests/live_platform.rs @@ -230,7 +230,7 @@ fn cli_data_and_api_key_flow_through_real_platform() { ); let key = cli.json(&[ - "key", + "api-key", "create", "--database", &database, @@ -256,6 +256,9 @@ fn cli_data_and_api_key_flow_through_real_platform() { ]); assert_eq!(login["success"], true); assert_eq!(login["database"], database); + let rejected = cli.execute(&["api-key", "delete", key_token], Some(&cli.token)); + assert_eq!(rejected.status.code(), Some(2)); + // Rejected token deletion leaves the key usable through its saved login. // With no token in the environment, the CLI must use the key saved by login. let key_query = cli.json_with_token( &[ @@ -267,7 +270,7 @@ fn cli_data_and_api_key_flow_through_real_platform() { None, ); assert_eq!(key_query["data"], queried["data"]); - assert_eq!(cli.json(&["key", "delete", key_id])["deleted"], true); + assert_eq!(cli.json(&["api-key", "delete", key_id])["deleted"], true); let deleted = cli.json(&["database", "delete", &database]); assert_eq!(deleted, json!({"deleted": true, "name": database})); diff --git a/tests/oauth_login.rs b/tests/oauth_login.rs index 3e2eed5..123c972 100644 --- a/tests/oauth_login.rs +++ b/tests/oauth_login.rs @@ -299,7 +299,7 @@ fn logout_revokes_without_refresh_and_retains_credentials_on_failure() { #[test] fn api_key_login_clears_old_oauth_state() { - let responses = [("GET /v1/keys".into(), "200 OK", json!({"keys":[]}))]; + let responses = [("GET /v1/api-keys".into(), "200 OK", json!({"keys":[]}))]; let (output, saved, _) = common::run_cli( &responses, &["login", "--api-key", "rt_explicit"], diff --git a/tests/oauth_refresh.rs b/tests/oauth_refresh.rs index df586cd..b17d082 100644 --- a/tests/oauth_refresh.rs +++ b/tests/oauth_refresh.rs @@ -210,7 +210,7 @@ fn key_precedence_and_device_override_apply_to_real_requests() { assert!(first.starts_with("POST /v1/auth/cli/device/start ")); reply(socket, json!({})); // Stop at malformed response; no browser or poll. } else if login { - assert!(first.starts_with("GET /v1/keys ")); + assert!(first.starts_with("GET /v1/api-keys ")); reply(socket, json!({"keys":[]})); } else { reply(socket, json!({"organizations":[]})); @@ -330,7 +330,7 @@ fn api_key_validation_does_not_hold_the_config_lock() { .spawn() .unwrap(); let (socket, first, _) = request(&listener); - assert!(first.starts_with("GET /v1/keys ")); + assert!(first.starts_with("GET /v1/api-keys ")); let mut selection = command(home.path(), &url, &["organization", "use", "other"]) .spawn() .unwrap();