mirror of
https://github.com/block/buzz.git
synced 2026-11-28 12:12:04 +00:00
🤖 ## Summary After part 1, a system channel is still returned by every query that returns ordinary channels, so existing clients would show it as a chat. This PR makes the relay leave system channels out of every read that does not name them. Clients do not need to filter, so clients that know nothing about system channels stay correct. | Query | Before | After | |---|---|---| | A query that does not name a channel (no `#h`), COUNT, full-text search, the HTTP `/query` and `/count` routes, artifact queries (`{"artifact": ...}`), the sidebar | Includes system channels | Leaves them out | | "Channels I belong to" (kind:39002 `#p:[me]`) | Includes them | Leaves them out | | A filter that names the channel with `#h`, or with `#d` on kinds 39000–39003 | Ordinary read rules | Unchanged: members can read it, and anyone can read it if it is open | Push notifications and "you were added to a channel" notifications (kinds 44100/44101) skip system channels, because a client that received one would show the channel. A client that is given a system channel's ID, for example in a pasted link, can still open it. Naming the ID is the opt-in. This keeps system channels ordinary NIP-29 groups. Part 2 of 3, stacked on part 1. ### Related issue None found. ### Details - The rule lives in one place: `get_accessible_channel_ids`, the set of channels a query may read when it does not name one. It is the union of the reader's memberships and every open channel; both halves now exclude `channel_type = 'system'`. Because the filter is in SQL before `LIMIT`, pages stay full. - A filter that names a system channel adds it to that filter's scope only (`handlers/system_channels.rs`). A sibling filter in the same request keeps the implicit set, so naming one system channel cannot widen another filter. - Thread windows and the workflows API name their channel, so they follow the same named-channel rule. - Artifact queries have their own read check in SQL. It reads a system channel only when the query's `#h` names it. - When a request re-checks membership for a named channel that its first lookup missed, a confirmed system channel joins only the filters that name it. Before, a reader who joined a system channel during the request could have it added to a sibling filter's scope. - The system-channel lookup runs only when a filter names a channel outside the implicit set, so ordinary queries do not pay for it. - **Spec.** NIP-CL lists the reads that leave system channels out, and says when a filter names one. `AGENTS.md` notes this for `get_channels`. ### Testing - End-to-end relay test (Postgres and Redis) with a private system channel, an open system channel and an ordinary channel, as a member and as a non-member: REQ without `#h`, NIP-50 search, COUNT, HTTP `/query`, HTTP search, HTTP `/count`, the channel list, and 39002 `#p:[me]` return only the ordinary channel. Named reads by `#h` and `#d` follow member-or-open on REQ, COUNT, search and HTTP. - Relay test: adding a member to a system channel sends no kind:44100; an ordinary channel still does. - Both tests fail when the SQL exclusion or the named-channel scope is removed. - Database test: an artifact in an open system channel is missing from `{"artifact":"current"}` and present with `#h:[<system channel>]`, for a member and a non-member. It fails without the channel-type condition. - Relay test: the membership re-check confirms a system channel that the system-channel lookup missed. The channel goes to the filter that names it, and a sibling filter's scope does not include it. It fails without the fix. - Unit tests for the per-filter scope. They now run in `just test-unit` and `scripts/run-tests.sh`. ### Stack These are two stacks. Merge them in this order. Client support (creating, labeling and finding these channels) will be in block/buzz-app, not the buzz SDK and CLI. **Stack 1: channel labels and creator lookup (#8174–#8176)** 1. #8174 channel type and creator tags, and the channel creation time 2. #8175 channel labels 3. #8176 database-side label and creator match, and the rule for choosing one channel **Stack 2: system channels (#8180–#8182)**, stacked on stack 1 because it uses labels and the creator tag 4. #8180 the system channel type 5. #8181 leave system channels out of reads that do not name them ← this PR 6. #8182 channel-state filters opt in to system channels --------- Signed-off-by: Logan Johnson <loganj@squareup.com> Co-authored-by: Larry <627498bd4bd1f281a16431e3c6cce3b5c25b6692798c78672298aefbf2f8f8b5@buzz.block.builderlab.xyz>
582 lines
20 KiB
Rust
582 lines
20 KiB
Rust
//! PostgreSQL regression tests for the production artifact transaction/query seams.
|
|
use super::artifact::ArtifactOutcome;
|
|
use crate::Db;
|
|
use buzz_core::{artifact, CommunityId};
|
|
use nostr::{Event, EventBuilder, Keys, Kind, Tag};
|
|
use sqlx::PgPool;
|
|
use uuid::Uuid;
|
|
|
|
struct Fixture {
|
|
db: Db,
|
|
community: CommunityId,
|
|
a: Uuid,
|
|
b: Uuid,
|
|
owner: Keys,
|
|
peer: Keys,
|
|
relay: Keys,
|
|
}
|
|
impl Fixture {
|
|
async fn new() -> Self {
|
|
let pool = PgPool::connect(&crate::test_support::database_url())
|
|
.await
|
|
.unwrap();
|
|
if std::env::var("BUZZ_TEST_SCHEMA_MODE").as_deref() != Ok("desired") {
|
|
crate::migration::run_migrations(&pool).await.unwrap();
|
|
}
|
|
let db = Db::from_pool(pool);
|
|
db.maintain_partitions(
|
|
1,
|
|
crate::partition::PartitionMaintenancePolicy {
|
|
create_enabled: true,
|
|
advance_enabled: false,
|
|
},
|
|
)
|
|
.await
|
|
.unwrap();
|
|
let community = CommunityId::from_uuid(Uuid::new_v4());
|
|
sqlx::query("INSERT INTO communities(id,host) VALUES($1,$2)")
|
|
.bind(community.as_uuid())
|
|
.bind(format!("artifact-{}.test", community.as_uuid()))
|
|
.execute(&db.pool)
|
|
.await
|
|
.unwrap();
|
|
let owner = Keys::generate();
|
|
let peer = Keys::generate();
|
|
let a = Uuid::new_v4();
|
|
let b = Uuid::new_v4();
|
|
for (id, visibility) in [(a, "open"), (b, "private")] {
|
|
sqlx::query("INSERT INTO channels(community_id,id,name,visibility,channel_type,created_by) VALUES($1,$2,$3,$4::channel_visibility,'stream',$5)")
|
|
.bind(community.as_uuid()).bind(id).bind(id.to_string()).bind(visibility).bind(owner.public_key().to_bytes().as_slice()).execute(&db.pool).await.unwrap();
|
|
sqlx::query("INSERT INTO channel_members(community_id,channel_id,pubkey,role) VALUES($1,$2,$3,'owner')")
|
|
.bind(community.as_uuid()).bind(id).bind(owner.public_key().to_bytes().as_slice()).execute(&db.pool).await.unwrap();
|
|
}
|
|
Self {
|
|
db,
|
|
community,
|
|
a,
|
|
b,
|
|
owner,
|
|
peer,
|
|
relay: Keys::generate(),
|
|
}
|
|
}
|
|
fn revision(
|
|
&self,
|
|
d: Uuid,
|
|
op: &str,
|
|
home: Uuid,
|
|
prev: Option<&Event>,
|
|
key: &Keys,
|
|
extra: Vec<Vec<String>>,
|
|
) -> Event {
|
|
let mut tags = vec![
|
|
vec!["ar".into(), "1".into()],
|
|
vec!["d".into(), d.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(), "Test".into()]);
|
|
}
|
|
if let Some(e) = prev {
|
|
tags.push(vec!["prev".into(), e.id.to_hex()]);
|
|
}
|
|
tags.extend(extra);
|
|
EventBuilder::new(
|
|
Kind::Custom(45010),
|
|
if op == "delete" { "" } else { "secret" },
|
|
)
|
|
.tags(tags.into_iter().map(|t| Tag::parse(t).unwrap()))
|
|
.sign_with_keys(key)
|
|
.unwrap()
|
|
}
|
|
async fn accept(&self, e: &Event, source: Option<Uuid>) -> ArtifactOutcome {
|
|
let env = artifact::validate(e).unwrap();
|
|
self.db
|
|
.accept_artifact(self.community, e, &env, source, &self.relay)
|
|
.await
|
|
.unwrap()
|
|
}
|
|
async fn count(&self, key: &Keys, value: serde_json::Value) -> i64 {
|
|
self.query(key, value, true).await.1
|
|
}
|
|
async fn query(
|
|
&self,
|
|
key: &Keys,
|
|
value: serde_json::Value,
|
|
count: bool,
|
|
) -> (Vec<buzz_core::StoredEvent>, i64) {
|
|
self.db
|
|
.query_artifacts(
|
|
self.community,
|
|
key.public_key().as_bytes(),
|
|
&artifact::parse_query(&value).unwrap(),
|
|
count,
|
|
)
|
|
.await
|
|
.unwrap()
|
|
}
|
|
}
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn lifecycle_cas_queries_move_redaction_and_retention() {
|
|
let f = Fixture::new().await;
|
|
let d = Uuid::new_v4();
|
|
let project = |v: &str| vec![vec!["project".to_string(), v.to_string()]];
|
|
let create = f.revision(d, "create", f.a, None, &f.owner, project("A"));
|
|
assert!(matches!(
|
|
f.accept(&create, None).await,
|
|
ArtifactOutcome::Accepted(_)
|
|
));
|
|
let x = f.revision(d, "update", f.a, Some(&create), &f.owner, project("B"));
|
|
let y = f.revision(d, "update", f.a, Some(&create), &f.peer, project("B"));
|
|
let (rx, ry) = tokio::join!(f.accept(&x, None), f.accept(&y, None));
|
|
let head = match (rx, ry) {
|
|
(ArtifactOutcome::Accepted(_), ArtifactOutcome::Conflict(..)) => &x,
|
|
(ArtifactOutcome::Conflict(..), ArtifactOutcome::Accepted(_)) => &y,
|
|
other => panic!("exactly one CAS winner: {other:?}"),
|
|
};
|
|
assert!(matches!(
|
|
f.accept(&create, None).await,
|
|
ArtifactOutcome::Duplicate
|
|
));
|
|
let current = |p: &str| serde_json::json!({"artifact":"current","#d":[d],"#project":[p]});
|
|
assert_eq!(f.count(&f.owner, current("A")).await, 0);
|
|
assert_eq!(f.count(&f.owner, current("B")).await, 1);
|
|
// First value in the same tag, never an annotation or reverse-name match.
|
|
let wrong = f.revision(
|
|
d,
|
|
"update",
|
|
f.a,
|
|
Some(head),
|
|
&f.owner,
|
|
vec![
|
|
vec!["project".into(), "C".into(), "B".into()],
|
|
vec!["B".into(), "project".into()],
|
|
],
|
|
);
|
|
assert!(matches!(
|
|
f.accept(&wrong, None).await,
|
|
ArtifactOutcome::Accepted(_)
|
|
));
|
|
assert_eq!(f.count(&f.owner, current("B")).await, 0);
|
|
|
|
// A move commits only against the source the relay authorized.
|
|
let moved = f.revision(d, "move", f.b, Some(&wrong), &f.owner, vec![]);
|
|
assert!(matches!(
|
|
f.accept(&moved, Some(f.b)).await,
|
|
ArtifactOutcome::Conflict(..)
|
|
));
|
|
let ArtifactOutcome::Accepted(stored) = f.accept(&moved, Some(f.a)).await else {
|
|
panic!("move accepted");
|
|
};
|
|
let removal = &stored[1];
|
|
assert_eq!(removal.event.kind.as_u16(), 45011);
|
|
assert_eq!(removal.channel_id, Some(f.a));
|
|
assert!(!serde_json::to_string(&removal.event)
|
|
.unwrap()
|
|
.contains(&f.b.to_string()));
|
|
let all = serde_json::json!({"artifact":"current","#d":[d]});
|
|
let history = serde_json::json!({"artifact":"history","#d":[d]});
|
|
assert_eq!(f.count(&f.peer, all.clone()).await, 0);
|
|
assert_eq!(f.count(&f.peer, history.clone()).await, 3);
|
|
assert_eq!(f.count(&f.owner, history.clone()).await, 4);
|
|
|
|
// Expiring an earlier payload keeps its identity reserved.
|
|
let retention = |id: nostr::EventId| {
|
|
sqlx::query("DELETE FROM events WHERE community_id=$1 AND id=$2")
|
|
.bind(f.community.as_uuid())
|
|
.bind(id.as_bytes().to_vec())
|
|
};
|
|
assert_eq!(
|
|
retention(create.id)
|
|
.execute(&f.db.pool)
|
|
.await
|
|
.unwrap()
|
|
.rows_affected(),
|
|
1
|
|
);
|
|
assert!(matches!(
|
|
f.accept(&create, None).await,
|
|
ArtifactOutcome::Duplicate
|
|
));
|
|
|
|
// Redaction is the generic soft delete: the head stays, its payload is hidden
|
|
// everywhere and may then be purged.
|
|
assert!(f
|
|
.db
|
|
.soft_delete_event_and_update_thread(f.community, moved.id.as_bytes(), None, None)
|
|
.await
|
|
.unwrap());
|
|
assert_eq!(f.count(&f.owner, all.clone()).await, 0);
|
|
assert_eq!(f.count(&f.owner, history.clone()).await, 2);
|
|
assert_eq!(
|
|
retention(moved.id)
|
|
.execute(&f.db.pool)
|
|
.await
|
|
.unwrap()
|
|
.rows_affected(),
|
|
1
|
|
);
|
|
assert!(f
|
|
.db
|
|
.soft_delete_event_and_update_thread(f.community, removal.event.id.as_bytes(), None, None)
|
|
.await
|
|
.is_err());
|
|
|
|
let deleted = f.revision(d, "delete", f.b, Some(&moved), &f.owner, vec![]);
|
|
assert!(matches!(
|
|
f.accept(&deleted, None).await,
|
|
ArtifactOutcome::Accepted(_)
|
|
));
|
|
assert_eq!(f.count(&f.owner, all.clone()).await, 0);
|
|
let update = f.revision(d, "update", f.b, Some(&deleted), &f.owner, vec![]);
|
|
assert!(matches!(
|
|
f.accept(&update, None).await,
|
|
ArtifactOutcome::Rejected(_)
|
|
));
|
|
let restore = f.revision(d, "restore", f.b, Some(&deleted), &f.peer, vec![]);
|
|
assert!(matches!(
|
|
f.accept(&restore, None).await,
|
|
ArtifactOutcome::Accepted(_)
|
|
));
|
|
assert_eq!(f.count(&f.owner, all.clone()).await, 1);
|
|
// Reads observe removed private membership.
|
|
sqlx::query(
|
|
"UPDATE channel_members SET removed_at=now() WHERE community_id=$1 AND channel_id=$2",
|
|
)
|
|
.bind(f.community.as_uuid())
|
|
.bind(f.b)
|
|
.execute(&f.db.pool)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(f.count(&f.owner, all).await, 0);
|
|
f.db.validate_deletion_serving_catalog().await.unwrap();
|
|
}
|
|
|
|
/// An artifact in a system channel is read only by a query whose `#h` names
|
|
/// that channel (NIP-CL), even when the channel is open.
|
|
/// Mutation: drop the `channel_type` condition from `query_artifacts` → RED.
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn system_channel_artifacts_are_read_only_by_name() {
|
|
let f = Fixture::new().await;
|
|
let system = Uuid::new_v4();
|
|
sqlx::query("INSERT INTO channels(community_id,id,name,visibility,channel_type,created_by) VALUES($1,$2,$3,'open','system',$4)")
|
|
.bind(f.community.as_uuid())
|
|
.bind(system)
|
|
.bind(system.to_string())
|
|
.bind(f.owner.public_key().to_bytes().as_slice())
|
|
.execute(&f.db.pool)
|
|
.await
|
|
.unwrap();
|
|
for home in [f.a, system] {
|
|
let create = f.revision(Uuid::new_v4(), "create", home, None, &f.owner, vec![]);
|
|
assert!(matches!(
|
|
f.accept(&create, None).await,
|
|
ArtifactOutcome::Accepted(_)
|
|
));
|
|
}
|
|
for reader in [&f.owner, &f.peer] {
|
|
let (events, _) = f
|
|
.query(reader, serde_json::json!({"artifact":"current"}), false)
|
|
.await;
|
|
let homes: Vec<_> = events.iter().map(|e| e.channel_id).collect();
|
|
assert_eq!(homes, [Some(f.a)], "no #h");
|
|
assert_eq!(
|
|
f.count(reader, serde_json::json!({"artifact":"current"}))
|
|
.await,
|
|
1
|
|
);
|
|
let named = serde_json::json!({"artifact":"current","#h":[system.to_string()]});
|
|
let (events, _) = f.query(reader, named.clone(), false).await;
|
|
let homes: Vec<_> = events.iter().map(|e| e.channel_id).collect();
|
|
assert_eq!(homes, [Some(system)], "#h names the system channel");
|
|
assert_eq!(f.count(reader, named).await, 1);
|
|
}
|
|
}
|
|
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn repeated_moves_get_distinct_source_safe_markers() {
|
|
let f = Fixture::new().await;
|
|
let d = Uuid::new_v4();
|
|
let create = f.revision(d, "create", f.a, None, &f.owner, vec![]);
|
|
let there = f.revision(d, "move", f.b, Some(&create), &f.owner, vec![]);
|
|
let back = f.revision(d, "move", f.a, Some(&there), &f.owner, vec![]);
|
|
let again = f.revision(d, "move", f.b, Some(&back), &f.owner, vec![]);
|
|
assert!(matches!(
|
|
f.accept(&create, None).await,
|
|
ArtifactOutcome::Accepted(_)
|
|
));
|
|
let mut markers = Vec::new();
|
|
for (event, source, replaced) in [
|
|
(&there, f.a, &create),
|
|
(&back, f.b, &there),
|
|
(&again, f.a, &back),
|
|
] {
|
|
let ArtifactOutcome::Accepted(stored) = f.accept(event, Some(source)).await else {
|
|
panic!("move accepted");
|
|
};
|
|
let marker = stored[1].event.clone();
|
|
// Only `prev` distinguishes same-second markers for one source.
|
|
let tags: Vec<_> = marker.tags.iter().map(|t| t.as_slice().to_vec()).collect();
|
|
assert_eq!(
|
|
tags,
|
|
[
|
|
vec!["ar".to_string(), "1".into()],
|
|
vec!["d".into(), d.to_string()],
|
|
vec!["h".into(), source.to_string()],
|
|
vec!["reason".into(), "moved".into()],
|
|
vec!["prev".into(), replaced.id.to_hex()],
|
|
]
|
|
);
|
|
markers.push(marker.id);
|
|
}
|
|
assert_ne!(markers[0], markers[2]);
|
|
}
|
|
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn root_anchor_and_tenant_boundaries() {
|
|
let f = Fixture::new().await;
|
|
let d = Uuid::new_v4();
|
|
let invalid = f.revision(
|
|
d,
|
|
"create",
|
|
f.a,
|
|
None,
|
|
&f.owner,
|
|
vec![vec!["root".into(), "a".repeat(64)]],
|
|
);
|
|
assert!(matches!(
|
|
f.accept(&invalid, None).await,
|
|
ArtifactOutcome::Rejected(_)
|
|
));
|
|
let anchor = EventBuilder::new(Kind::Custom(9), "anchor")
|
|
.tags([Tag::parse(["h", &f.a.to_string()]).unwrap()])
|
|
.sign_with_keys(&f.owner)
|
|
.unwrap();
|
|
f.db.insert_event(f.community, &anchor, Some(f.a))
|
|
.await
|
|
.unwrap();
|
|
let root = || vec![vec!["root".to_string(), anchor.id.to_hex()]];
|
|
let create = f.revision(d, "create", f.a, None, &f.owner, root());
|
|
assert!(matches!(
|
|
f.accept(&create, None).await,
|
|
ArtifactOutcome::Accepted(_)
|
|
));
|
|
// Later loss of the anchor does not block edits that keep it.
|
|
sqlx::query("UPDATE events SET deleted_at=now() WHERE community_id=$1 AND id=$2")
|
|
.bind(f.community.as_uuid())
|
|
.bind(anchor.id.as_bytes().as_slice())
|
|
.execute(&f.db.pool)
|
|
.await
|
|
.unwrap();
|
|
let update = f.revision(d, "update", f.a, Some(&create), &f.peer, root());
|
|
assert!(matches!(
|
|
f.accept(&update, None).await,
|
|
ArtifactOutcome::Accepted(_)
|
|
));
|
|
let bad_delete = f.revision(d, "delete", f.a, Some(&update), &f.owner, vec![]);
|
|
assert!(matches!(
|
|
f.accept(&bad_delete, None).await,
|
|
ArtifactOutcome::Rejected(_)
|
|
));
|
|
let other = Fixture::new().await;
|
|
assert!(!other
|
|
.db
|
|
.artifact_accepted(other.community, create.id.as_bytes())
|
|
.await
|
|
.unwrap());
|
|
let same_id = other.revision(d, "create", other.a, None, &other.owner, vec![]);
|
|
assert!(matches!(
|
|
other.accept(&same_id, None).await,
|
|
ArtifactOutcome::Accepted(_)
|
|
));
|
|
assert_eq!(
|
|
other
|
|
.count(
|
|
&other.owner,
|
|
serde_json::json!({"artifact":"history","#d":[d]})
|
|
)
|
|
.await,
|
|
1
|
|
);
|
|
}
|
|
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn concurrent_artifacts_on_ttl_channel_commit() {
|
|
let f = Fixture::new().await;
|
|
sqlx::query("UPDATE channels SET ttl_seconds=60 WHERE community_id=$1 AND id=$2")
|
|
.bind(f.community.as_uuid())
|
|
.bind(f.a)
|
|
.execute(&f.db.pool)
|
|
.await
|
|
.unwrap();
|
|
let a = f.revision(Uuid::new_v4(), "create", f.a, None, &f.owner, vec![]);
|
|
let b = f.revision(Uuid::new_v4(), "create", f.a, None, &f.peer, vec![]);
|
|
let (a, b) = tokio::join!(f.accept(&a, None), f.accept(&b, None));
|
|
assert!(matches!(a, ArtifactOutcome::Accepted(_)));
|
|
assert!(matches!(b, ArtifactOutcome::Accepted(_)));
|
|
let live: bool = sqlx::query_scalar(
|
|
"SELECT ttl_deadline>now() FROM channels WHERE community_id=$1 AND id=$2",
|
|
)
|
|
.bind(f.community.as_uuid())
|
|
.bind(f.a)
|
|
.fetch_one(&f.db.pool)
|
|
.await
|
|
.unwrap();
|
|
assert!(live);
|
|
}
|
|
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn quiescing_community_rejects_artifact_at_admission_before_coordinate_lock() {
|
|
let f = Fixture::new().await;
|
|
let d = Uuid::new_v4();
|
|
let create = f.revision(d, "create", f.a, None, &f.owner, vec![]);
|
|
let env = artifact::validate(&create).unwrap();
|
|
crate::test_support::quiesce_community_for_tests(&f.db.pool, f.community).await;
|
|
|
|
// Hold the artifact coordinate lock. Admission must reject before
|
|
// `accept_artifact` reaches it, so the write cannot queue behind it.
|
|
let mut holder = f.db.pool.begin().await.unwrap();
|
|
sqlx::query("SELECT pg_advisory_xact_lock(hashtextextended($1,0))")
|
|
.bind(format!("artifact:{}:{}", f.community.as_uuid(), env.id))
|
|
.execute(&mut *holder)
|
|
.await
|
|
.unwrap();
|
|
let error = tokio::time::timeout(
|
|
std::time::Duration::from_secs(5),
|
|
f.db.accept_artifact(f.community, &create, &env, None, &f.relay),
|
|
)
|
|
.await
|
|
.expect("admission must reject before waiting on the coordinate lock")
|
|
.expect_err("a quiescing community must reject artifact writes");
|
|
holder.rollback().await.unwrap();
|
|
assert!(
|
|
crate::test_support::is_admission_rejection(&error),
|
|
"expected entry admission rejection, got: {error:#}"
|
|
);
|
|
|
|
let persisted: (i64, i64) = sqlx::query_as(
|
|
"SELECT (SELECT count(*) FROM events WHERE community_id=$1 AND id=$2), \
|
|
(SELECT count(*) FROM artifact_heads WHERE community_id=$1 AND artifact_id=$3)",
|
|
)
|
|
.bind(f.community.as_uuid())
|
|
.bind(create.id.as_bytes().as_slice())
|
|
.bind(env.id)
|
|
.fetch_one(&f.db.pool)
|
|
.await
|
|
.unwrap();
|
|
assert_eq!(
|
|
persisted,
|
|
(0, 0),
|
|
"a rejected artifact must persist nothing"
|
|
);
|
|
}
|
|
|
|
/// A non-create revision whose head lives outside the channel the caller
|
|
/// authorized answers exactly like a missing artifact, before the revision,
|
|
/// type, deleted and root checks could describe the head.
|
|
#[tokio::test]
|
|
#[ignore = "requires Postgres"]
|
|
async fn head_outside_authorized_channel_matches_missing_head() {
|
|
let f = Fixture::new().await;
|
|
let d = Uuid::new_v4();
|
|
let create = f.revision(d, "create", f.a, None, &f.owner, vec![]);
|
|
assert!(matches!(
|
|
f.accept(&create, None).await,
|
|
ArtifactOutcome::Accepted(_)
|
|
));
|
|
let gone = Uuid::new_v4();
|
|
let deleted_d = Uuid::new_v4();
|
|
let deleted_create = f.revision(deleted_d, "create", f.a, None, &f.owner, vec![]);
|
|
assert!(matches!(
|
|
f.accept(&deleted_create, None).await,
|
|
ArtifactOutcome::Accepted(_)
|
|
));
|
|
let deleted = f.revision(
|
|
deleted_d,
|
|
"delete",
|
|
f.a,
|
|
Some(&deleted_create),
|
|
&f.owner,
|
|
vec![],
|
|
);
|
|
assert!(matches!(
|
|
f.accept(&deleted, None).await,
|
|
ArtifactOutcome::Accepted(_)
|
|
));
|
|
let retyped = {
|
|
let mut tags: Vec<Vec<String>> = vec![
|
|
vec!["ar".into(), "1".into()],
|
|
vec!["d".into(), d.to_string()],
|
|
vec!["h".into(), f.b.to_string()],
|
|
vec!["type".into(), "buzz.note".into()],
|
|
vec!["op".into(), "update".into()],
|
|
vec!["title".into(), "Test".into()],
|
|
];
|
|
tags.push(vec!["prev".into(), create.id.to_hex()]);
|
|
EventBuilder::new(Kind::Custom(45010), "secret")
|
|
.tags(tags.into_iter().map(|t| Tag::parse(t).unwrap()))
|
|
.sign_with_keys(&f.peer)
|
|
.unwrap()
|
|
};
|
|
let cases = [
|
|
(
|
|
"missing",
|
|
f.revision(gone, "update", f.b, Some(&create), &f.peer, vec![]),
|
|
None,
|
|
),
|
|
(
|
|
"current prev",
|
|
f.revision(d, "update", f.b, Some(&create), &f.peer, vec![]),
|
|
None,
|
|
),
|
|
(
|
|
"stale prev",
|
|
f.revision(d, "update", f.b, Some(&deleted), &f.peer, vec![]),
|
|
None,
|
|
),
|
|
("other type", retyped, None),
|
|
(
|
|
"delete",
|
|
f.revision(d, "delete", f.b, Some(&create), &f.peer, vec![]),
|
|
None,
|
|
),
|
|
(
|
|
"restore deleted",
|
|
f.revision(deleted_d, "restore", f.b, Some(&deleted), &f.peer, vec![]),
|
|
None,
|
|
),
|
|
(
|
|
"update deleted",
|
|
f.revision(deleted_d, "update", f.b, Some(&deleted), &f.peer, vec![]),
|
|
None,
|
|
),
|
|
(
|
|
"move from unauthorized source",
|
|
f.revision(d, "move", f.b, Some(&create), &f.peer, vec![]),
|
|
Some(f.b),
|
|
),
|
|
];
|
|
for (case, event, source) in cases {
|
|
match f.accept(&event, source).await {
|
|
ArtifactOutcome::Conflict(reason) => {
|
|
assert_eq!(reason, super::artifact::HEAD_UNAVAILABLE, "{case}")
|
|
}
|
|
other => panic!("{case}: {other:?}"),
|
|
}
|
|
}
|
|
// Positive control: the same revision homed where the head lives.
|
|
let update = f.revision(d, "update", f.a, Some(&create), &f.peer, vec![]);
|
|
assert!(matches!(
|
|
f.accept(&update, None).await,
|
|
ArtifactOutcome::Accepted(_)
|
|
));
|
|
}
|