From a33df9098d536ed48b05eadf601563c420045521 Mon Sep 17 00:00:00 2001 From: Daniel Cadenas Date: Tue, 30 Jul 2024 11:46:15 -0300 Subject: [PATCH] Cleanup and enable test --- src/config.rs | 25 ++++++++++++++----------- src/db.rs | 35 +++++++++++++++-------------------- src/info.rs | 2 +- src/server.rs | 20 ++++++++------------ tests/common/mod.rs | 4 ++-- tests/conn.rs | 4 ++-- tests/integration_test.rs | 9 ++++----- 7 files changed, 46 insertions(+), 53 deletions(-) diff --git a/src/config.rs b/src/config.rs index 5b1cfc2f..4388667d 100644 --- a/src/config.rs +++ b/src/config.rs @@ -2,7 +2,7 @@ use crate::payment::Processor; use config::{Config, ConfigError, File}; use serde::{Deserialize, Serialize}; -use std::time::Duration; +use std::{default, time::Duration}; #[derive(Debug, Serialize, Deserialize, Clone)] #[allow(unused)] @@ -80,11 +80,14 @@ pub struct Limits { #[derive(Debug, Clone, Serialize, Deserialize)] #[allow(unused)] pub struct Authorization { - pub word_whitelist: Option>, // If present, only allow event contents that contain these words - pub pubkey_whitelist: Option>, // If present, only allow these pubkeys to publish events - pub pubkey_whitelist_readers: Option>, // List of pubkeys that can read this relay - pub nip42_auth: bool, // if true enables NIP-42 authentication - pub nip42_dms: bool, // if true send DMs only to their authenticated recipients + #[serde(default)] + pub required_words: Vec, // If present, only allow event contents that contain these words + #[serde(default)] + pub write_pubkeys: Vec, // If present, only allow these pubkeys to publish events + #[serde(default)] + pub read_pubkeys: Vec, // List of pubkeys that can read this relay + pub nip42_auth: bool, // if true enables NIP-42 authentication + pub nip42_dms: bool, // if true send DMs only to their authenticated recipients } #[derive(Debug, Clone, Serialize, Deserialize)] @@ -314,11 +317,11 @@ impl Default for Settings { limit_scrapers: false, }, authorization: Authorization { - word_whitelist: None, // Words needed in the content to be able to publish to the relay - pubkey_whitelist: None, // Allow any pubkey from this list to publish - pubkey_whitelist_readers: None, // Allow any pubkey from this list to read - nip42_auth: false, // Disable NIP-42 authentication - nip42_dms: false, // Send DMs to everybody + required_words: Vec::new(), // Words needed in the content to be able to publish to the relay + write_pubkeys: Vec::new(), // Allow any pubkey from this list to publish + read_pubkeys: Vec::new(), // Allow any pubkey from this list to read + nip42_auth: false, // Disable NIP-42 authentication + nip42_dms: false, // Send DMs to everybody }, pay_to_relay: PayToRelay { enabled: false, diff --git a/src/db.rs b/src/db.rs index ee317355..63df8b84 100644 --- a/src/db.rs +++ b/src/db.rs @@ -120,7 +120,7 @@ pub async fn db_writer( //upgrade_db(&mut pool.get()?)?; // Make a copy of the whitelist - let whitelist = &settings.authorization.pubkey_whitelist.clone(); + let whitelist = &settings.authorization.write_pubkeys.clone(); // get rate limit settings let rps_setting = settings.limits.messages_per_sec; @@ -203,28 +203,23 @@ pub async fn db_writer( let mut user_balance: Option = None; if !pay_to_relay_enabled { // check if this event is authorized. - if let Some(allowed_addrs) = whitelist { - // TODO: incorporate delegated pubkeys - // if the event address is not in allowed_addrs. - if !allowed_addrs.contains(&event.pubkey) { - debug!( - "rejecting event: {}, unauthorized author", - event.get_event_id_prefix() - ); - notice_tx - .try_send(Notice::blocked( - event.id, - "pubkey is not allowed to publish to this relay", - )) - .ok(); - continue; - } + // if the event address is not in allowed_addrs. + if !whitelist.contains(&event.pubkey) { + debug!( + "rejecting event: {}, unauthorized author", + event.get_event_id_prefix() + ); + notice_tx + .try_send(Notice::blocked( + event.id, + "pubkey is not allowed to publish to this relay", + )) + .ok(); + continue; } } else { // If the user is on whitelist there is no need to check if the user is admitted or has balance to post - if whitelist.is_none() - || (whitelist.is_some() && !whitelist.as_ref().unwrap().contains(&event.pubkey)) - { + if whitelist.contains(&event.pubkey) { let key = Keys::from_pk_str(&event.pubkey).unwrap(); match repo.get_account_balance(&key).await { Ok((user_admitted, balance)) => { diff --git a/src/info.rs b/src/info.rs index b8ac9757..8ea2eda4 100644 --- a/src/info.rs +++ b/src/info.rs @@ -81,7 +81,7 @@ impl From for RelayInfo { restricted_writes: Some( p.enabled || c.verified_users.is_enabled() - || c.authorization.pubkey_whitelist.is_some() + || !c.authorization.write_pubkeys.is_empty() || c.grpc.restricts_write, ), }; diff --git a/src/server.rs b/src/server.rs index 7ae22464..cc37b7d9 100644 --- a/src/server.rs +++ b/src/server.rs @@ -774,10 +774,10 @@ pub fn start_server(settings: &Settings, shutdown_rx: MpscReceiver<()>) -> Resul ); let socket_addr = addr.parse().expect("listening address not valid"); // address whitelisting settings - if let Some(addr_whitelist) = &settings.authorization.pubkey_whitelist { + if !settings.authorization.write_pubkeys.is_empty() { info!( "Event publishing restricted to {} pubkey(s)", - addr_whitelist.len() + settings.authorization.write_pubkeys.len() ); } // check if NIP-05 enforced user verification is on @@ -1146,13 +1146,9 @@ async fn nostr_server( } } - let word_whitelist = settings.authorization.word_whitelist.as_ref().unwrap(); - let write_whitelist = settings.authorization.pubkey_whitelist.as_ref().unwrap(); - let read_whitelist = settings - .authorization - .pubkey_whitelist_readers - .as_ref() - .unwrap(); + let required_words = &settings.authorization.required_words; + let write_pubkeys = &settings.authorization.write_pubkeys; + let read_pubkeys = &settings.authorization.read_pubkeys; loop { tokio::select! { @@ -1282,14 +1278,14 @@ async fn nostr_server( continue; }, Some(pubkey) => { - if !write_whitelist.contains(&pubkey) { + if !write_pubkeys.contains(pubkey) { info!("client: {} not authorized to write, {:?}", cid, pubkey); let notice = Notice::restricted(e.id, "Writes not allowed for this account. Contact nprofile1qqsq7gkqd6kpqqngfm7vdr6ks4qwsdpdzcya2z9u6scjcquwvx203dsrg7t4x"); ws_stream.send(make_notice_message(¬ice)).await.ok(); continue; } - if !word_whitelist.is_empty() && !word_whitelist.iter().any(|word| e.content.contains(word)) { + if !required_words.is_empty() && !required_words.iter().any(|word| e.content.contains(word)) { info!("client: {} tried to write an event with no keyword, {:?}", cid, e.id); let notice = Notice::restricted(e.id, "The event doesn't contain a keyword"); ws_stream.send(make_notice_message(¬ice)).await.ok(); @@ -1389,7 +1385,7 @@ async fn nostr_server( continue }, Some(pubkey) => { - if !read_whitelist.contains(&pubkey) { + if !read_pubkeys.contains(pubkey) { info!("client: {} not authorized to read, {:?}", cid, pubkey); let json = json!(["CLOSED", cid, "restricted: Reads not allowed for this account. Contact nprofile1qqsq7gkqd6kpqqngfm7vdr6ks4qwsdpdzcya2z9u6scjcquwvx203dsrg7t4x"]); let message = Message::text(json.to_string()); diff --git a/tests/common/mod.rs b/tests/common/mod.rs index 52d68f96..3a76d98f 100644 --- a/tests/common/mod.rs +++ b/tests/common/mod.rs @@ -18,12 +18,12 @@ pub struct Relay { pub shutdown_tx: MpscSender<()>, } -pub fn start_relay() -> Result { +pub fn start_relay(settings: Option) -> Result { // setup tracing let _trace_sub = tracing_subscriber::fmt::try_init(); info!("Starting a new relay"); // replace default settings - let mut settings = config::Settings::default(); + let mut settings = settings.unwrap_or_default(); // identify open port info!("Checking for address..."); let port = get_available_port().unwrap(); diff --git a/tests/conn.rs b/tests/conn.rs index 4fccaab9..86623b73 100644 --- a/tests/conn.rs +++ b/tests/conn.rs @@ -44,7 +44,7 @@ mod tests { let pubkey = XOnlyPublicKey::from_keypair(&key_pair); let mut settings = Settings::new(&None).unwrap(); - settings.authorization.pubkey_whitelist = Some(vec![pubkey.to_hex()]); + settings.authorization.write_pubkeys = vec![pubkey.to_hex()]; let mut client_conn = ClientConn::new("127.0.0.1".into(), settings); assert_eq!(client_conn.auth_challenge(), None); @@ -84,7 +84,7 @@ mod tests { let pubkey = XOnlyPublicKey::from_keypair(&key_pair); let mut settings = Settings::new(&None).unwrap(); - settings.authorization.pubkey_whitelist = Some(vec![pubkey.to_hex()]); + settings.authorization.write_pubkeys = vec![pubkey.to_hex()]; let mut client_conn = ClientConn::new("127.0.0.1".into(), settings); assert_eq!(client_conn.auth_challenge(), None); diff --git a/tests/integration_test.rs b/tests/integration_test.rs index f65f4e8e..b402aff5 100644 --- a/tests/integration_test.rs +++ b/tests/integration_test.rs @@ -11,7 +11,7 @@ mod common; async fn start_and_stop() -> Result<()> { // this will be the common pattern for acquiring a new relay: // start a fresh relay, on a port to-be-provided back to us: - let relay = common::start_relay()?; + let relay = common::start_relay(None)?; // wait for the relay's webserver to start up and deliver a page: common::wait_for_healthy_relay(&relay).await?; let port = relay.port; @@ -41,18 +41,17 @@ async fn start_and_stop() -> Result<()> { #[tokio::test] async fn relay_home_page() -> Result<()> { // get a relay and wait for startup... - let relay = common::start_relay()?; + let relay = common::start_relay(None)?; common::wait_for_healthy_relay(&relay).await?; // tell relay to shutdown let _res = relay.shutdown_tx.send(()); Ok(()) } -//#[tokio::test] -// Still inwork +#[tokio::test] async fn publish_test() -> Result<()> { // get a relay and wait for startup - let relay = common::start_relay()?; + let relay = common::start_relay(None)?; common::wait_for_healthy_relay(&relay).await?; // open a non-secure websocket connection. let (mut ws, _res) = connect_async(format!("ws://localhost:{}", relay.port)).await?;