Skip to content

Commit 7dd5b34

Browse files
wesbillmanBrain
andauthored
Add channel visibility & ephemeral TTL controls to manage sidebar (#911)
Signed-off-by: Wes <[email protected]> Co-authored-by: Brain <21994759fc7a6fa6b965551d35cfd7897d262f2495467f2d78694ddcfa6a5c7e@sprout-oss.stage.blox.sqprod.co>
1 parent 4b78fe3 commit 7dd5b34

19 files changed

Lines changed: 1086 additions & 53 deletions

File tree

‎crates/sprout-cli/src/commands/channels.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -350,7 +350,7 @@ pub async fn cmd_update_channel(
350350
}
351351
let channel_uuid = parse_uuid(channel_id)?;
352352

353-
let builder = sprout_sdk::build_update_channel(channel_uuid, name, description)
353+
let builder = sprout_sdk::build_update_channel(channel_uuid, name, description, None, None)
354354
.map_err(|e| CliError::Other(format!("build_update_channel failed: {e}")))?;
355355

356356
let event = client.sign_event(builder)?;

‎crates/sprout-db/src/channel.rs‎

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -902,30 +902,42 @@ fn row_to_member_record(row: sqlx::postgres::PgRow) -> Result<MemberRecord> {
902902

903903
// ── Phase 2: Channel Metadata ─────────────────────────────────────────────────
904904

905-
/// Partial update for channel name/description.
905+
/// Partial update for channel metadata. Every field is `None` to leave the
906+
/// column unchanged.
907+
#[derive(Default)]
906908
pub struct ChannelUpdate {
907909
/// New channel name, or `None` to leave unchanged.
908910
pub name: Option<String>,
909911
/// New channel description, or `None` to leave unchanged.
910912
pub description: Option<String>,
913+
/// New visibility (`"open"`/`"private"`), or `None` to leave unchanged.
914+
pub visibility: Option<String>,
915+
/// TTL change: outer `None` leaves it unchanged, `Some(None)` clears the
916+
/// ephemeral TTL (channel becomes permanent), `Some(Some(secs))` sets it.
917+
/// On any change the `ttl_deadline` is reset to `NOW() + ttl_seconds`.
918+
pub ttl_seconds: Option<Option<i32>>,
911919
}
912920

913-
/// Updates channel name and/or description dynamically.
921+
/// Updates channel metadata dynamically.
914922
///
915-
/// At least one field must be `Some`; returns `InvalidData` otherwise.
923+
/// At least one field must be provided; returns `InvalidData` otherwise.
916924
/// Returns the updated `ChannelRecord` on success.
917925
pub async fn update_channel(
918926
pool: &PgPool,
919927
channel_id: Uuid,
920928
updates: ChannelUpdate,
921929
) -> Result<ChannelRecord> {
922-
if updates.name.is_none() && updates.description.is_none() {
930+
if updates.name.is_none()
931+
&& updates.description.is_none()
932+
&& updates.visibility.is_none()
933+
&& updates.ttl_seconds.is_none()
934+
{
923935
return Err(DbError::InvalidData(
924936
"at least one field must be provided for update".to_string(),
925937
));
926938
}
927939

928-
// Build SET clause dynamically — only include fields that are Some.
940+
// Build SET clause dynamically — only include fields that are provided.
929941
// Track parameter index for positional placeholders.
930942
let mut set_parts: Vec<String> = Vec::new();
931943
let mut param_idx: usize = 1;
@@ -937,6 +949,22 @@ pub async fn update_channel(
937949
set_parts.push(format!("description = ${param_idx}"));
938950
param_idx += 1;
939951
}
952+
if updates.visibility.is_some() {
953+
set_parts.push(format!("visibility = ${param_idx}::channel_visibility"));
954+
param_idx += 1;
955+
}
956+
if let Some(ref ttl) = updates.ttl_seconds {
957+
// Set ttl_seconds, then reset the deadline from now (or clear both).
958+
set_parts.push(format!("ttl_seconds = ${param_idx}"));
959+
param_idx += 1;
960+
match ttl {
961+
Some(_) => set_parts.push(format!(
962+
"ttl_deadline = NOW() + (${} || ' seconds')::interval",
963+
param_idx - 1
964+
)),
965+
None => set_parts.push("ttl_deadline = NULL".to_string()),
966+
}
967+
}
940968
let sql = format!(
941969
"UPDATE channels SET {}, updated_at = NOW() WHERE id = ${param_idx} AND deleted_at IS NULL",
942970
set_parts.join(", ")
@@ -949,6 +977,12 @@ pub async fn update_channel(
949977
if let Some(ref desc) = updates.description {
950978
q = q.bind(desc);
951979
}
980+
if let Some(ref vis) = updates.visibility {
981+
q = q.bind(vis);
982+
}
983+
if let Some(ref ttl) = updates.ttl_seconds {
984+
q = q.bind(*ttl);
985+
}
952986
q = q.bind(channel_id);
953987

954988
let result = q.execute(pool).await?;

‎crates/sprout-relay/src/handlers/event.rs‎

Lines changed: 187 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,50 @@ fn bounded_kind_label(kind: u32) -> String {
4747
}
4848
}
4949

50+
/// Drop recipients without access before fan-out on a private channel.
51+
///
52+
/// Open and channel-less events skip membership filtering (open channel-scoped
53+
/// events pay one visibility lookup; see `channel_visibility_cached`). For a
54+
/// private channel, each recipient is kept only if its connection's
55+
/// authenticated pubkey is a current member; unknown/unauthenticated recipients
56+
/// fail closed. This is the cluster-wide backstop: even if a stale subscription
57+
/// survives on another node after an open->private flip, its events are not
58+
/// delivered here.
59+
pub async fn filter_fanout_by_access(
60+
state: &Arc<AppState>,
61+
stored_event: &StoredEvent,
62+
matches: Vec<(crate::subscription::ConnId, crate::subscription::SubId)>,
63+
) -> Vec<(crate::subscription::ConnId, crate::subscription::SubId)> {
64+
let Some(channel_id) = stored_event.channel_id else {
65+
return matches;
66+
};
67+
match state.channel_visibility_cached(channel_id).await {
68+
Ok(v) if v != "private" => return matches,
69+
Ok(_) => {}
70+
Err(e) => {
71+
// Fail closed: if we cannot determine visibility, do not leak a
72+
// possibly-private channel's events.
73+
warn!(%channel_id, "fan-out access filter: visibility lookup failed: {e}");
74+
return Vec::new();
75+
}
76+
}
77+
78+
let mut allowed = Vec::with_capacity(matches.len());
79+
for (conn_id, sub_id) in matches {
80+
let Some(pubkey) = state.conn_manager.pubkey_for_conn(conn_id) else {
81+
continue;
82+
};
83+
match state.is_member_cached(channel_id, &pubkey).await {
84+
Ok(true) => allowed.push((conn_id, sub_id)),
85+
Ok(false) => {}
86+
Err(e) => {
87+
warn!(%channel_id, "fan-out access filter: membership lookup failed: {e}");
88+
}
89+
}
90+
}
91+
allowed
92+
}
93+
5094
/// Publish a stored event to subscribers and kick off async side effects.
5195
pub(crate) async fn dispatch_persistent_event(
5296
state: &Arc<AppState>,
@@ -70,6 +114,7 @@ pub(crate) async fn dispatch_persistent_event(
70114
}
71115

72116
let matches = state.sub_registry.fan_out(stored_event);
117+
let matches = filter_fanout_by_access(state, stored_event, matches).await;
73118
metrics::histogram!("sprout_fanout_recipients").record(matches.len() as f64);
74119
debug!(
75120
event_id = %event_id_hex,
@@ -923,4 +968,146 @@ mod tests {
923968
let err = super::agent_observer_route(&event).expect_err("route should reject plaintext");
924969
assert!(err.contains("NIP-44"));
925970
}
971+
972+
mod fanout_access {
973+
use std::collections::HashMap;
974+
use std::sync::atomic::AtomicU8;
975+
use std::sync::Arc;
976+
977+
use nostr::{EventBuilder, Keys, Kind};
978+
use sprout_core::StoredEvent;
979+
use tokio::sync::{mpsc, Mutex};
980+
use tokio_util::sync::CancellationToken;
981+
use uuid::Uuid;
982+
983+
use crate::handlers::event::filter_fanout_by_access;
984+
use crate::state::AppState;
985+
986+
fn test_config() -> crate::config::Config {
987+
let mut config = crate::config::Config::from_env().expect("default config loads");
988+
config.require_relay_membership = false;
989+
config.redis_url = "redis://127.0.0.1:1".to_string();
990+
config
991+
}
992+
993+
async fn test_state() -> Arc<AppState> {
994+
let config = test_config();
995+
let pool = sqlx::PgPool::connect_lazy(&config.database_url).expect("lazy pg pool");
996+
let db = sprout_db::Db::from_pool(pool.clone());
997+
let redis_pool = deadpool_redis::Config::from_url(&config.redis_url)
998+
.create_pool(Some(deadpool_redis::Runtime::Tokio1))
999+
.expect("redis pool");
1000+
let pubsub = Arc::new(
1001+
sprout_pubsub::PubSubManager::new(&config.redis_url, redis_pool.clone())
1002+
.await
1003+
.expect("pubsub manager"),
1004+
);
1005+
let audit = sprout_audit::AuditService::new(pool);
1006+
let auth = sprout_auth::AuthService::new(config.auth.clone());
1007+
let search = sprout_search::SearchService::new(sprout_search::SearchConfig {
1008+
url: config.typesense_url.clone(),
1009+
api_key: config.typesense_key.clone(),
1010+
collection: "events".to_string(),
1011+
});
1012+
let workflow_engine = Arc::new(sprout_workflow::WorkflowEngine::new(
1013+
db.clone(),
1014+
sprout_workflow::WorkflowConfig::default(),
1015+
));
1016+
let media_storage =
1017+
sprout_media::MediaStorage::new(&config.media).expect("media storage");
1018+
let (state, _audit_shutdown) = AppState::new(
1019+
config,
1020+
db,
1021+
redis_pool,
1022+
audit,
1023+
pubsub,
1024+
auth,
1025+
search,
1026+
workflow_engine,
1027+
Keys::generate(),
1028+
media_storage,
1029+
);
1030+
Arc::new(state)
1031+
}
1032+
1033+
fn register_conn(state: &AppState, pubkey: Option<Vec<u8>>) -> Uuid {
1034+
let conn_id = Uuid::new_v4();
1035+
let (tx, _rx) = mpsc::channel(1);
1036+
state.conn_manager.register(
1037+
conn_id,
1038+
tx,
1039+
CancellationToken::new(),
1040+
Arc::new(AtomicU8::new(0)),
1041+
Arc::new(Mutex::new(HashMap::new())),
1042+
);
1043+
if let Some(pk) = pubkey {
1044+
state.conn_manager.set_authenticated_pubkey(conn_id, pk);
1045+
}
1046+
conn_id
1047+
}
1048+
1049+
fn channel_event(channel_id: Option<Uuid>) -> StoredEvent {
1050+
let event = EventBuilder::new(Kind::Custom(9), "{}")
1051+
.sign_with_keys(&Keys::generate())
1052+
.expect("sign event");
1053+
StoredEvent::new(event, channel_id)
1054+
}
1055+
1056+
#[tokio::test]
1057+
async fn channel_less_event_passes_through() {
1058+
let state = test_state().await;
1059+
let conn = register_conn(&state, Some(vec![1u8; 32]));
1060+
let matches = vec![(conn, "s".to_string())];
1061+
let out = filter_fanout_by_access(&state, &channel_event(None), matches.clone()).await;
1062+
assert_eq!(out, matches);
1063+
}
1064+
1065+
#[tokio::test]
1066+
async fn open_channel_event_passes_through_unfiltered() {
1067+
let state = test_state().await;
1068+
let channel_id = Uuid::new_v4();
1069+
state
1070+
.channel_visibility_cache
1071+
.insert(channel_id, "open".to_string());
1072+
// A connection with no authenticated pubkey would be dropped on a
1073+
// private channel; on open it must pass untouched.
1074+
let conn = register_conn(&state, None);
1075+
let matches = vec![(conn, "s".to_string())];
1076+
let out =
1077+
filter_fanout_by_access(&state, &channel_event(Some(channel_id)), matches.clone())
1078+
.await;
1079+
assert_eq!(out, matches);
1080+
}
1081+
1082+
#[tokio::test]
1083+
async fn private_channel_keeps_member_drops_non_member_and_unknown() {
1084+
let state = test_state().await;
1085+
let channel_id = Uuid::new_v4();
1086+
state
1087+
.channel_visibility_cache
1088+
.insert(channel_id, "private".to_string());
1089+
1090+
let member_pk = vec![1u8; 32];
1091+
let non_member_pk = vec![2u8; 32];
1092+
state
1093+
.membership_cache
1094+
.insert((channel_id, member_pk.clone()), true);
1095+
state
1096+
.membership_cache
1097+
.insert((channel_id, non_member_pk.clone()), false);
1098+
1099+
let member = register_conn(&state, Some(member_pk));
1100+
let non_member = register_conn(&state, Some(non_member_pk));
1101+
let unauthed = register_conn(&state, None);
1102+
1103+
let matches = vec![
1104+
(member, "m".to_string()),
1105+
(non_member, "n".to_string()),
1106+
(unauthed, "u".to_string()),
1107+
];
1108+
let out =
1109+
filter_fanout_by_access(&state, &channel_event(Some(channel_id)), matches).await;
1110+
assert_eq!(out, vec![(member, "m".to_string())]);
1111+
}
1112+
}
9261113
}

0 commit comments

Comments
 (0)