Skip to content
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
7 changes: 5 additions & 2 deletions NOSTR.md
Original file line number Diff line number Diff line change
Expand Up @@ -207,8 +207,11 @@ the child, without joining it.
`parent` and any other metadata tag is refused. Setting takes a direct owner or admin role in the
child and a role that may post in the new parent. Clearing takes a direct
owner or admin role in the child or in its current parent.
- Only streams and forums without a TTL take part, and a channel with a
parent or children cannot be given a TTL. A tree is at most three channels
- Only streams and forums take part. A channel with a parent may have a TTL
and auto-archive; it still reads and grants as before once archived. A
project, a channel with children and no parent, may not: the relay refuses
a TTL on it, filing a channel under a channel that has a TTL and no parent,
and clearing the parent of a channel that has a TTL and children. A tree is at most three channels
deep (channel, parent, grandparent) and has no loops; the relay refuses a
change that breaks either. A new parent must not be archived.
- **Reading.** A private child is readable by its members and by anyone who
Expand Down
4 changes: 2 additions & 2 deletions crates/buzz-db/src/store/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1818,11 +1818,11 @@ pub(crate) async fn apply_channel_metadata_event(
));
}
}
// A parent change, or a TTL on a channel in a tree, is decided here,
// A parent change, or a TTL on a project, is decided here,
// under the channel's locks, so every check sees the state it commits
// against (`crate::channel_tree`).
if matches!(edit.columns.ttl_seconds, Some(Some(_))) {
crate::channel_tree::refuse_ttl_in_tree(locked.tx(), channel_id).await?;
crate::channel_tree::refuse_ttl_on_project(locked.tx(), channel_id).await?;
}
if let Some(change) = edit.columns.parent_id {
crate::channel_tree::decide_parent_change(
Expand Down
108 changes: 75 additions & 33 deletions crates/buzz-db/src/store/channel_tree.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,13 @@
//!
//! A tree is at most three channels deep: a top channel, a child, and a
//! grandchild ([`MAX_ANCESTORS`] parents above any channel). Only streams and
//! forums take part, never an ephemeral (TTL) channel. Both rules, and the
//! absence of loops, are enforced when a parent is written
//! ([`decide_parent_change`]), under row locks on every channel involved.
//! forums take part. A channel filed under a parent may auto-archive (have a
//! TTL); a project, a channel with children and no parent of its own, may
//! not ([`PROJECTS_MAY_AUTO_ARCHIVE`]). Auto-archive only archives, and an
//! archived channel still reads and grants as before. These rules, and the
//! absence of loops, are enforced when a parent or a TTL is written
//! ([`decide_parent_change`], [`refuse_ttl_on_project`]), under row locks on
//! every channel involved.
//!
//! ## The rule: the closest grant wins
//!
Expand Down Expand Up @@ -434,8 +438,10 @@ pub type ParentChange = Option<Uuid>;
/// - **Clearing** needs a direct owner or admin row in the child or in its
/// current parent. Clearing only narrows who can read the child.
///
/// Both channels must be streams or forums with no TTL, and the new parent
/// must be live and unarchived. The tree stays at most [`MAX_ANCESTORS`] + 1
/// Both channels must be streams or forums, and the new parent must be live
/// and unarchived. Neither the new parent nor a child whose parent is
/// cleared may be left an auto-archiving project
/// ([`refuse_auto_archiving_project`]). The tree stays at most [`MAX_ANCESTORS`] + 1
/// deep and loop-free.
pub(crate) async fn decide_parent_change(
tx: &mut crate::AdmittedTx,
Expand All @@ -461,27 +467,34 @@ pub(crate) async fn decide_parent_change(
let actor_role_in_child = direct_role(tx, child, actor).await?;

let Some(parent) = change else {
if elevated_in(actor_role_in_child) {
return Ok(());
let authorized = elevated_in(actor_role_in_child)
|| match current_parent {
Some(current) => elevated_in(direct_role(tx, current, actor).await?),
None => false,
};
if !authorized {
return Err(DbError::AccessDenied(
"only an owner or admin of the channel or of its parent may clear its parent"
.into(),
));
}
if let Some(current) = current_parent {
if elevated_in(direct_role(tx, current, actor).await?) {
return Ok(());
}
// Without a parent, an auto-archiving channel with children would
// become an auto-archiving project. A channel filed under `child`
// locks `child` first, which this transaction holds.
if child_ttl.is_some() {
refuse_auto_archiving_project(false, has_live_children(tx, child).await?)?;
}
return Err(DbError::AccessDenied(
"only an owner or admin of the channel or of its parent may clear its parent".into(),
));
return Ok(());
};

if !elevated_in(actor_role_in_child) {
return Err(DbError::AccessDenied(
"only an owner or admin of the channel may set its parent".into(),
));
}
if !PARENTABLE_CHANNEL_TYPES.contains(&child_type.as_str()) || child_ttl.is_some() {
if !PARENTABLE_CHANNEL_TYPES.contains(&child_type.as_str()) {
return Err(DbError::InvalidData(
"only a stream or forum without a ttl can have a parent".into(),
"only a stream or forum can have a parent".into(),
));
}

Expand Down Expand Up @@ -518,11 +531,15 @@ pub(crate) async fn decide_parent_change(
let channel_type: String = row.try_get("channel_type")?;
let ttl: Option<i32> = row.try_get("ttl_seconds")?;
let archived: bool = row.try_get("archived")?;
if !PARENTABLE_CHANNEL_TYPES.contains(&channel_type.as_str()) || ttl.is_some() {
if !PARENTABLE_CHANNEL_TYPES.contains(&channel_type.as_str()) {
return Err(DbError::InvalidData(
"only a stream or forum without a ttl can be a parent".into(),
"only a stream or forum can be a parent".into(),
));
}
if ttl.is_some() {
let has_parent = row.try_get::<Option<Uuid>, _>("parent_id")?.is_some();
refuse_auto_archiving_project(has_parent, true)?;
}
if archived {
return Err(DbError::AccessDenied(
"the parent channel is archived".into(),
Expand Down Expand Up @@ -621,28 +638,53 @@ async fn subtree_height(tx: &mut crate::AdmittedTx, channel_id: Uuid) -> Result<
})
}

/// Refuse, on `tx`, giving `channel_id` a TTL while it has a parent or a
/// live child: only channels without a TTL take part in a tree. The caller
/// holds `channel_id`'s row lock, and a parent change locks the new parent
/// too, so neither can slip past the other.
pub(crate) async fn refuse_ttl_in_tree(tx: &mut crate::AdmittedTx, channel_id: Uuid) -> Result<()> {
/// Whether a project, a channel with live children and no parent of its
/// own, may auto-archive (have a TTL). A channel filed under a parent may,
/// whatever it holds. Allowing projects too means flipping this, the one
/// check every path goes through ([`refuse_auto_archiving_project`]).
const PROJECTS_MAY_AUTO_ARCHIVE: bool = false;

/// Refuse leaving an auto-archiving channel as a project: with live children
/// and no parent.
fn refuse_auto_archiving_project(has_parent: bool, has_live_children: bool) -> Result<()> {
if PROJECTS_MAY_AUTO_ARCHIVE || has_parent || !has_live_children {
return Ok(());
}
Err(DbError::InvalidData(
"a project (a channel with children and no parent) cannot have a ttl".into(),
))
}

/// Whether `channel_id` has a live child.
async fn has_live_children(tx: &mut crate::AdmittedTx, channel_id: Uuid) -> Result<bool> {
let community_id = tx.community();
let in_tree: bool = sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM channels WHERE community_id = $1 AND id = $2 \
AND parent_id IS NOT NULL) \
OR EXISTS (SELECT 1 FROM channels WHERE community_id = $1 AND parent_id = $2 \
Ok(sqlx::query_scalar(
"SELECT EXISTS (SELECT 1 FROM channels WHERE community_id = $1 AND parent_id = $2 \
AND deleted_at IS NULL)",
)
.bind(community_id.as_uuid())
.bind(channel_id)
.fetch_one(tx.conn())
.await?)
}

/// Refuse, on `tx`, giving `channel_id` a TTL while it is a project
/// ([`refuse_auto_archiving_project`]). The caller holds `channel_id`'s row
/// lock, and filing a channel under it locks it too, so neither can slip
/// past the other.
pub(crate) async fn refuse_ttl_on_project(
tx: &mut crate::AdmittedTx,
channel_id: Uuid,
) -> Result<()> {
let community_id = tx.community();
let has_parent: bool = sqlx::query_scalar(
"SELECT parent_id IS NOT NULL FROM channels WHERE community_id = $1 AND id = $2",
)
.bind(community_id.as_uuid())
.bind(channel_id)
.fetch_one(tx.conn())
.await?;
if in_tree {
return Err(DbError::InvalidData(
"a channel with a parent or children cannot have a TTL".to_string(),
));
}
Ok(())
refuse_auto_archiving_project(has_parent, has_live_children(tx, channel_id).await?)
}

/// The live private channels under `channel_id`, children and grandchildren.
Expand Down
134 changes: 122 additions & 12 deletions crates/buzz-relay/src/handlers/parent_access_postgres_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -568,12 +568,11 @@ async fn an_unlisted_projects_children_are_named_only() {
}

/// kind:39000 names the parent, and the child's metadata is readable by the
/// project's readers. A channel in a tree cannot take a TTL.
/// Mutation: drop the `parent` tag from `group_metadata_tags`, or the TTL
/// refusal → RED.
/// project's readers.
/// Mutation: drop the `parent` tag from `group_metadata_tags` → RED.
#[tokio::test]
#[ignore = "requires Postgres"]
async fn metadata_names_the_parent_and_a_tree_has_no_ttl() {
async fn metadata_names_the_parent() {
let t = Tree::new("parent-metadata").await;
let (state, tenant) = (&t.state, &t.tenant);
let tags = group_state_tags(state, tenant, t.child, 39000).await;
Expand All @@ -594,14 +593,6 @@ async fn metadata_names_the_parent_and_a_tree_has_no_ttl() {
"a project reader reads the child's metadata"
);

for channel in [t.child, t.project] {
assert!(
edit_channel(state, tenant, &t.owner, channel, &[&["ttl", "3600"]])
.await
.is_err(),
"a channel in a tree takes no TTL"
);
}
// A parent tag rides alone.
assert!(edit_channel(
state,
Expand Down Expand Up @@ -952,3 +943,122 @@ async fn only_the_channels_own_admin_changes_parent_access() {
assert_eq!(read_named(state, tenant, &t.reader, chat).await, vec![note]);
assert!(post(state, tenant, &t.reader, chat).await.is_err());
}

/// Expire `channel`'s TTL now and run the reaper, which must archive it.
async fn auto_archive(state: &Arc<AppState>, tenant: &TenantContext, channel: Uuid) {
sqlx::query(
"UPDATE channels SET ttl_deadline = clock_timestamp() - interval '1 second' \
WHERE community_id = $1 AND id = $2",
)
.bind(tenant.community().as_uuid())
.bind(channel)
.execute(state.db.pool())
.await
.expect("expire ttl");
let reaped = state
.db
.reap_expired_ephemeral_channels()
.await
.expect("reap");
assert!(
reaped.iter().any(|r| r.channel_id == channel),
"the reaper archives the expired channel: {reaped:?}"
);
}

/// A chat filed in a project may auto-archive. The project's readers post
/// in it before, and find and read it after, by name, implicitly, by COUNT
/// and through its metadata; an outsider still gets nothing.
/// Mutation: refuse a TTL on any channel with a parent → RED.
#[tokio::test]
#[ignore = "requires Postgres"]
async fn a_filed_chat_auto_archives_and_stays_readable_through_its_project() {
let t = Tree::new("parent-auto-archive").await;
let (state, tenant) = (&t.state, &t.tenant);
edit_channel(state, tenant, &t.owner, t.child, &[&["ttl", "3600"]])
.await
.expect("a filed chat takes a TTL");
let first = post(state, tenant, &t.owner, t.child).await.unwrap();
let second = post(state, tenant, &t.reader, t.child)
.await
.expect("a project reader posts in the auto-archiving chat");

auto_archive(state, tenant, t.child).await;

let mut read = read_named(state, tenant, &t.reader, t.child).await;
read.sort();
let mut expected = vec![first.clone(), second.clone()];
expected.sort();
assert_eq!(read, expected);
let implicit = read_implicit(state, tenant, &t.reader).await;
assert!(implicit.contains(&first) && implicit.contains(&second));
assert_eq!(
count_named(state, tenant, &t.reader, t.child).await,
Some(2)
);
assert_eq!(metadata_named(state, tenant, &t.reader, t.child).await, 1);
let tags = group_state_tags(state, tenant, t.child, 39000).await;
assert!(
tags.contains(&vec!["parent".to_string(), t.project.to_string()]),
"{tags:?}"
);
assert!(read_named(state, tenant, &t.outsider, t.child)
.await
.is_empty());
assert!(!read_implicit(state, tenant, &t.outsider)
.await
.contains(&first));
assert_eq!(role_in(state, tenant, t.child, &t.reader).await, None);
}

/// A project, a channel with children and no parent, never auto-archives:
/// not by taking a TTL, not by having a channel filed under it while it has
/// one, and not by losing its own parent while it has one and children. An
/// auto-archiving chat in a project may still hold task conversations.
/// Mutation: set `PROJECTS_MAY_AUTO_ARCHIVE` → RED.
#[tokio::test]
#[ignore = "requires Postgres"]
async fn a_project_never_auto_archives() {
let t = Tree::new("parent-project-ttl").await;
let (state, tenant) = (&t.state, &t.tenant);
assert!(
edit_channel(state, tenant, &t.owner, t.project, &[&["ttl", "3600"]])
.await
.is_err(),
"a project takes no TTL"
);

edit_channel(state, tenant, &t.owner, t.child, &[&["ttl", "3600"]])
.await
.expect("a filed chat takes a TTL");
let task = create_channel(state, tenant, &t.owner, &[&["visibility", "private"]]).await;
set_parent(state, tenant, &t.owner, task, Some(t.child))
.await
.expect("an auto-archiving filed chat holds a task conversation");
assert!(
set_parent(state, tenant, &t.owner, t.child, None)
.await
.is_err(),
"clearing its parent would leave an auto-archiving project"
);

let standalone = create_channel(state, tenant, &t.owner, &[]).await;
edit_channel(state, tenant, &t.owner, standalone, &[&["ttl", "3600"]])
.await
.expect("a channel outside any tree takes a TTL");
let other = create_channel(state, tenant, &t.owner, &[]).await;
assert!(
set_parent(state, tenant, &t.owner, other, Some(standalone))
.await
.is_err(),
"filing under it would make it an auto-archiving project"
);
set_parent(state, tenant, &t.owner, standalone, Some(t.project))
.await
.expect("an auto-archiving channel is filed in a project");

// Without children, a filed auto-archiving channel may leave its project.
set_parent(state, tenant, &t.owner, standalone, None)
.await
.expect("a childless auto-archiving channel leaves its project");
}
Loading