diff --git a/crates/buzz-core/src/artifact.rs b/crates/buzz-core/src/artifact.rs index 2d8bfb67ccf..8a8945b52ab 100644 --- a/crates/buzz-core/src/artifact.rs +++ b/crates/buzz-core/src/artifact.rs @@ -56,6 +56,23 @@ pub struct ArtifactEnvelope { pub prev: Option>, /// Optional conversation anchor. pub root: Option>, + /// Who created the artifact (`["creator", ]`), when the + /// revision names them. The relay holds it to the creating signer. + pub creator: Option, + /// The people assigned (`["assignee", ]`), distinct, in tag + /// order. The relay holds each to someone who can read the home. + pub assignees: Vec, +} + +/// The most `assignee` tags one revision may carry. +pub const MAX_ASSIGNEES: usize = 4; + +/// Whether `value` is a lowercase hex public key. +fn hex_pubkey(value: &str) -> bool { + value.len() == 64 + && value + .bytes() + .all(|b| matches!(b, b'0'..=b'9' | b'a'..=b'f')) } /// Parse a canonical, non-nil UUID. pub fn canonical_uuid(value: &str) -> Result { @@ -156,6 +173,29 @@ pub fn validate(event: &Event) -> Result { return Err("title must be nonblank and at most 512 UTF-8 bytes"); } } + let mut creator = None; + let mut assignees: Vec = Vec::new(); + for tag in event.tags.iter() { + let parts = tag.as_slice(); + match parts[0].as_str() { + "creator" => { + if parts.len() != 2 || !hex_pubkey(&parts[1]) || creator.is_some() { + return Err("creator must occur at most once as a lowercase hex pubkey"); + } + creator = Some(parts[1].clone()); + } + "assignee" => { + if parts.len() != 2 || !hex_pubkey(&parts[1]) || assignees.contains(&parts[1]) { + return Err("each assignee must be a distinct lowercase hex pubkey"); + } + assignees.push(parts[1].clone()); + } + _ => {} + } + } + if assignees.len() > MAX_ASSIGNEES { + return Err("too-many-assignees: — a revision names at most 4 assignees"); + } Ok(ArtifactEnvelope { id, home, @@ -163,6 +203,8 @@ pub fn validate(event: &Event) -> Result { op, prev, root, + creator, + assignees, }) } /// Domain separator for [`conversation_id`]. @@ -240,9 +282,48 @@ mod tests { (vec![], "delete", "hidden"), (vec![vec!["x".into(), "x".repeat(4097)]], "create", ""), (vec![vec!["x".repeat(129), "x".into()]], "create", ""), + (vec![vec!["creator".into(), "A".repeat(64)]], "create", ""), + ( + vec![ + vec!["creator".into(), "a".repeat(64)], + vec!["creator".into(), "b".repeat(64)], + ], + "create", + "", + ), + (vec![vec!["assignee".into(), "a".repeat(63)]], "create", ""), + ( + vec![ + vec!["assignee".into(), "a".repeat(64)], + vec!["assignee".into(), "a".repeat(64)], + ], + "create", + "", + ), + ( + (0..=MAX_ASSIGNEES) + .map(|i| vec!["assignee".into(), format!("{i:064x}")]) + .collect(), + "create", + "", + ), + (vec![vec!["creator".into(), "a".repeat(64)]], "delete", ""), + (vec![vec!["assignee".into(), "a".repeat(64)]], "delete", ""), ] { assert!(validate(&event(tags, op, content)).is_err()); } + let env = validate(&event( + vec![ + vec!["creator".into(), "c".repeat(64)], + vec!["assignee".into(), "a".repeat(64)], + vec!["assignee".into(), "b".repeat(64)], + ], + "update", + "", + )) + .unwrap(); + assert_eq!(env.creator, Some("c".repeat(64))); + assert_eq!(env.assignees, vec!["a".repeat(64), "b".repeat(64)]); } #[test] fn filter_routes_and_views() { @@ -277,6 +358,14 @@ mod tests { assert_eq!(query.view, ArtifactView::Current); let head = parse_query(&json!({"artifact":"head","#d":["x"]})).unwrap(); assert_eq!(head.view, ArtifactView::Head); + let project = "8c1f3d2e-4b5a-4c6d-9e7f-0a1b2c3d4e5f"; + let find = parse_query(&json!({ + "artifact":"current","until":1700000000,"unassigned":true,"within":project + })) + .unwrap(); + assert_eq!(find.until, Some(1700000000)); + assert!(find.unassigned); + assert_eq!(find.within, Some(Uuid::parse_str(project).unwrap())); for invalid in [ json!({"artifact":"lookup","#d":["x"]}), json!({"artifact":"history"}), @@ -287,6 +376,14 @@ mod tests { json!({"artifact":"history","#d":[]}), json!({"artifact":"head"}), json!({"artifact":"sync","#h":["c"]}), + json!({"artifact":"current","until":-1}), + json!({"artifact":"current","until":"1"}), + json!({"artifact":"current","unassigned":false}), + json!({"artifact":"current","unassigned":true,"#assignee":["a"]}), + json!({"artifact":"current","within":"p"}), + json!({"artifact":"current","within":project.to_uppercase()}), + json!({"artifact":"head","#d":["x"],"unassigned":true}), + json!({"artifact":"history","#d":["x"],"within":project}), ] { assert!(parse_query(&invalid).is_err(), "{invalid}"); } @@ -323,6 +420,14 @@ pub struct ArtifactQuery { pub limit: i64, /// Bounded page offset. pub offset: i64, + /// Only revisions created at or before this Unix time; the page is then + /// ordered by `created_at`, newest first. + pub until: Option, + /// Only artifacts with no `assignee` tag. + pub unassigned: bool, + /// Only artifacts whose home is this channel or a channel filed under + /// it, as far as the reader may read. + pub within: Option, } /// Maximum artifact page offset. pub const MAX_OFFSET: u64 = 10000; @@ -368,7 +473,18 @@ pub fn parse_query(value: &serde_json::Value) -> Result ArtifactView::Head, _ => return Err("artifact must be \"current\", \"history\" or \"head\""), }; - let tags = parse_predicates(object, &["artifact", "kinds", "limit", "offset"])?; + let tags = parse_predicates( + object, + &[ + "artifact", + "kinds", + "limit", + "offset", + "until", + "unassigned", + "within", + ], + )?; let number = |name: &str, default: u64| { object .get(name) @@ -384,11 +500,41 @@ pub fn parse_query(value: &serde_json::Value) -> Result false, + Some(serde_json::Value::Bool(true)) => true, + Some(_) => return Err("unassigned must be true"), + }; + let within = object + .get("within") + .map(|v| { + v.as_str() + .ok_or("invalid within") + .and_then(|v| canonical_uuid(v).map_err(|_| "invalid within")) + }) + .transpose()?; + if view != ArtifactView::Current && (unassigned || within.is_some()) { + return Err("unassigned and within require the current view"); + } + if unassigned && tags.iter().any(|(n, _)| n == "assignee") { + return Err("unassigned excludes #assignee"); + } Ok(ArtifactQuery { view, tags, limit: limit as i64, offset: offset as i64, + until, + unassigned, + within, }) } /// Parse the `kinds` and `#name` predicates shared by every artifact filter. diff --git a/crates/buzz-db/src/runtime/migration.rs b/crates/buzz-db/src/runtime/migration.rs index 38b00a11df7..f906712adb1 100644 --- a/crates/buzz-db/src/runtime/migration.rs +++ b/crates/buzz-db/src/runtime/migration.rs @@ -890,7 +890,7 @@ mod postgres_tests { let mut migrations: Vec<_> = MIGRATOR.iter().collect(); migrations.sort_by_key(|migration| migration.version); - assert_eq!(migrations.len(), 95); + assert_eq!(migrations.len(), 96); assert_eq!(migrations[89].version, 90); assert!(migrations[89] .sql @@ -944,6 +944,13 @@ mod postgres_tests { artifact_type.trim(), "ALTER TYPE channel_type ADD VALUE IF NOT EXISTS 'artifact';" ); + // Artifact creator and assignees (0096): nullable columns, so no rewrite and no + // backfill, under bounded locks. + let creator = strip_sql_comments(migrations[95].sql.as_str()); + assert!(creator.contains("SET LOCAL lock_timeout = '1s';")); + assert!(creator.contains("ADD COLUMN IF NOT EXISTS creator TEXT;")); + assert!(creator.contains("ADD COLUMN IF NOT EXISTS assignees TEXT[];")); + assert!(!creator.to_ascii_uppercase().contains("UPDATE ")); for (index, migration) in migrations.iter().enumerate() { assert_eq!(migration.version, (index + 1) as i64); } diff --git a/crates/buzz-db/src/store/artifact.rs b/crates/buzz-db/src/store/artifact.rs index c80dec1dea1..b5f1e8914ed 100644 --- a/crates/buzz-db/src/store/artifact.rs +++ b/crates/buzz-db/src/store/artifact.rs @@ -30,6 +30,24 @@ pub enum ArtifactOutcome { Conflict(&'static str), /// Protocol violation with a public-safe reason. Rejected(&'static str), + /// Refused under a stable reason code (NIP-AR), naming the keys involved. + Refused { + /// The reason code. + code: &'static str, + /// The keys the refusal is about, lowercase hex, or `none`. + keys: Vec, + }, +} + +/// Which of a revision's assignees the relay found it may not name, judged +/// before the transaction. The transaction decides which of them count: +/// everyone on a create, move or restore; only those an update adds. +#[derive(Debug, Default)] +pub struct AssigneeFindings { + /// Assignees recorded as agents. + pub agents: Vec, + /// Assignees who can't read the revision's home. + pub unreadable: Vec, } /// Outcome of a request to open an artifact's conversation. @@ -53,6 +71,62 @@ pub const CONVERSATION_CANNOT_MOVE: &str = "this artifact's comments can't move /// outside every channel the sender was authorized for. pub const HEAD_UNAVAILABLE: &str = "artifact head unavailable"; +/// The head's creator and assignees. A head saved before the relay kept +/// them has no assignee list (NULL, distinct from an empty one) and is +/// filled from what is still on hand: the creator is the signer of the first +/// save, else the current revision's `creator` tag, else stays unknown +/// (`None`), and nobody can claim it later. The assignees are the current +/// revision's; `None` when that revision is gone, so everyone counts as +/// added. +async fn known_creator_and_assignees( + tx: &mut crate::AdmittedTx, + community: CommunityId, + artifact: Uuid, + head: &sqlx::postgres::PgRow, +) -> Result<(Option, Option>)> { + let creator: Option = head.get("creator"); + // Every head saved since keeps a list, empty when nobody is assigned. + if let Some(assignees) = head.get::>, _>("assignees") { + return Ok((creator, Some(assignees))); + } + let current: Option = sqlx::query_scalar( + "SELECT tags FROM events WHERE community_id=$1 AND id=$2 AND deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .bind(head.get::, _>("event_id")) + .fetch_optional(tx.conn()) + .await?; + let tag_values = |name: &str| -> Vec { + current + .as_ref() + .and_then(|tags| tags.as_array()) + .into_iter() + .flatten() + .filter_map(|tag| match tag.as_array().map(Vec::as_slice) { + Some([key, value]) if key == name => value.as_str().map(str::to_owned), + _ => None, + }) + .collect() + }; + let creator = match creator { + Some(creator) => Some(creator), + None => { + let first_signer: Option> = sqlx::query_scalar( + "SELECT e.pubkey FROM (SELECT event_id FROM artifact_revisions WHERE community_id=$1 AND artifact_id=$2 ORDER BY modified_at,event_id LIMIT 1) r JOIN events e ON e.community_id=$1 AND e.id=r.event_id AND e.deleted_at IS NULL", + ) + .bind(community.as_uuid()) + .bind(artifact) + .fetch_optional(tx.conn()) + .await?; + match first_signer { + Some(pubkey) => Some(hex::encode(pubkey)), + None => tag_values("creator").into_iter().next(), + } + } + }; + Ok((creator, current.is_some().then(|| tag_values("assignee")))) +} + fn invalid(message: &str) -> DbError { DbError::InvalidData(message.into()) } @@ -124,6 +198,7 @@ impl Db { event: &Event, env: &ArtifactEnvelope, authorized_source: Option, + findings: &AssigneeFindings, relay_keys: &Keys, ) -> Result { let mut tx = self.begin_event_write_transaction(community).await?; @@ -146,7 +221,7 @@ impl Db { return Ok(ArtifactOutcome::Duplicate); } let head = sqlx::query( - "SELECT event_id,channel_id,artifact_type,root,deleted FROM artifact_heads WHERE community_id=$1 AND artifact_id=$2 FOR UPDATE", + "SELECT event_id,channel_id,artifact_type,root,deleted,creator,assignees FROM artifact_heads WHERE community_id=$1 AND artifact_id=$2 FOR UPDATE", ) .bind(community.as_uuid()) .bind(env.id) @@ -197,6 +272,59 @@ impl Db { } } } + // The creator, named on create, is the creating signer and never + // changes; the assignees are the current revision's. The head holds + // both, so they outlive retention and redaction. A head saved before + // the relay kept them fills them here, under the lock. + let signer = event.pubkey.to_hex(); + let (creator, stored_assignees) = match &head { + None => (env.creator.clone(), None), + Some(head) => known_creator_and_assignees(&mut tx, community, env.id, head).await?, + }; + match env.op { + ArtifactOp::Create => { + if let Some(claimed) = env.creator.as_ref().filter(|c| **c != signer) { + return Ok(ArtifactOutcome::Refused { + code: "creator-not-signer", + keys: vec![claimed.clone()], + }); + } + } + // A delete carries no creator; a restore names it again. + ArtifactOp::Delete => {} + _ => { + if env.creator != creator { + return Ok(ArtifactOutcome::Refused { + code: "creator-changed", + keys: vec![creator.unwrap_or_else(|| "none".into())], + }); + } + } + } + // Every assignee is checked when the artifact lands somewhere (a + // create, move or restore); an update is checked only for the people + // it adds, so someone who lost access since doesn't block it. + let checked: Vec<&String> = env + .assignees + .iter() + .filter(|a| match (env.op, &stored_assignees) { + (ArtifactOp::Update, Some(stored)) => !stored.contains(a), + _ => true, + }) + .collect(); + for (code, found) in [ + ("assignee-agent", &findings.agents), + ("assignee-unreadable", &findings.unreadable), + ] { + let keys: Vec = checked + .iter() + .filter(|a| found.contains(a)) + .map(|a| (*a).clone()) + .collect(); + if !keys.is_empty() { + return Ok(ArtifactOutcome::Refused { code, keys }); + } + } if source != Some(env.home) { // A conversation holds comments, never artifacts. let home_type: Option = sqlx::query_scalar( @@ -232,8 +360,8 @@ impl Db { .bind(if env.op == ArtifactOp::Move { source } else { None }) .execute(tx.conn()) .await?; - sqlx::query("INSERT INTO artifact_heads (community_id,artifact_id,event_id,channel_id,artifact_type,root,deleted,modified_at) VALUES ($1,$2,$3,$4,$5,$6,$7,clock_timestamp()) ON CONFLICT (community_id,artifact_id) DO UPDATE SET event_id=EXCLUDED.event_id,channel_id=EXCLUDED.channel_id,root=EXCLUDED.root,deleted=EXCLUDED.deleted,modified_at=clock_timestamp()") - .bind(community.as_uuid()).bind(env.id).bind(event.id.as_bytes().as_slice()).bind(env.home).bind(&env.artifact_type).bind(&env.root).bind(env.op == ArtifactOp::Delete).execute(tx.conn()).await?; + sqlx::query("INSERT INTO artifact_heads (community_id,artifact_id,event_id,channel_id,artifact_type,root,deleted,creator,assignees,modified_at) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9,clock_timestamp()) ON CONFLICT (community_id,artifact_id) DO UPDATE SET event_id=EXCLUDED.event_id,channel_id=EXCLUDED.channel_id,root=EXCLUDED.root,deleted=EXCLUDED.deleted,creator=EXCLUDED.creator,assignees=EXCLUDED.assignees,modified_at=clock_timestamp()") + .bind(community.as_uuid()).bind(env.id).bind(event.id.as_bytes().as_slice()).bind(env.home).bind(&env.artifact_type).bind(&env.root).bind(env.op == ArtifactOp::Delete).bind(&creator).bind(&env.assignees).execute(tx.conn()).await?; let conversation = match env.op { ArtifactOp::Move | ArtifactOp::Delete | ArtifactOp::Restore => { match follow_artifact(&mut tx, env).await? { diff --git a/crates/buzz-db/src/store/artifact_postgres_tests.rs b/crates/buzz-db/src/store/artifact_postgres_tests.rs index d8be9b92812..948ca71ceb7 100644 --- a/crates/buzz-db/src/store/artifact_postgres_tests.rs +++ b/crates/buzz-db/src/store/artifact_postgres_tests.rs @@ -97,7 +97,14 @@ impl Fixture { async fn accept(&self, e: &Event, source: Option) -> ArtifactOutcome { let env = artifact::validate(e).unwrap(); self.db - .accept_artifact(self.community, e, &env, source, &self.relay) + .accept_artifact( + self.community, + e, + &env, + source, + &Default::default(), + &self.relay, + ) .await .unwrap() } @@ -564,7 +571,14 @@ async fn quiescing_community_rejects_artifact_at_admission_before_coordinate_loc .unwrap(); let error = tokio::time::timeout( std::time::Duration::from_secs(5), - f.db.accept_artifact(f.community, &create, &env, None, &f.relay), + f.db.accept_artifact( + f.community, + &create, + &env, + None, + &Default::default(), + &f.relay, + ), ) .await .expect("admission must reject before waiting on the coordinate lock") diff --git a/crates/buzz-db/src/store/artifact_query.rs b/crates/buzz-db/src/store/artifact_query.rs index 43346e57815..c54080a9337 100644 --- a/crates/buzz-db/src/store/artifact_query.rs +++ b/crates/buzz-db/src/store/artifact_query.rs @@ -47,6 +47,27 @@ pub(super) fn predicates( .push(")"); } } + if query.unassigned { + qb.push(" AND NOT EXISTS (SELECT 1 FROM jsonb_array_elements(e.tags) tag WHERE tag->>0='assignee')"); + } + if let Some(within) = query.within { + // The channel and what is filed under it, two levels deep like every + // channel tree (`crate::channel_tree`); the scope above still decides + // what the reader may read. + qb.push(" AND (e.channel_id=") + .push_bind(within) + .push(" OR EXISTS (SELECT 1 FROM channels d WHERE d.community_id=e.community_id AND d.id=e.channel_id AND d.deleted_at IS NULL AND (d.parent_id=") + .push_bind(within) + .push(" OR EXISTS (SELECT 1 FROM channels m WHERE m.community_id=d.community_id AND m.id=d.parent_id AND m.deleted_at IS NULL AND m.parent_id=") + .push_bind(within) + .push("))))"); + } + if let Some(until) = query.until { + qb.push(" AND e.created_at<=").push_bind( + chrono::DateTime::from_timestamp(until, 0) + .unwrap_or(chrono::DateTime::::MAX_UTC), + ); + } } /// Append the reader's permission scope and the exact tag predicates. A @@ -230,10 +251,16 @@ impl Db { tx.commit().await?; return Ok((vec![], n)); } - qb.push(" ORDER BY e.received_at DESC,e.id ASC LIMIT ") - .push_bind(query.limit) - .push(" OFFSET ") - .push_bind(query.offset); + // With `until`, the page follows `created_at`, so the next page asks + // `until` the oldest it got; without it, newest received first. + qb.push(if query.until.is_some() { + " ORDER BY e.created_at DESC,e.id ASC LIMIT " + } else { + " ORDER BY e.received_at DESC,e.id ASC LIMIT " + }) + .push_bind(query.limit) + .push(" OFFSET ") + .push_bind(query.offset); let events = rows_to_events(qb.build().fetch_all(&mut *tx).await?)?; tx.commit().await?; Ok((events, 0)) diff --git a/crates/buzz-db/src/store/user.rs b/crates/buzz-db/src/store/user.rs index fbcc46c62a7..c668f407a02 100644 --- a/crates/buzz-db/src/store/user.rs +++ b/crates/buzz-db/src/store/user.rs @@ -533,6 +533,23 @@ pub async fn owned_agents_among( .await?) } +/// Of `candidates`, the keys this community has recorded as agents: those +/// with an `agent_owner_pubkey`. An agent that never presented an owner +/// attestation has none, so this finds known agents only. +pub async fn agents_among( + pool: &PgPool, + community_id: CommunityId, + candidates: &[Vec], +) -> Result>> { + Ok(sqlx::query_scalar::<_, Vec>( + "SELECT pubkey FROM users WHERE community_id = $1 AND agent_owner_pubkey IS NOT NULL AND pubkey = ANY($2)", + ) + .bind(community_id.as_uuid()) + .bind(candidates) + .fetch_all(pool) + .await?) +} + /// Check whether `actor_pubkey` is the `agent_owner_pubkey` of `target_pubkey`. /// Queries `agent_owner_pubkey` directly rather than going through /// `get_agent_channel_policy`, which would fetch unrelated fields. @@ -750,6 +767,16 @@ impl Db { crate::user::owned_agents_among(&self.pool, community_id, owner_pubkey, candidates).await } + /// Of `candidates`, the keys recorded as agents in one community. + #[datastore_span(name = "agents_among", system = "postgresql")] + pub async fn agents_among( + &self, + community_id: CommunityId, + candidates: &[Vec], + ) -> Result>> { + crate::user::agents_among(&self.pool, community_id, candidates).await + } + /// Check whether `actor_pubkey` is the agent owner of `target_pubkey`. #[datastore_span(name = "is_agent_owner", system = "postgresql")] pub async fn is_agent_owner( diff --git a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs index c3cb82e32a8..0887793cab8 100644 --- a/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs +++ b/crates/buzz-relay/src/api/artifact_postgres_tests/sync_postgres_tests.rs @@ -45,6 +45,7 @@ async fn accept(f: &Fixture, event: &Event) { event, &envelope, source, + &Default::default(), &f.state.relay_keypair ) .await diff --git a/crates/buzz-relay/src/api/artifact_sync.rs b/crates/buzz-relay/src/api/artifact_sync.rs index 8b50f748939..a3f8be213c1 100644 --- a/crates/buzz-relay/src/api/artifact_sync.rs +++ b/crates/buzz-relay/src/api/artifact_sync.rs @@ -141,9 +141,12 @@ async fn execute( filter: &Value, ) -> Response { let request: Request = serde_json::from_value(filter.clone()).map_err(|_| invalid())?; + // Paging and the current-read-only filters have no incremental form; a + // filter this path would not apply is refused, never ignored. if request.artifact != "incremental" - || request.query.get("limit").is_some() - || request.query.get("offset").is_some() + || ["limit", "offset", "until", "unassigned", "within"] + .iter() + .any(|key| request.query.get(*key).is_some()) { return Err(invalid()); } diff --git a/crates/buzz-relay/src/handlers/artifact.rs b/crates/buzz-relay/src/handlers/artifact.rs index 01f418a2711..f7671d3e6f3 100644 --- a/crates/buzz-relay/src/handlers/artifact.rs +++ b/crates/buzz-relay/src/handlers/artifact.rs @@ -3,7 +3,7 @@ use super::ingest::{IngestAuth, IngestError, IngestResult}; use crate::state::AppState; use buzz_core::artifact::ArtifactOp; use buzz_core::{StoredEvent, TenantContext}; -use buzz_db::artifact::{ArtifactOutcome, ConversationOutcome}; +use buzz_db::artifact::{ArtifactOutcome, AssigneeFindings, ConversationOutcome}; use nostr::Event; use std::sync::Arc; @@ -36,6 +36,21 @@ pub(crate) async fn accept( } else { None }; + // Task saves are signed by people; an agent acts through its owner's + // key with a "via" label. Only agents with an owner on record are known. + let signer = event.pubkey.to_bytes().to_vec(); + if !state + .db + .agents_among(tenant.community(), std::slice::from_ref(&signer)) + .await + .map_err(|e| IngestError::Internal(format!("artifact signer: {e}")))? + .is_empty() + { + return Err(refused("signer-agent", &[event.pubkey.to_hex()])); + } + let findings = assignee_findings(state, tenant, &env) + .await + .map_err(|e| IngestError::Internal(format!("artifact assignee: {e}")))?; let outcome = state .db .accept_artifact( @@ -43,6 +58,7 @@ pub(crate) async fn accept( event, &env, source, + &findings, &state.relay_keypair, ) .await @@ -71,6 +87,7 @@ pub(crate) async fn accept( ArtifactOutcome::Rejected(message) => { return Err(IngestError::Rejected(format!("invalid: {message}"))) } + ArtifactOutcome::Refused { code, keys } => return Err(refused(code, &keys)), } Ok(IngestResult { event_id: event.id.to_hex(), @@ -79,6 +96,53 @@ pub(crate) async fn accept( }) } +/// Which of `env`'s assignees are recorded agents and which can't read its +/// home. The acceptance transaction decides which of them the revision is +/// held to (NIP-AR, Assignees). A delete names nobody. +async fn assignee_findings( + state: &AppState, + tenant: &TenantContext, + env: &buzz_core::artifact::ArtifactEnvelope, +) -> Result { + let mut findings = AssigneeFindings::default(); + if env.assignees.is_empty() { + return Ok(findings); + } + // Validation admits only lowercase hex pubkeys. + let keys: Vec> = env + .assignees + .iter() + .filter_map(|a| hex::decode(a).ok()) + .collect(); + findings.agents = state + .db + .agents_among(tenant.community(), &keys) + .await? + .into_iter() + .map(hex::encode) + .collect(); + for (assignee, key) in env.assignees.iter().zip(&keys) { + if !super::channel_access::can_read(state, tenant.community(), key, env.home).await? { + findings.unreadable.push(assignee.clone()); + } + } + Ok(findings) +} + +/// A refusal under a NIP-AR reason code: `invalid: : — `, +/// keys comma-separated. +fn refused(code: &str, keys: &[String]) -> IngestError { + let text = match code { + "signer-agent" => "an agent can't sign an artifact; its owner signs", + "assignee-agent" => "an agent can't be an assignee", + "assignee-unreadable" => "an assignee can't see this artifact", + "creator-not-signer" => "creator must be the signer on create", + "creator-changed" => "creator cannot change; resend with the named creator", + _ => "refused", + }; + IngestError::Rejected(format!("invalid: {code}:{} — {text}", keys.join(","))) +} + /// The tag on a kind:9007 that opens an artifact's conversation and names /// the artifact. pub(crate) const CONVERSATION_ARTIFACT_TAG: &str = "artifact"; diff --git a/crates/buzz-relay/src/handlers/artifact_assignee_postgres_tests.rs b/crates/buzz-relay/src/handlers/artifact_assignee_postgres_tests.rs new file mode 100644 index 00000000000..cb275cc7bca --- /dev/null +++ b/crates/buzz-relay/src/handlers/artifact_assignee_postgres_tests.rs @@ -0,0 +1,840 @@ +//! Postgres-backed tests for who a task names (NOSTR.md, NIP-AR Assignees +//! and Creator) and for finding tasks by them. Saves go through real +//! ingest, reads through the real `POST /query` route. + +use std::sync::Arc; + +use buzz_core::TenantContext; +use nostr::{Event, EventBuilder, Keys, Kind, Tag}; +use serde_json::{json, Value}; +use uuid::Uuid; + +use crate::handlers::artifact_conversation_postgres_tests::send; +use crate::handlers::channel_access_postgres_tests::{live_state, query}; +use crate::handlers::group_state_postgres_tests::{community, create_channel}; +use crate::handlers::parent_access_postgres_tests::{add, set_parent}; +use crate::state::AppState; + +/// A `buzz.task` revision of `id` in `home`, signed by `key`, created at +/// `at`, with `extra` tags. +fn revision( + key: &Keys, + home: Uuid, + id: Uuid, + op: &str, + prev: Option<&Event>, + extra: &[[&str; 2]], + at: u64, +) -> Event { + let mut tags = vec![ + vec!["ar".to_owned(), "1".into()], + vec!["d".into(), id.to_string()], + vec!["h".into(), home.to_string()], + vec!["type".into(), "buzz.task".into()], + vec!["op".into(), op.into()], + ]; + if op != "delete" { + tags.push(vec!["title".into(), "Review".into()]); + } + if let Some(prev) = prev { + tags.push(vec!["prev".into(), prev.id.to_hex()]); + } + tags.extend( + extra + .iter() + .map(|[n, v]| vec![n.to_string(), v.to_string()]), + ); + EventBuilder::new(Kind::Custom(45010), if op == "delete" { "" } else { "x" }) + .tags(tags.into_iter().map(|t| Tag::parse(t).unwrap())) + .custom_created_at(nostr::Timestamp::from(at)) + .sign_with_keys(key) + .unwrap() +} + +fn now() -> u64 { + nostr::Timestamp::now().as_secs() +} + +/// The project, a child and a grandchild filed under it, all private and +/// owned by `owner`; `member` is a member of the project only; `elsewhere` +/// is a private channel only `owner` reads. +struct Fixture { + state: Arc, + tenant: TenantContext, + owner: Keys, + member: Keys, + project: Uuid, + child: Uuid, + grandchild: Uuid, + elsewhere: Uuid, +} + +impl Fixture { + async fn new(label: &str) -> Self { + let state = live_state().await; + let tenant = community(&state, label).await; + let owner = Keys::generate(); + let member = Keys::generate(); + let private: &[&[&str]] = &[&["visibility", "private"]]; + let project = create_channel(&state, &tenant, &owner, private).await; + let child = create_channel(&state, &tenant, &owner, private).await; + let grandchild = create_channel(&state, &tenant, &owner, private).await; + let elsewhere = create_channel(&state, &tenant, &owner, private).await; + set_parent(&state, &tenant, &owner, child, Some(project)) + .await + .expect("file the child"); + set_parent(&state, &tenant, &owner, grandchild, Some(child)) + .await + .expect("file the grandchild"); + add(&state, &tenant, &owner, project, &member, "member").await; + Self { + state, + tenant, + owner, + member, + project, + child, + grandchild, + elsewhere, + } + } + + async fn save(&self, event: &Event) -> Result<(), String> { + send(&self.state, &self.tenant, event.clone()).await + } + + /// The `d` of each artifact `viewer` finds with `filter`, in order. + async fn find(&self, viewer: &Keys, filter: Value) -> Vec { + let (status, body) = query(&self.state, &self.tenant, viewer, &json!([filter]), true).await; + assert!(status.is_success(), "{filter}: {status} {body}"); + body.as_array() + .unwrap() + .iter() + .map(|e| { + e["tags"] + .as_array() + .unwrap() + .iter() + .find(|t| t[0] == "d") + .unwrap()[1] + .as_str() + .unwrap() + .to_owned() + }) + .collect() + } +} + +/// `r` is refused under reason `code`, naming exactly `keys`. +fn refused(r: Result<(), String>, code: &str, keys: &[&str]) { + let e = r.expect_err("refused"); + assert!( + e.contains(&format!("invalid: {code}:{} — ", keys.join(","))), + "{code}: {e}" + ); +} + +impl Fixture { + /// A fresh key recorded as an agent of `owner`, made a member of the + /// project so only its being an agent can refuse it. + async fn agent(&self) -> Keys { + let agent = Keys::generate(); + let community = self.tenant.community(); + for key in [&agent, &self.owner] { + self.state + .db + .ensure_user(community, key.public_key().as_bytes()) + .await + .expect("ensure user"); + } + self.state + .db + .set_agent_owner( + community, + agent.public_key().as_bytes(), + self.owner.public_key().as_bytes(), + ) + .await + .expect("record the owner"); + add( + &self.state, + &self.tenant, + &self.owner, + self.project, + &agent, + "member", + ) + .await; + agent + } + + /// Forget the head's creator and assignees, as a head saved before the + /// relay kept them. + async fn as_before_0096(&self, id: Uuid) { + sqlx::query("UPDATE artifact_heads SET creator=NULL, assignees=NULL WHERE community_id=$1 AND artifact_id=$2") + .bind(self.tenant.community().as_uuid()) + .bind(id) + .execute(self.state.db.pool()) + .await + .expect("forget the head's creator and assignees"); + } + + /// Expire a stored payload, as retention may. + async fn expire(&self, event: &Event) { + sqlx::query("DELETE FROM events WHERE community_id=$1 AND id=$2") + .bind(self.tenant.community().as_uuid()) + .bind(event.id.as_bytes().as_slice()) + .execute(self.state.db.pool()) + .await + .expect("expire a payload"); + } + + async fn head(&self, id: Uuid) -> (Option, Option>) { + sqlx::query_as("SELECT creator, assignees FROM artifact_heads WHERE community_id=$1 AND artifact_id=$2") + .bind(self.tenant.community().as_uuid()) + .bind(id) + .fetch_one(self.state.db.pool()) + .await + .expect("head") + } + + async fn remove_from_project(&self, person: &Keys) { + let removal = EventBuilder::new(Kind::Custom(9001), "") + .tags([ + Tag::parse(["h", &self.project.to_string()]).unwrap(), + Tag::parse(["p", &person.public_key().to_hex()]).unwrap(), + ]) + .sign_with_keys(&self.owner) + .unwrap(); + self.save(&removal).await.expect("remove from the project"); + } +} + +/// Every assignee must be able to read the home a save puts the task in. +/// A create, move or restore checks everyone; an update checks only the +/// people it adds, so someone who lost access since doesn't block an +/// unrelated edit. The refusal names who failed. At most four, people only, +/// and an agent can't sign the save. +/// Mutation: skip the assignee check, check everyone on an update, check +/// nobody on a move or restore, raise the cap, or skip either agent check +/// → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn every_assignee_must_see_the_task() { + let f = Fixture::new("assignees").await; + let member = f.member.public_key().to_hex(); + let outsider = Keys::generate().public_key().to_hex(); + let id = Uuid::new_v4(); + + refused( + f.save(&revision( + &f.owner, + f.child, + id, + "create", + None, + &[["assignee", &outsider]], + now(), + )) + .await, + "assignee-unreadable", + &[&outsider], + ); + let create = revision( + &f.owner, + f.child, + id, + "create", + None, + &[["assignee", &member]], + now(), + ); + f.save(&create) + .await + .expect("the member reads the child through the project"); + refused( + f.save(&revision( + &f.owner, + f.child, + id, + "update", + Some(&create), + &[["assignee", &member], ["assignee", &outsider]], + now(), + )) + .await, + "assignee-unreadable", + &[&outsider], + ); + refused( + f.save(&revision( + &f.owner, + f.elsewhere, + id, + "move", + Some(&create), + &[["assignee", &member]], + now(), + )) + .await, + "assignee-unreadable", + &[&member], + ); + let moved = revision(&f.owner, f.elsewhere, id, "move", Some(&create), &[], now()); + f.save(&moved).await.expect("a move without the member"); + refused( + f.save(&revision( + &f.owner, + f.elsewhere, + id, + "update", + Some(&moved), + &[["assignee", &member]], + now(), + )) + .await, + "assignee-unreadable", + &[&member], + ); + + // Access lost after assignment: an edit that keeps them is accepted, a + // move or restore that keeps them is refused, a delete names nobody. + let other = Uuid::new_v4(); + let created = revision( + &f.owner, + f.grandchild, + other, + "create", + None, + &[["assignee", &member]], + now(), + ); + f.save(&created).await.expect("assigned in the grandchild"); + f.remove_from_project(&f.member).await; + // Measured against the stored current state, even once retention has + // expired the revision that assigned them. + f.expire(&created).await; + let edit = revision( + &f.owner, + f.grandchild, + other, + "update", + Some(&created), + &[["assignee", &member]], + now(), + ); + f.save(&edit) + .await + .expect("an edit that adds nobody isn't held to a lost access"); + refused( + f.save(&revision( + &f.owner, + f.child, + other, + "move", + Some(&edit), + &[["assignee", &member]], + now(), + )) + .await, + "assignee-unreadable", + &[&member], + ); + let deleted = revision( + &f.owner, + f.grandchild, + other, + "delete", + Some(&edit), + &[], + now(), + ); + f.save(&deleted).await.expect("a delete names nobody"); + refused( + f.save(&revision( + &f.owner, + f.grandchild, + other, + "restore", + Some(&deleted), + &[["assignee", &member]], + now(), + )) + .await, + "assignee-unreadable", + &[&member], + ); + + // At most four, people only, signed by a person. + let five: Vec = (0..5) + .map(|_| Keys::generate().public_key().to_hex()) + .collect(); + let tags: Vec<[&str; 2]> = five.iter().map(|k| ["assignee", k.as_str()]).collect(); + refused( + f.save(&revision( + &f.owner, + f.child, + Uuid::new_v4(), + "create", + None, + &tags, + now(), + )) + .await, + "too-many-assignees", + &[], + ); + let agent = f.agent().await; + let agent_hex = agent.public_key().to_hex(); + refused( + f.save(&revision( + &f.owner, + f.child, + Uuid::new_v4(), + "create", + None, + &[["assignee", &agent_hex]], + now(), + )) + .await, + "assignee-agent", + &[&agent_hex], + ); + refused( + f.save(&revision( + &agent, + f.child, + Uuid::new_v4(), + "create", + None, + &[], + now(), + )) + .await, + "signer-agent", + &[&agent_hex], + ); +} + +/// The creator is the creating signer and never changes, through moves and +/// a delete and restore, even after retention expires the earlier payloads. +/// A refusal names the creator to resend with. +/// Mutation: skip the create check, skip the keep check, or let a later +/// revision rewrite the head's creator → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn the_creator_is_the_signer_and_never_changes() { + let f = Fixture::new("creator").await; + let owner = f.owner.public_key().to_hex(); + let member = f.member.public_key().to_hex(); + let id = Uuid::new_v4(); + + refused( + f.save(&revision( + &f.owner, + f.child, + id, + "create", + None, + &[["creator", &member]], + now(), + )) + .await, + "creator-not-signer", + &[&member], + ); + let create = revision( + &f.owner, + f.child, + id, + "create", + None, + &[["creator", &owner]], + now(), + ); + f.save(&create).await.expect("the signer creates"); + for creator in [None, Some(member.as_str())] { + let tags: Vec<[&str; 2]> = creator.map(|c| ["creator", c]).into_iter().collect(); + refused( + f.save(&revision( + &f.member, + f.child, + id, + "update", + Some(&create), + &tags, + now(), + )) + .await, + "creator-changed", + &[&owner], + ); + } + let edit = revision( + &f.member, + f.child, + id, + "update", + Some(&create), + &[["creator", &owner]], + now(), + ); + f.save(&edit) + .await + .expect("another editor keeps the creator"); + let moved = revision( + &f.owner, + f.project, + id, + "move", + Some(&edit), + &[["creator", &owner]], + now(), + ); + f.save(&moved).await.expect("a move keeps the creator"); + let deleted = revision(&f.owner, f.project, id, "delete", Some(&moved), &[], now()); + f.save(&deleted).await.expect("a delete carries no creator"); + for expired in [&create, &edit, &moved] { + f.expire(expired).await; + } + refused( + f.save(&revision( + &f.owner, + f.project, + id, + "restore", + Some(&deleted), + &[], + now(), + )) + .await, + "creator-changed", + &[&owner], + ); + f.save(&revision( + &f.owner, + f.project, + id, + "restore", + Some(&deleted), + &[["creator", &owner]], + now(), + )) + .await + .expect("a restore keeps the creator from before the delete"); + + // Without a creator at create, none can be added later. + let plain = Uuid::new_v4(); + let create = revision(&f.owner, f.child, plain, "create", None, &[], now()); + f.save(&create).await.expect("no creator"); + refused( + f.save(&revision( + &f.owner, + f.child, + plain, + "update", + Some(&create), + &[["creator", &owner]], + now(), + )) + .await, + "creator-changed", + &["none"], + ); +} + +/// A task saved before the relay kept its creator and assignees gets them +/// on its next save: the creator from its first save's signer, else the +/// current revision's tag, else none, which nobody can claim later; the +/// assignees from its current revision, so an edit isn't held to someone +/// who lost access since. It never becomes uneditable. +/// Mutation: treat unknown assignees as nobody assigned, take the current +/// tag over the first signer, or let an edit set an unknown creator → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn a_task_saved_before_0096_stays_editable() { + let f = Fixture::new("before-0096").await; + let owner = f.owner.public_key().to_hex(); + let member = f.member.public_key().to_hex(); + + // Its assignee lost access; a title edit is still accepted. + let id = Uuid::new_v4(); + let create = revision( + &f.owner, + f.grandchild, + id, + "create", + None, + &[["creator", &owner], ["assignee", &member]], + now(), + ); + f.save(&create).await.expect("create"); + f.as_before_0096(id).await; + f.remove_from_project(&f.member).await; + f.save(&revision( + &f.owner, + f.grandchild, + id, + "update", + Some(&create), + &[["creator", &owner], ["assignee", &member]], + now(), + )) + .await + .expect("a title edit keeps the assignee who lost access"); + assert_eq!( + f.head(id).await, + (Some(owner.clone()), Some(vec![member.clone()])) + ); + + // The first save's signer outranks a current tag; the refusal names it. + let id = Uuid::new_v4(); + let editor = Keys::generate(); + add(&f.state, &f.tenant, &f.owner, f.child, &editor, "member").await; + let create = revision(&f.owner, f.child, id, "create", None, &[], now()); + f.save(&create).await.expect("create without a tag"); + let edit = revision(&editor, f.child, id, "update", Some(&create), &[], now()); + f.save(&edit).await.expect("an edit by someone else"); + f.as_before_0096(id).await; + // Before the relay checked it, a stored tag could name anyone. + sqlx::query("UPDATE events SET tags = tags || jsonb_build_array(jsonb_build_array('creator', $3::text)) WHERE community_id=$1 AND id=$2") + .bind(f.tenant.community().as_uuid()) + .bind(edit.id.as_bytes().as_slice()) + .bind(&member) + .execute(f.state.db.pool()) + .await + .expect("an unverified tag"); + for tags in [vec![], vec![["creator", member.as_str()]]] { + refused( + f.save(&revision( + &f.owner, + f.child, + id, + "update", + Some(&edit), + &tags, + now(), + )) + .await, + "creator-changed", + &[&owner], + ); + } + f.save(&revision( + &f.owner, + f.child, + id, + "update", + Some(&edit), + &[["creator", &owner]], + now(), + )) + .await + .expect("resent with the named creator"); + + // First save gone: the current revision's tag. + let id = Uuid::new_v4(); + let create = revision( + &f.owner, + f.project, + id, + "create", + None, + &[["creator", &owner]], + now(), + ); + f.save(&create).await.expect("create"); + let edit = revision( + &f.owner, + f.project, + id, + "update", + Some(&create), + &[["creator", &owner]], + now(), + ); + f.save(&edit).await.expect("edit"); + f.as_before_0096(id).await; + f.expire(&create).await; + refused( + f.save(&revision( + &f.owner, + f.project, + id, + "update", + Some(&edit), + &[["creator", &member]], + now(), + )) + .await, + "creator-changed", + &[&owner], + ); + f.save(&revision( + &f.owner, + f.project, + id, + "update", + Some(&edit), + &[["creator", &owner]], + now(), + )) + .await + .expect("the current revision's creator"); + + // Neither on hand: no creator, and nobody can claim one. + let id = Uuid::new_v4(); + let create = revision(&f.owner, f.child, id, "create", None, &[], now()); + f.save(&create).await.expect("create"); + f.as_before_0096(id).await; + f.expire(&create).await; + refused( + f.save(&revision( + &f.owner, + f.child, + id, + "update", + Some(&create), + &[["creator", &owner]], + now(), + )) + .await, + "creator-changed", + &["none"], + ); + f.save(&revision( + &f.owner, + f.child, + id, + "update", + Some(&create), + &[], + now(), + )) + .await + .expect("an edit without a creator"); + assert_eq!(f.head(id).await, (None, Some(vec![]))); +} + +/// Find reads current tasks by assignee and status, finds the ones nobody +/// has, covers a project's whole tree with `within`, and pages newest +/// first with `until`, all inside what the reader may read. +/// Mutation: drop the `unassigned` clause, drop the grandchild level from +/// `within`, keep the received order under `until`, or let an incremental +/// read take them → RED. +#[tokio::test] +#[ignore = "requires Postgres and Redis"] +async fn find_reads_unassigned_tasks_within_a_project_page_by_page() { + let f = Fixture::new("find").await; + let member = f.member.public_key().to_hex(); + let t = now(); + let mut ids = Vec::new(); + // Saved newest first, so the received order is the reverse of + // `created_at` order. + for (home, at, extra) in [ + (f.elsewhere, t - 10, vec![["status", "todo"]]), + (f.project, t - 20, vec![["status", "done"]]), + (f.grandchild, t - 30, vec![["status", "in_progress"]]), + ( + f.child, + t - 40, + vec![["status", "todo"], ["assignee", member.as_str()]], + ), + ] { + let id = Uuid::new_v4(); + f.save(&revision(&f.owner, home, id, "create", None, &extra, at)) + .await + .expect("create"); + ids.push(id.to_string()); + } + let [elsewhere, done, open, assigned] = <[String; 4]>::try_from(ids).unwrap(); + let open_statuses = json!(["todo", "in_progress"]); + + assert_eq!( + f.find( + &f.member, + json!({"artifact":"current","#type":["buzz.task"],"#assignee":[member]}) + ) + .await, + vec![assigned.clone()], + ); + assert_eq!( + f.find( + &f.member, + json!({"artifact":"current","#type":["buzz.task"],"#status":open_statuses,"unassigned":true}), + ) + .await, + vec![open.clone()], + "open and nobody has it, among what the member reads" + ); + assert_eq!( + f.find( + &f.owner, + json!({"artifact":"current","#status":open_statuses,"unassigned":true,"until":t}), + ) + .await, + vec![elsewhere.clone(), open.clone()], + ); + assert_eq!( + f.find( + &f.owner, + json!({"artifact":"current","within":f.project,"until":t}) + ) + .await, + vec![done.clone(), open.clone(), assigned.clone()], + "the project, its child and its grandchild, newest first" + ); + assert_eq!( + f.find( + &f.owner, + json!({"artifact":"current","within":f.child,"until":t}) + ) + .await, + vec![open.clone(), assigned.clone()], + ); + assert!(f + .find( + &Keys::generate(), + json!({"artifact":"current","within":f.project}) + ) + .await + .is_empty()); + + let page = + |until: u64| json!({"artifact":"current","within":f.project,"until":until,"limit":2}); + assert_eq!( + f.find(&f.owner, page(t)).await, + vec![done.clone(), open.clone()] + ); + // `until` is inclusive: the next page starts at the oldest one got. + assert_eq!( + f.find(&f.owner, page(t - 30)).await, + vec![open.clone(), assigned.clone()] + ); + assert_eq!(f.find(&f.owner, page(t - 31)).await, vec![assigned.clone()]); + assert!(f.find(&f.owner, page(t - 41)).await.is_empty()); + + // Incremental reads have no form of these filters, so they are refused + // there rather than ignored. + let plain = json!([{"artifact": "incremental", "query": {"artifact": "current", "#type": ["buzz.task"]}}]); + let (status, response) = query(&f.state, &f.tenant, &f.owner, &plain, true).await; + assert!(status.is_success(), "{status}: {response}"); + for extra in [ + json!({"unassigned": true}), + json!({"within": f.project}), + json!({"until": t}), + ] { + let mut inner = json!({"artifact": "current", "#type": ["buzz.task"]}); + inner + .as_object_mut() + .unwrap() + .extend(extra.as_object().unwrap().clone()); + let body = json!([{"artifact": "incremental", "query": inner}]); + let (status, response) = query(&f.state, &f.tenant, &f.owner, &body, true).await; + assert_eq!( + status, + axum::http::StatusCode::BAD_REQUEST, + "{extra}: {response}" + ); + } +} diff --git a/crates/buzz-relay/src/handlers/channel_access.rs b/crates/buzz-relay/src/handlers/channel_access.rs index 52d246f08fc..db9f365f0ba 100644 --- a/crates/buzz-relay/src/handlers/channel_access.rs +++ b/crates/buzz-relay/src/handlers/channel_access.rs @@ -146,6 +146,19 @@ fn role_name(role: MemberRole) -> &'static str { } } +/// Whether `pubkey` can read `channel_id`, by the rule the answer leaves +/// unreadable channels out with. +pub(crate) async fn can_read( + state: &AppState, + community_id: CommunityId, + pubkey: &[u8], + channel_id: Uuid, +) -> Result { + Ok(readable(state, community_id, pubkey, channel_id) + .await? + .is_some()) +} + /// `pubkey`'s access to `channel_id` under their community `restriction`; /// `None` when they cannot read it, whether it is private, deleted or missing. async fn access( @@ -155,16 +168,8 @@ async fn access( channel_id: Uuid, restriction: Restriction, ) -> Result, buzz_db::DbError> { - let channel = match state - .db - .get_channel_for_event_write(community_id, channel_id) - .await - { - Ok(channel) if channel.deleted_at.is_none() => channel, - Ok(_) | Err(buzz_db::DbError::ChannelNotFound(_)) => return Ok(None), - Err(e) => return Err(e), - }; - let Some((role, joined)) = acting_role(state, community_id, &channel, pubkey).await? else { + let Some((channel, role, joined)) = readable(state, community_id, pubkey, channel_id).await? + else { return Ok(None); }; let post = role.can_post() @@ -181,6 +186,29 @@ async fn access( })) } +/// A live channel `pubkey` can read, with the role they act with and +/// whether it is their own row's; `None` when it is private to them, +/// deleted or missing. +async fn readable( + state: &AppState, + community_id: CommunityId, + pubkey: &[u8], + channel_id: Uuid, +) -> Result, buzz_db::DbError> { + let channel = match state + .db + .get_channel_for_event_write(community_id, channel_id) + .await + { + Ok(channel) if channel.deleted_at.is_none() => channel, + Ok(_) | Err(buzz_db::DbError::ChannelNotFound(_)) => return Ok(None), + Err(e) => return Err(e), + }; + Ok(acting_role(state, community_id, &channel, pubkey) + .await? + .map(|(role, joined)| (channel, role, joined))) +} + /// The role `pubkey` acts with in `channel` and whether it is their own /// row's, or `None` when they cannot read it. Mirrors /// [`super::ingest::may_post`]: an active row's role, else an open channel's diff --git a/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs b/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs index 83383a7a008..71d29830737 100644 --- a/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs +++ b/crates/buzz-relay/src/handlers/channel_access_postgres_tests.rs @@ -38,7 +38,7 @@ async fn ask_with( /// `POST /query` with `body`, signed by `viewer`, with a payload tag unless /// `payload` is false. -async fn query( +pub(crate) async fn query( state: &Arc, tenant: &TenantContext, viewer: &Keys, diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index 3c7accb85be..809f5ad0ea7 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -7321,7 +7321,14 @@ mod postgres_tests { let env = buzz_core::artifact::validate(&create).expect("valid create"); healthy .db - .accept_artifact(community, &create, &env, None, &healthy.relay_keypair) + .accept_artifact( + community, + &create, + &env, + None, + &Default::default(), + &healthy.relay_keypair, + ) .await .map_err(db_err)?; diff --git a/crates/buzz-relay/src/handlers/mod.rs b/crates/buzz-relay/src/handlers/mod.rs index 78606f6b36e..4c2aa828739 100644 --- a/crates/buzz-relay/src/handlers/mod.rs +++ b/crates/buzz-relay/src/handlers/mod.rs @@ -2,6 +2,8 @@ pub mod admin_action_worker; pub mod admin_outbox_worker; #[cfg(test)] +mod artifact_assignee_postgres_tests; +#[cfg(test)] pub(crate) mod artifact_conversation_postgres_tests; /// NIP-AR Sync subscriptions. pub mod artifact_sync; diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index 76f4796326d..997453fe842 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -283,6 +283,7 @@ impl RelayInfo { // kind:20005 one timed-out pubkey, to ask again (NOSTR.md, // Channel access). "buzz-channel-access".to_string(), + "buzz-artifact-assignees".to_string(), ]; let gif = gif_provider.map(|provider| { supported_extensions.push("buzz-gif".to_string()); @@ -856,6 +857,7 @@ mod tests { assert!(extensions.contains(&"buzz-channel-parent-access".to_string())); assert!(extensions.contains(&"buzz-artifact-conversations".to_string())); assert!(extensions.contains(&"buzz-channel-access".to_string())); + assert!(extensions.contains(&"buzz-artifact-assignees".to_string())); } /// NIP-WP → NIP-11 mirror: a set workspace icon is served in the standard diff --git a/docs/nips/NIP-AR.md b/docs/nips/NIP-AR.md index 075c31e4e66..c6596a4e86f 100644 --- a/docs/nips/NIP-AR.md +++ b/docs/nips/NIP-AR.md @@ -31,7 +31,7 @@ Each event contains a complete snapshot. For example, a task created directly in } ``` -The `assignee` and `project` tags and the payload are illustrative, not required fields; this NIP does not define a task schema. +The `project` tag and the payload are illustrative, not required fields; this NIP does not define a task schema. `assignee` and `creator` tags are optional, and when present the relay enforces them (see Assignees and creator). | Tag | Meaning | | --- | --- | @@ -62,6 +62,42 @@ A `create` whose `d` is already in use fails. When the sender cannot read the ex On creation or when changed from the previous accepted revision, `root` MUST identify an existing, undeleted conversation anchor in `h`. Later loss of that anchor does not prevent edits. Replies belong to that conversation, not to an artifact revision. +## Assignees and creator + +Two optional tags name people, and the relay holds them to rules so a reader can trust the current revision without its history. + +- **Assignee.** `["assignee", ]`, once per person, distinct, at most 4 per revision. Assignees are people. Assignees are checked when someone is assigned and when the artifact moves: + - On a `create`, `move` or `restore`, every assignee MUST be able to read the home that revision puts the artifact in, judged when the revision is accepted. + - On an `update`, only the assignees it adds, compared with the artifact's current state, are checked. Someone who lost access since being assigned doesn't block an unrelated edit, and can't read the artifact anyway. + - A move that would leave an assignee unable to read the destination is rejected, so the client saves it without them. + - A `delete` carries no assignees. +- **Creator.** `["creator", ]`, at most once. On `create` it MUST equal the revision's signer. Every later `update`, `move` and `restore` MUST carry the creator named on `create`: present and equal, or absent when the artifact was created without one. A `delete` carries none. +- **Signer.** An artifact revision is signed by a person. An agent acts through its owner's key and names itself in client-defined tags. Comments in the artifact's conversation are ordinary messages and may be signed by agents. + +The relay keeps the creator and the current assignees with the artifact's current state, so expiring or redacting earlier revisions does not change the rules. For an artifact saved before a relay kept them, the relay fills them on its next accepted revision: +- The creator is the signer of its first revision while that revision is still stored, else the current revision's `creator` tag, else unknown. +- An unknown creator stays unknown, and later revisions carry none. +- The assignees are the current revision's. + +The relay knows a key is an agent only when the key has presented an owner attestation (NIP-OA, or an agent assertion under NIP-FI). An agent that never did looks like a person to the relay, so clients keep their own rule as the first line. + +Values are 64 lowercase hex characters. A malformed, repeated or extra tag rejects the envelope. + +### Reason codes + +A rejected revision's `OK` message reads `invalid: : — `. `` is a comma-separated list of lowercase hex pubkeys, `none`, or empty. Clients match on ``; `` is for people and may change. + +| Code | Keys | Meaning | +| --- | --- | --- | +| `assignee-unreadable` | The assignees that failed | They can't read the home, on a create, move or restore, or when an update adds them. | +| `assignee-agent` | The assignees that failed | They are known agents. | +| `too-many-assignees` | empty | More than 4 assignees. | +| `signer-agent` | The signer | A known agent signed the revision. | +| `creator-not-signer` | The claimed creator | A `create` names someone else as creator. | +| `creator-changed` | The stored creator, or `none` | A later revision's creator differs. Resend with the named creator, or with none. | + +Relays that enforce these rules and support the `unassigned`, `within` and `until` query keys advertise `buzz-artifact-assignees` in NIP-11 `supported_extensions`. + ## Access Channel read permission governs every artifact read, including lookups, history, search, previews, counts, and live updates. Threads inherit their channel's audience. Membership and visibility changes take effect on subsequent reads and deliveries. @@ -97,6 +133,14 @@ An artifact's current state is its latest accepted revision, as determined by th Relays MUST support querying current artifacts across channels the reader can access using exact tag-name/value matches, including multi-character tag names. Conditions on different tag names are combined with AND; requested values for one name are combined with OR. A match compares the tag name and its first value in the same tag. Access checks and tag matching apply before pagination and any counts. Older revisions do not contribute matches. +Current-state queries also accept these keys, combined with the tag conditions by AND: + +- `"unassigned": true` matches only artifacts with no `assignee` tag. It cannot be combined with `#assignee`. +- `"within": ` matches artifacts whose home is that channel or a channel filed under it, down to its grandchildren, as far as the reader may read each one. A project search covers the project's whole tree this way. +- `"until": ` matches revisions with `created_at` at or before it, and orders the page by `created_at`, newest first. The next page asks `until` the oldest `created_at` it received and skips artifacts it already has. + +`history` and `head` reads refuse `unassigned` and `within`, and incremental reads refuse all three. + Relays MUST advertise and enforce limits on tag-name/value sizes, total tag bytes, query predicates and values, and page size. Queries MUST run within an enforced execution budget. Unsupported or over-limit requests fail explicitly; predicates MUST NOT be silently ignored or incomplete results presented as complete. Artifact revisions are state changes, not conversation messages. Receiving one MUST NOT increase chat or reply counts, add a chat unread, mark a conversation read, or repeat mention or push notifications for tags carried over from the previous revision. diff --git a/migrations/0096_artifact_head_creator.sql b/migrations/0096_artifact_head_creator.sql new file mode 100644 index 00000000000..120d2bef9b3 --- /dev/null +++ b/migrations/0096_artifact_head_creator.sql @@ -0,0 +1,18 @@ +-- Artifact creator and assignees on the head (NIP-AR, Assignees and +-- creator). The head outlives event retention and redaction, so the relay +-- checks later revisions against it rather than against earlier payloads. +-- +-- `creator` is the pubkey a `creator` tag named on create; it never changes. +-- `assignees` is the current revision's assignees, so a revision is checked +-- only for the people it adds. +-- +-- Both are NULL for artifacts saved before this change: not yet known, which +-- is distinct from an empty assignee list. The relay fills them on the +-- artifact's next save, inside its lock (migrations carry no backfills). +-- +-- Additive and nullable, so no rewrite, under bounded locks. +SET LOCAL lock_timeout = '1s'; +SET LOCAL statement_timeout = '5s'; + +ALTER TABLE artifact_heads ADD COLUMN IF NOT EXISTS creator TEXT; +ALTER TABLE artifact_heads ADD COLUMN IF NOT EXISTS assignees TEXT[]; diff --git a/schema/tables/public/artifact_heads.sql b/schema/tables/public/artifact_heads.sql index 7e73557b9b6..06162ba25c6 100644 --- a/schema/tables/public/artifact_heads.sql +++ b/schema/tables/public/artifact_heads.sql @@ -7,6 +7,8 @@ CREATE TABLE artifact_heads ( artifact_type TEXT NOT NULL, root BYTEA, deleted BOOLEAN NOT NULL DEFAULT false, + creator TEXT, + assignees TEXT[], modified_at TIMESTAMPTZ NOT NULL DEFAULT clock_timestamp(), PRIMARY KEY (community_id, artifact_id) );