Skip to content

Commit 409ca53

Browse files
Duncanwpfleger96
andcommitted
test(relay): cover artifact-move source lookup failure
Moves the restricted-role setup into shared helpers used by both lookup-failure regressions. Co-authored-by: Will Pfleger <[email protected]> Signed-off-by: Will Pfleger <[email protected]>
1 parent f2dfa44 commit 409ca53

1 file changed

Lines changed: 156 additions & 38 deletions

File tree

‎crates/buzz-relay/src/handlers/ingest.rs‎

Lines changed: 156 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -6267,6 +6267,55 @@ mod postgres_tests {
62676267
Arc::new(state)
62686268
}
62696269

6270+
async fn role_sql(admin: &sqlx::PgPool, q: String) -> Result<(), sqlx::Error> {
6271+
sqlx::query(sqlx::AssertSqlSafe(q))
6272+
.execute(admin)
6273+
.await
6274+
.map(|_| ())
6275+
}
6276+
6277+
async fn create_role(admin: &sqlx::PgPool, role: &str) -> Result<(), sqlx::Error> {
6278+
role_sql(admin, format!("CREATE ROLE {role} NOLOGIN")).await
6279+
}
6280+
6281+
async fn drop_role(admin: &sqlx::PgPool, role: &str) -> Result<(), sqlx::Error> {
6282+
role_sql(admin, format!("DROP OWNED BY {role}")).await?;
6283+
role_sql(admin, format!("DROP ROLE {role}")).await
6284+
}
6285+
6286+
/// A pool whose connections run as `role`, which can do everything ingest
6287+
/// needs except `SELECT` on `channels`.
6288+
async fn channel_blind_pool(
6289+
admin: &sqlx::PgPool,
6290+
db_url: &str,
6291+
role: &str,
6292+
) -> Result<sqlx::PgPool, sqlx::Error> {
6293+
for q in [
6294+
format!("GRANT USAGE ON SCHEMA public TO {role}"),
6295+
format!(
6296+
"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {role}"
6297+
),
6298+
format!("GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO {role}"),
6299+
format!("REVOKE SELECT ON channels FROM {role}"),
6300+
format!("GRANT {role} TO CURRENT_USER"),
6301+
] {
6302+
role_sql(admin, q).await?;
6303+
}
6304+
let set_role = format!("SET ROLE {role}");
6305+
sqlx::postgres::PgPoolOptions::new()
6306+
.after_connect(move |conn, _| {
6307+
let set_role = set_role.clone();
6308+
Box::pin(async move {
6309+
sqlx::query(sqlx::AssertSqlSafe(set_role))
6310+
.execute(conn)
6311+
.await
6312+
.map(|_| ())
6313+
})
6314+
})
6315+
.connect(db_url)
6316+
.await
6317+
}
6318+
62706319
/// Main ingest wiring for the archive gate: when only the channel lookup
62716320
/// fails, a kind-9 post by a (cached) member of an archived channel is
62726321
/// denied and not stored. The control run, with a working lookup, is denied
@@ -6288,46 +6337,14 @@ mod postgres_tests {
62886337
.expect("connect test Postgres");
62896338

62906339
let role = format!("archive_probe_{}", Uuid::new_v4().simple());
6291-
let sql = |q: String| {
6292-
let admin = admin.clone();
6293-
async move {
6294-
sqlx::query(sqlx::AssertSqlSafe(q))
6295-
.execute(&admin)
6296-
.await
6297-
.map(|_| ())
6298-
}
6299-
};
6300-
sql(format!("CREATE ROLE {role} NOLOGIN"))
6340+
create_role(&admin, &role)
63016341
.await
63026342
.expect("create restricted role");
63036343

63046344
// Everything between creating and dropping the server-wide role is
63056345
// fallible, so a setup failure still reaches the cleanup below.
63066346
let outcome = async {
6307-
for q in [
6308-
format!("GRANT USAGE ON SCHEMA public TO {role}"),
6309-
format!(
6310-
"GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO {role}"
6311-
),
6312-
format!("GRANT USAGE, SELECT ON ALL SEQUENCES IN SCHEMA public TO {role}"),
6313-
format!("REVOKE SELECT ON channels FROM {role}"),
6314-
format!("GRANT {role} TO CURRENT_USER"),
6315-
] {
6316-
sql(q).await?;
6317-
}
6318-
let set_role = format!("SET ROLE {role}");
6319-
let restricted = sqlx::postgres::PgPoolOptions::new()
6320-
.after_connect(move |conn, _| {
6321-
let set_role = set_role.clone();
6322-
Box::pin(async move {
6323-
sqlx::query(sqlx::AssertSqlSafe(set_role))
6324-
.execute(conn)
6325-
.await
6326-
.map(|_| ())
6327-
})
6328-
})
6329-
.connect(&db_url)
6330-
.await?;
6347+
let restricted = channel_blind_pool(&admin, &db_url, &role).await?;
63316348
let healthy = build_canvas_ingest_state(&db_url, &admin).await;
63326349
let failing = build_canvas_ingest_state(&db_url, &restricted).await;
63336350

@@ -6398,10 +6415,7 @@ mod postgres_tests {
63986415
}
63996416
.await;
64006417

6401-
sql(format!("DROP OWNED BY {role}"))
6402-
.await
6403-
.expect("drop restricted role grants");
6404-
sql(format!("DROP ROLE {role}"))
6418+
drop_role(&admin, &role)
64056419
.await
64066420
.expect("drop restricted role");
64076421

@@ -6424,6 +6438,110 @@ mod postgres_tests {
64246438
assert_eq!(stored, 0, "denied post must not be stored");
64256439
}
64266440

6441+
/// An artifact move whose source-channel lookup fails is an internal
6442+
/// error, not a client rejection carrying the database error text.
6443+
#[tokio::test]
6444+
#[ignore = "requires Postgres"]
6445+
async fn cluster_global_artifact_move_source_lookup_failure_is_internal() {
6446+
use buzz_db::channel::{ChannelType, ChannelVisibility};
6447+
use nostr::{Keys, Tag};
6448+
6449+
let db_url = std::env::var("BUZZ_TEST_DATABASE_URL")
6450+
.or_else(|_| std::env::var("DATABASE_URL"))
6451+
.unwrap_or_else(|_| "postgres://buzz:buzz_dev@localhost:5432/buzz".to_string()); // sadscan:disable np.postgres.1
6452+
let admin = sqlx::PgPool::connect(&db_url)
6453+
.await
6454+
.expect("connect test Postgres");
6455+
let role = format!("archive_probe_{}", Uuid::new_v4().simple());
6456+
create_role(&admin, &role)
6457+
.await
6458+
.expect("create restricted role");
6459+
6460+
let outcome = async {
6461+
let restricted = channel_blind_pool(&admin, &db_url, &role).await?;
6462+
let healthy = build_canvas_ingest_state(&db_url, &admin).await;
6463+
let failing = build_canvas_ingest_state(&db_url, &restricted).await;
6464+
let db_err = |e: buzz_db::DbError| sqlx::Error::Protocol(e.to_string());
6465+
6466+
let host = format!("artifact-move-{}.test", Uuid::new_v4().simple());
6467+
let community = healthy
6468+
.db
6469+
.ensure_configured_community(&host)
6470+
.await
6471+
.map_err(db_err)?
6472+
.id;
6473+
let tenant = TenantContext::resolved(community, &host);
6474+
let author = Keys::generate();
6475+
let [source, target] = [Uuid::new_v4(), Uuid::new_v4()];
6476+
for channel in [source, target] {
6477+
healthy
6478+
.db
6479+
.create_channel_with_id(
6480+
community,
6481+
channel,
6482+
&format!("artifact-move-{}", channel.simple()),
6483+
ChannelType::Stream,
6484+
ChannelVisibility::Open,
6485+
None,
6486+
author.public_key().to_bytes().as_slice(),
6487+
None,
6488+
)
6489+
.await
6490+
.map_err(db_err)?;
6491+
}
6492+
6493+
let artifact = Uuid::new_v4().to_string();
6494+
let revision = |home: Uuid, op: &str, prev: Option<String>| {
6495+
let mut tags = vec![
6496+
vec!["ar".to_string(), "1".into()],
6497+
vec!["d".into(), artifact.clone()],
6498+
vec!["h".into(), home.to_string()],
6499+
vec!["type".into(), "buzz.task".into()],
6500+
vec!["op".into(), op.into()],
6501+
vec!["title".into(), "Task".into()],
6502+
];
6503+
tags.extend(prev.map(|p| vec!["prev".into(), p]));
6504+
EventBuilder::new(Kind::Custom(45010), "")
6505+
.tags(tags.into_iter().map(|t| Tag::parse(t).unwrap()))
6506+
.sign_with_keys(&author)
6507+
.expect("sign revision")
6508+
};
6509+
let create = revision(source, "create", None);
6510+
let env = buzz_core::artifact::validate(&create).expect("valid create");
6511+
healthy
6512+
.db
6513+
.accept_artifact(community, &create, &env, None, &healthy.relay_keypair)
6514+
.await
6515+
.map_err(db_err)?;
6516+
6517+
let auth = IngestAuth::Http {
6518+
pubkey: author.public_key(),
6519+
scopes: vec![Scope::MessagesWrite],
6520+
auth_method: HttpAuthMethod::Nip98,
6521+
};
6522+
failing.membership_cache.insert(
6523+
(community, source, author.public_key().to_bytes().to_vec()),
6524+
true,
6525+
);
6526+
let moved = revision(target, "move", Some(create.id.to_hex()));
6527+
let result = super::super::artifact::accept(&failing, &tenant, &moved, &auth).await;
6528+
restricted.close().await;
6529+
Ok::<_, sqlx::Error>(result)
6530+
}
6531+
.await;
6532+
6533+
drop_role(&admin, &role)
6534+
.await
6535+
.expect("drop restricted role");
6536+
match outcome.expect("test setup") {
6537+
Err(IngestError::Internal(reason)) => {
6538+
assert!(reason.starts_with("error: database error"), "{reason}")
6539+
}
6540+
Err(other) => panic!("a failed source lookup must be internal, got {other:?}"),
6541+
Ok(_) => panic!("a failed source lookup must deny the move, got accepted"),
6542+
}
6543+
}
6544+
64276545
/// End-to-end CAS dispatch wiring: a tagged write inserts, a stale same-head
64286546
/// competitor returns the exact conflict: rejection, the loser is absent from
64296547
/// the DB, and an untagged write still appends unconditionally.

0 commit comments

Comments
 (0)