diff --git a/Cargo.lock b/Cargo.lock index 026a9cff..040b601b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -7,6 +7,7 @@ name = "admin" version = "0.0.0" dependencies = [ "rt", + "sys", ] [[package]] diff --git a/crates/admin/Cargo.toml b/crates/admin/Cargo.toml index 86e05d58..0fc6087f 100644 --- a/crates/admin/Cargo.toml +++ b/crates/admin/Cargo.toml @@ -9,6 +9,7 @@ autotests = false [dependencies] rt = { path = "../rt" } +sys = { path = "../sys" } [[test]] name = "admin" diff --git a/crates/admin/src/proto.rs b/crates/admin/src/proto.rs index 58e33bc7..414aa7bc 100644 --- a/crates/admin/src/proto.rs +++ b/crates/admin/src/proto.rs @@ -15,6 +15,9 @@ const POOL_LIST: u8 = 7; const QUEUE_LIST: u8 = 8; const QUEUE_RETRY: u8 = 9; const QUEUE_REBIND: u8 = 10; +const KEY_CREATE: u8 = 11; +const KEY_REVOKE: u8 = 12; +const KEY_LIST: u8 = 13; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Error { @@ -60,9 +63,34 @@ pub enum Request { TenantResume(u32), PoolSet(PoolSpec), PoolList(u32), - QueueList { tenant: u32, from: u32 }, - QueueRetry { tenant: u32, queue: u32 }, - QueueRebind { tenant: u32, queue: u32, pool: u32 }, + QueueList { + tenant: u32, + from: u32, + }, + QueueRetry { + tenant: u32, + queue: u32, + }, + QueueRebind { + tenant: u32, + queue: u32, + pool: u32, + }, + KeyCreate { + tenant: u32, + smtp: bool, + api: bool, + hooks: bool, + pool: u32, + }, + KeyRevoke { + tenant: u32, + id: u32, + }, + KeyList { + tenant: u32, + from: u32, + }, } impl Request { @@ -136,6 +164,28 @@ impl Request { body.extend_from_slice(&queue.to_be_bytes()); body.extend_from_slice(&pool.to_be_bytes()); } + Self::KeyCreate { + tenant, + smtp, + api, + hooks, + pool, + } => { + body.push(KEY_CREATE); + body.extend_from_slice(&tenant.to_be_bytes()); + body.push(u8::from(*smtp) | u8::from(*api) << 1 | u8::from(*hooks) << 2); + body.extend_from_slice(&pool.to_be_bytes()); + } + Self::KeyRevoke { tenant, id } => { + body.push(KEY_REVOKE); + body.extend_from_slice(&tenant.to_be_bytes()); + body.extend_from_slice(&id.to_be_bytes()); + } + Self::KeyList { tenant, from } => { + body.push(KEY_LIST); + body.extend_from_slice(&tenant.to_be_bytes()); + body.extend_from_slice(&from.to_be_bytes()); + } } framed(&body) } @@ -190,6 +240,28 @@ impl Request { queue: fields.u32()?, pool: fields.u32()?, }, + KEY_CREATE => { + let tenant = fields.u32()?; + let scopes = fields.u8()?; + if scopes & !7 != 0 { + return Err(Error::Body); + } + Self::KeyCreate { + tenant, + smtp: scopes & 1 != 0, + api: scopes & 2 != 0, + hooks: scopes & 4 != 0, + pool: fields.u32()?, + } + } + KEY_REVOKE => Self::KeyRevoke { + tenant: fields.u32()?, + id: fields.u32()?, + }, + KEY_LIST => Self::KeyList { + tenant: fields.u32()?, + from: fields.u32()?, + }, _ => return Err(Error::Command), }; if !fields.0.is_empty() { diff --git a/crates/admin/src/server.rs b/crates/admin/src/server.rs index 9ee48b6d..d2ff9ab5 100644 --- a/crates/admin/src/server.rs +++ b/crates/admin/src/server.rs @@ -135,8 +135,19 @@ async fn session(stream: &UnixStream, handler: &H, state: &Shared) { Reply::new(Code::Refused, error.to_string()) } }; - let written = timeout(IDLE, stream.write_all(Buf::from_slice(&reply.encode()))).await; - if !matches!(written, Ok((Ok(()), _))) { + let mut encoded = reply.encode(); + let written = timeout(IDLE, stream.write_all(Buf::from_slice(&encoded))).await; + let sent = match written { + Ok((result, mut buf)) => { + sys::mem::wipe(&mut buf); + result.is_ok() + } + Err(_) => false, + }; + sys::mem::wipe(&mut encoded); + let mut text = reply.text.into_bytes(); + sys::mem::wipe(&mut text); + if !sent { return; } } diff --git a/crates/admin/tests/proto.rs b/crates/admin/tests/proto.rs index 4d3c12a6..d4dcb92e 100644 --- a/crates/admin/tests/proto.rs +++ b/crates/admin/tests/proto.rs @@ -107,6 +107,15 @@ fn every_request_round_trips() { queue: 9, pool: 2, }, + Request::KeyCreate { + tenant: 5, + smtp: true, + api: false, + hooks: true, + pool: 2, + }, + Request::KeyRevoke { tenant: 5, id: 9 }, + Request::KeyList { tenant: 5, from: 9 }, Request::TenantSuspend(u32::MAX), Request::TenantResume(7), Request::TenantCreate(TenantSpec { @@ -163,5 +172,36 @@ fn short_long_or_odd_fields_are_refused() { assert_eq!(Request::decode(&odd), Err(Error::Body)); assert_eq!(Request::decode(&[VERSION, 4, 0, 0, 0]), Err(Error::Body)); assert_eq!(Request::decode(&[VERSION, 8]), Err(Error::Body)); + let mut unknown_scopes = body( + &Request::KeyCreate { + tenant: 5, + smtp: true, + api: true, + hooks: true, + pool: 2, + } + .encode(), + ); + unknown_scopes[6] = 8; + assert_eq!(Request::decode(&unknown_scopes), Err(Error::Body)); + for request in [ + Request::KeyCreate { + tenant: 5, + smtp: true, + api: true, + hooks: false, + pool: 2, + }, + Request::KeyRevoke { tenant: 5, id: 9 }, + Request::KeyList { tenant: 5, from: 9 }, + ] { + let short = body(&request.encode()); + for cut in 2..short.len() { + assert_eq!(Request::decode(&short[..cut]), Err(Error::Body), "{cut}"); + } + let mut long = short; + long.push(0); + assert_eq!(Request::decode(&long), Err(Error::Body)); + } assert_eq!(Request::decode(&[VERSION, 255]), Err(Error::Command)); } diff --git a/crates/bunzzle/src/admin.rs b/crates/bunzzle/src/admin.rs index 1ba77e16..d05eef21 100644 --- a/crates/bunzzle/src/admin.rs +++ b/crates/bunzzle/src/admin.rs @@ -17,7 +17,10 @@ pub const USAGE: &str = "usage: bunzzle admin status bunzzle admin pool set =[,=...] bunzzle admin queue list [from ] bunzzle admin queue retry - bunzzle admin queue rebind "; + bunzzle admin queue rebind + bunzzle admin key create [pool ] + bunzzle admin key revoke + bunzzle admin key list [from ]"; const MAX_ITEMS: usize = 255; @@ -49,6 +52,22 @@ pub fn parse(args: &[String]) -> Option<(&str, Request)> { queue: queue.parse().ok()?, pool: pool.parse().ok()?, }, + ["key", "create", tenant, scopes] => key_create(tenant, scopes, 0)?, + ["key", "create", tenant, scopes, "pool", pool] => { + key_create(tenant, scopes, pool.parse().ok()?)? + } + ["key", "revoke", tenant, id] => Request::KeyRevoke { + tenant: tenant.parse().ok()?, + id: id.parse().ok()?, + }, + ["key", "list", tenant] => Request::KeyList { + tenant: tenant.parse().ok()?, + from: 0, + }, + ["key", "list", tenant, "from", from] => Request::KeyList { + tenant: tenant.parse().ok()?, + from: from.parse().ok()?, + }, ["tenant", "suspend", id] => Request::TenantSuspend(id.parse().ok()?), ["tenant", "resume", id] => Request::TenantResume(id.parse().ok()?), ["tenant", "create", id, pools, options @ ..] => { @@ -90,6 +109,31 @@ fn tenant(id: &str, pools: &str, options: &[&str]) -> Option { Some(spec) } +fn key_create(tenant: &str, scopes: &str, pool: u32) -> Option { + let mut smtp = false; + let mut api = false; + let mut hooks = false; + for scope in scopes.split(',') { + let seen = match scope { + "smtp" => &mut smtp, + "api" => &mut api, + "hooks" => &mut hooks, + _ => return None, + }; + if *seen { + return None; + } + *seen = true; + } + Some(Request::KeyCreate { + tenant: tenant.parse().ok()?, + smtp, + api, + hooks, + pool, + }) +} + fn list(text: &str, item: impl Fn(&str) -> Option) -> Option> { let items: Vec = text.split(',').map(item).collect::>()?; (items.len() <= MAX_ITEMS).then_some(items) @@ -235,6 +279,38 @@ mod tests { pool: 2 }) ); + assert_eq!( + parsed(&["key", "create", "5", "hooks,smtp,api"]), + Some(Request::KeyCreate { + tenant: 5, + smtp: true, + api: true, + hooks: true, + pool: 0, + }) + ); + assert_eq!( + parsed(&["key", "create", "5", "api", "pool", "2"]), + Some(Request::KeyCreate { + tenant: 5, + smtp: false, + api: true, + hooks: false, + pool: 2, + }) + ); + assert_eq!( + parsed(&["key", "revoke", "5", "9"]), + Some(Request::KeyRevoke { tenant: 5, id: 9 }) + ); + assert_eq!( + parsed(&["key", "list", "5"]), + Some(Request::KeyList { tenant: 5, from: 0 }) + ); + assert_eq!( + parsed(&["key", "list", "5", "from", "9"]), + Some(Request::KeyList { tenant: 5, from: 9 }) + ); assert_eq!(parsed(&["queue", "list"]), None); assert_eq!(parsed(&["queue", "retry", "5"]), None); assert_eq!( @@ -287,6 +363,13 @@ mod tests { &["pool", "set", "1", "192.0.2.1"], &["pool", "set", "1", "192.0.2.1=70000"], &["pool", "set", "1", "host=1"], + &["key", "create", "5", ""], + &["key", "create", "5", "smtp,smtp"], + &["key", "create", "5", "smtp,unknown"], + &["key", "create", "5", "smtp", "pool"], + &["key", "create", "5", "smtp", "pool=2"], + &["key", "revoke", "5"], + &["key", "list", "5", "from"], ] { assert_eq!(parsed(bad), None, "{bad:?}"); } diff --git a/crates/node/src/ops.rs b/crates/node/src/ops.rs index 4b86a0f5..da715297 100644 --- a/crates/node/src/ops.rs +++ b/crates/node/src/ops.rs @@ -3,7 +3,7 @@ use std::net::IpAddr; use std::rc::Rc; use admin::{Admin, Code, Handler, PoolSpec, Reply, Request, TenantSpec}; -use control::{Limits, Object, Pool, State, Table, Tenant}; +use control::{Limits, Object, Pool, Scopes, State, Table, Tenant}; use rt::UnixListener; use sched::{Node, QueueDone, QueueRefusal, Transport}; @@ -58,6 +58,27 @@ impl Handler for Ops { done, ) } + Request::KeyCreate { + tenant, + smtp, + api, + hooks, + pool, + } => { + let reply = self + .key_create(tenant, Scopes { smtp, api, hooks }, pool) + .await; + if reply.code != Code::Ok { + logged(&format!("key create {tenant}"), &reply); + } + reply + } + Request::KeyRevoke { tenant, id } => { + let reply = self.key_revoke(tenant, id).await; + logged(&format!("key revoke {tenant} {id}"), &reply); + reply + } + Request::KeyList { tenant, from } => self.keys(tenant, from), } } } @@ -108,6 +129,78 @@ impl Ops { Reply::new(Code::Ok, listed(lines, None)) } + fn keys(&self, tenant: u32, from: u32) -> Reply { + let table = self.node.table(); + let Some(current) = table.tenant(tenant).filter(|t| !t.state.deleted()) else { + return tenant_not_found(tenant); + }; + let generation = current.generation; + let lines = table + .accesses(tenant) + .filter(move |a| a.id >= from && a.generation == generation) + .map(|a| { + let line = format!( + "key {} scopes {} pool {} generation {}\n", + a.id, + scope_list(a.scopes), + a.pool, + a.generation, + ); + (a.id, line) + }); + Reply::new(Code::Ok, listed(lines, None)) + } + + async fn key_create(&self, tenant: u32, scopes: Scopes, pool: u32) -> Reply { + { + let table = self.node.table(); + let Some(current) = table.tenant(tenant).filter(|t| !t.state.deleted()) else { + return tenant_not_found(tenant); + }; + if current.state != State::Active { + return Reply::new(Code::Refused, format!("tenant {tenant} is not active")); + } + } + let (access, secret) = match self.node.access_new(tenant, scopes, pool).await { + Ok(created) => created, + Err(error) => return key_failed(error), + }; + let id = access.id; + eprintln!("admin key create {tenant}: Ok id {id}"); + let secret = std::str::from_utf8(&secret).expect("access tokens are ASCII"); + let mut text = String::with_capacity(secret.len() + 24); + let _ = write!(text, "key {id} secret "); + text.push_str(secret); + text.push('\n'); + Reply::new(Code::Ok, text) + } + + async fn key_revoke(&self, tenant: u32, id: u32) -> Reply { + { + let table = self.node.table(); + if table + .tenant(tenant) + .is_none_or(|tenant| tenant.state.deleted()) + { + return tenant_not_found(tenant); + } + let Some(access) = table.access(id).filter(|a| a.tenant == tenant) else { + return key_not_found(tenant, id); + }; + if table.gone(tenant, access.generation) { + return key_not_found(tenant, id); + } + } + match self.node.access_revoke(tenant, id).await { + Ok(removal) => Reply::new( + Code::Ok, + format!("key {id} revoked, version {}\n", removal.version), + ), + Err(sched::Error::Control(control::Error::Refused)) => key_not_found(tenant, id), + Err(error) => key_failed(error), + } + } + async fn queues(&self, tenant: u32, from: u32) -> Reply { let known = self .node @@ -256,6 +349,51 @@ impl Ops { } } +fn scope_list(scopes: Scopes) -> String { + let mut names = Vec::new(); + if scopes.smtp { + names.push("smtp"); + } + if scopes.api { + names.push("api"); + } + if scopes.hooks { + names.push("hooks"); + } + names.join(",") +} + +fn logged(command: &str, reply: &Reply) { + eprintln!( + "admin {command}: {:?} {}", + reply.code, + reply.text.trim_end() + ); +} + +fn tenant_not_found(tenant: u32) -> Reply { + Reply::new(Code::NotFound, format!("tenant {tenant} not found")) +} + +fn key_not_found(tenant: u32, id: u32) -> Reply { + Reply::new( + Code::NotFound, + format!("key {id} of tenant {tenant} not found"), + ) +} + +fn key_failed(error: sched::Error) -> Reply { + match error { + sched::Error::Control(control::Error::Busy) => { + Reply::new(Code::Busy, "another change is being written") + } + sched::Error::Control(error @ (control::Error::Invalid(_) | control::Error::Refused)) => { + Reply::new(Code::Refused, error.to_string()) + } + error => Reply::new(Code::Failed, error.to_string()), + } +} + fn queued(command: &str, tenant: u32, queue: u32, done: Result) -> Reply { let reply = match done { Ok(QueueDone::Retried(waiting)) => Reply::new( diff --git a/crates/node/tests/boot.rs b/crates/node/tests/boot.rs index bdb6d9bd..14c42a65 100644 --- a/crates/node/tests/boot.rs +++ b/crates/node/tests/boot.rs @@ -759,6 +759,95 @@ async fn unknown_queues() { assert_eq!(ask(rebind).await.0, NotFound); } +#[test] +fn admin_creates_lists_and_revokes_keys() { + use admin::Code::{NotFound, Ok, Refused}; + use admin::Request::{KeyCreate, KeyList, KeyRevoke, PoolSet, TenantResume, TenantSuspend}; + let driver = created(23); + let extra = format!("[admin]\nsocket = \"{ADMIN}\"\n"); + let node = booted(&driver, config_with(7, &extra), CORES); + node.machine.block_on(0, async move { + drop(serving().await); + let key = |tenant, smtp, api, hooks, pool| KeyCreate { + tenant, + smtp, + api, + hooks, + pool, + }; + assert_eq!( + ask(key(7, true, false, false, 0)).await, + (NotFound, "tenant 7 not found".into()) + ); + assert_eq!( + ask(KeyList { tenant: 7, from: 0 }).await, + (NotFound, "tenant 7 not found".into()) + ); + assert_eq!( + ask(KeyRevoke { tenant: 7, id: 1 }).await, + (NotFound, "tenant 7 not found".into()) + ); + + let pool = admin::PoolSpec { + id: 1, + addresses: vec![("192.0.2.1".parse().expect("ip"), 1)], + }; + assert_eq!(ask(PoolSet(pool)).await.0, Ok); + assert_eq!(ask(tenant(5, &[1])).await.0, Ok); + assert_eq!(ask(tenant(6, &[1])).await.0, Ok); + assert_eq!(ask(TenantSuspend(5)).await.0, Ok); + assert_eq!( + ask(key(5, true, false, false, 1)).await, + (Refused, "tenant 5 is not active".into()) + ); + assert_eq!(ask(TenantResume(5)).await.0, Ok); + assert_eq!( + ask(key(5, false, false, false, 0)).await, + (Refused, "invalid scopes".into()) + ); + assert_eq!( + ask(key(5, false, false, true, 1)).await, + (Refused, "invalid scopes".into()) + ); + assert_eq!( + ask(key(5, true, false, false, 2)).await, + (Refused, "invalid pool".into()) + ); + + let (code, text) = ask(key(5, true, true, false, 1)).await; + assert_eq!(code, Ok); + let secret = text + .strip_prefix("key 1 secret ") + .and_then(|text| text.strip_suffix('\n')) + .expect("create reply"); + assert!(secret.starts_with("bz_")); + assert_eq!( + ask(KeyList { tenant: 5, from: 0 }).await, + (Ok, "key 1 scopes smtp,api pool 1 generation 1\n".into()) + ); + + assert_eq!(ask(key(6, false, false, true, 0)).await.0, Ok); + assert_eq!( + ask(KeyRevoke { tenant: 5, id: 2 }).await, + (NotFound, "key 2 of tenant 5 not found".into()) + ); + assert_eq!(ask(KeyRevoke { tenant: 5, id: 1 }).await.0, Ok); + assert_eq!( + ask(KeyList { tenant: 5, from: 0 }).await, + (Ok, String::new()) + ); + assert_eq!( + ask(KeyRevoke { tenant: 5, id: 1 }).await, + (NotFound, "key 1 of tenant 5 not found".into()) + ); + assert_eq!( + ask(KeyList { tenant: 6, from: 0 }).await, + (Ok, "key 2 scopes hooks pool 0 generation 1\n".into()) + ); + }); + stopped(&driver, node); +} + #[test] fn admin_creates_suspends_and_resumes_tenants() { use admin::Code::{NotFound, Ok, Refused};