Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Cleanup and enable test #6

Draft
wants to merge 1 commit into
base: auth_changes
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 14 additions & 11 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)]
Expand Down Expand Up @@ -80,11 +80,14 @@ pub struct Limits {
#[derive(Debug, Clone, Serialize, Deserialize)]
#[allow(unused)]
pub struct Authorization {
pub word_whitelist: Option<Vec<String>>, // If present, only allow event contents that contain these words
pub pubkey_whitelist: Option<Vec<String>>, // If present, only allow these pubkeys to publish events
pub pubkey_whitelist_readers: Option<Vec<String>>, // 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<String>, // If present, only allow event contents that contain these words
#[serde(default)]
pub write_pubkeys: Vec<String>, // If present, only allow these pubkeys to publish events
#[serde(default)]
pub read_pubkeys: Vec<String>, // 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)]
Expand Down Expand Up @@ -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,
Expand Down
35 changes: 15 additions & 20 deletions src/db.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -203,28 +203,23 @@ pub async fn db_writer(
let mut user_balance: Option<u64> = 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)) => {
Expand Down
2 changes: 1 addition & 1 deletion src/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ impl From<Settings> 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,
),
};
Expand Down
20 changes: 8 additions & 12 deletions src/server.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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! {
Expand Down Expand Up @@ -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(&notice)).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(&notice)).await.ok();
Expand Down Expand Up @@ -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());
Expand Down
4 changes: 2 additions & 2 deletions tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,12 @@ pub struct Relay {
pub shutdown_tx: MpscSender<()>,
}

pub fn start_relay() -> Result<Relay> {
pub fn start_relay(settings: Option<config::Settings>) -> Result<Relay> {
// 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();
Expand Down
4 changes: 2 additions & 2 deletions tests/conn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down Expand Up @@ -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);
Expand Down
9 changes: 4 additions & 5 deletions tests/integration_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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?;
Expand Down