Skip to content

Commit aff407d

Browse files
author
coder2
committed
fix(db): preserve partition reader grants
Signed-off-by: coder2 <4acc49cb93576448ba82e631688c51a40bf03d6a889d78fddf57917d198de10f@buzz.block.builderlab.xyz>
1 parent ca3be55 commit aff407d

3 files changed

Lines changed: 234 additions & 1 deletion

File tree

‎crates/buzz-db/src/store/partition/maintenance.rs‎

Lines changed: 41 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,8 @@
1111
//! lock, then the catch-all, in the order writers take them, waiting only on
1212
//! the parent and failing fast on any other contention;
1313
//! 3. re-audits under those locks and refuses if the plan changed; and
14-
//! 4. re-audits the changed catalog and verifies index and constraint
14+
//! 4. copies the parent's explicit table-level SELECT grants to new children;
15+
//! 5. re-audits the changed catalog and verifies index and constraint
1516
//! inheritance before commit.
1617
//!
1718
//! A populated catch-all is always refused before any lock is taken: moving
@@ -732,6 +733,14 @@ async fn apply_change(
732733
.await?;
733734
}
734735

736+
grant_parent_readers(
737+
&mut transaction,
738+
parent.oid,
739+
&parent.schema,
740+
&expected.target_names(table),
741+
)
742+
.await?;
743+
735744
let after = audit_table_on(&mut transaction, table, months_ahead, now).await?;
736745
let verified = verify_applied(&locked, &after, &expected).and(
737746
verify_inheritance(&mut transaction, parent.oid, &expected.target_names(table)).await?,
@@ -746,6 +755,37 @@ async fn apply_change(
746755
Ok(LockedAttempt::Committed(expected))
747756
}
748757

758+
/// The parent ACL is the reader policy; never copy writes or grant options.
759+
/// PostgreSQL quotes catalog role names, including names containing quotes.
760+
/// PUBLIC is an ACL grantee too, but must remain an unquoted SQL keyword.
761+
async fn grant_parent_readers(
762+
connection: &mut PgConnection,
763+
parent_oid: i64,
764+
schema: &str,
765+
children: &[String],
766+
) -> Result<()> {
767+
let grants: Vec<String> = sqlx::query_scalar(
768+
"SELECT DISTINCT pg_catalog.format(\
769+
'GRANT SELECT ON TABLE %I.%I TO %s', $2::text, child, \
770+
CASE WHEN acl.grantee = 0 THEN 'PUBLIC' \
771+
ELSE pg_catalog.quote_ident(pg_catalog.pg_get_userbyid(acl.grantee)) END) \
772+
FROM pg_catalog.pg_class parent \
773+
CROSS JOIN LATERAL pg_catalog.aclexplode(parent.relacl) acl \
774+
CROSS JOIN pg_catalog.unnest($3::text[]) child \
775+
WHERE parent.oid = $1::bigint::oid \
776+
AND acl.privilege_type = 'SELECT' AND acl.grantee <> parent.relowner",
777+
)
778+
.bind(parent_oid)
779+
.bind(schema)
780+
.bind(children)
781+
.fetch_all(&mut *connection)
782+
.await?;
783+
for grant in grants {
784+
execute_ddl(connection, grant).await?;
785+
}
786+
Ok(())
787+
}
788+
749789
async fn configure_maintenance_transaction(connection: &mut PgConnection) -> Result<()> {
750790
pin_catalog_rendering(connection).await?;
751791
for (setting, value) in [

‎crates/buzz-db/src/store/partition/maintenance_tests.rs‎

Lines changed: 178 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -584,6 +584,184 @@ mod postgres_tests {
584584
.any(|child| child.name == format!("{}_p2026_09", table.table))));
585585
}
586586

587+
#[tokio::test]
588+
#[ignore = "requires Postgres"]
589+
async fn cluster_global_parent_readers_follow_monthly_creation_and_catch_all_advancement() {
590+
use crate::store::partition::quote_identifier;
591+
592+
let (pool, scratch) = scratch_pool().await;
593+
seed_parents(&pool).await;
594+
let reader = format!("{}_r\"x", scratch.name);
595+
let writer = format!("{}_writer", scratch.name);
596+
for role in [&reader, &writer] {
597+
execute_ddl(
598+
&mut pool.acquire().await.unwrap(),
599+
format!("CREATE ROLE {}", quote_identifier(role)),
600+
)
601+
.await
602+
.unwrap();
603+
}
604+
for statement in [
605+
format!(
606+
"GRANT USAGE ON SCHEMA {} TO {}, {}",
607+
scratch.name,
608+
quote_identifier(&reader),
609+
quote_identifier(&writer)
610+
),
611+
format!(
612+
"GRANT SELECT ON events TO {} WITH GRANT OPTION",
613+
quote_identifier(&reader)
614+
),
615+
format!(
616+
"GRANT INSERT, UPDATE ON events TO {}",
617+
quote_identifier(&reader)
618+
),
619+
format!(
620+
"GRANT INSERT, SELECT (id) ON events TO {}",
621+
quote_identifier(&writer)
622+
),
623+
"GRANT SELECT ON delivery_log TO PUBLIC".to_string(),
624+
"CREATE TABLE unrelated (id BIGINT)".to_string(),
625+
] {
626+
execute_ddl(&mut pool.acquire().await.unwrap(), statement)
627+
.await
628+
.unwrap();
629+
}
630+
for table in PARTITIONED_TABLES {
631+
create_child(
632+
&pool,
633+
table,
634+
&format!("{table}_p_past"),
635+
"MINVALUE",
636+
"'2026-09-01'",
637+
)
638+
.await;
639+
}
640+
641+
maintain_partitions_at(&pool, 0, CREATE_ONLY, fixed_now())
642+
.await
643+
.expect("create uncovered September");
644+
let can = |role: String, relation: String, privilege: &'static str| {
645+
let pool = pool.clone();
646+
async move {
647+
sqlx::query_scalar::<_, bool>("SELECT has_table_privilege($1, $2, $3)")
648+
.bind(role)
649+
.bind(relation)
650+
.bind(privilege)
651+
.fetch_one(&pool)
652+
.await
653+
.unwrap()
654+
}
655+
};
656+
let mut direct_read = pool.begin().await.unwrap();
657+
execute_ddl(
658+
&mut direct_read,
659+
format!("SET LOCAL ROLE {}", quote_identifier(&reader)),
660+
)
661+
.await
662+
.unwrap();
663+
sqlx::query("SELECT * FROM events_p2026_09 LIMIT 0")
664+
.execute(&mut *direct_read)
665+
.await
666+
.expect("parent reader can query the new child directly");
667+
direct_read.rollback().await.unwrap();
668+
assert!(can(reader.clone(), "events_p2026_09".into(), "SELECT").await);
669+
for privilege in ["INSERT", "UPDATE", "SELECT WITH GRANT OPTION"] {
670+
assert!(!can(reader.clone(), "events_p2026_09".into(), privilege).await);
671+
}
672+
for relation in [
673+
"events_p2026_09",
674+
"events_p_past",
675+
"delivery_log_p_past",
676+
"unrelated",
677+
] {
678+
assert!(!can(writer.clone(), relation.into(), "SELECT").await);
679+
}
680+
assert!(!can(reader.clone(), "events_p_past".into(), "SELECT").await);
681+
assert!(!can(reader.clone(), "unrelated".into(), "SELECT").await);
682+
assert!(can(writer.clone(), "delivery_log_p2026_09".into(), "SELECT").await);
683+
684+
// The next rotation uses the current parent ACL, not a cached reader list.
685+
for statement in [
686+
format!("REVOKE SELECT ON events FROM {}", quote_identifier(&reader)),
687+
format!("GRANT SELECT ON events TO {}", quote_identifier(&writer)),
688+
] {
689+
execute_ddl(&mut pool.acquire().await.unwrap(), statement)
690+
.await
691+
.unwrap();
692+
}
693+
for table in PARTITIONED_TABLES {
694+
create_child(
695+
&pool,
696+
table,
697+
&format!("{table}_p_future"),
698+
"'2026-10-01'",
699+
"MAXVALUE",
700+
)
701+
.await;
702+
}
703+
maintain_partitions_at(&pool, 1, ADVANCE, fixed_now())
704+
.await
705+
.expect("replace catch-all and grant new readers");
706+
for relation in ["events_p2026_10", "events_p_future"] {
707+
assert!(can(writer.clone(), relation.into(), "SELECT").await);
708+
assert!(!can(writer.clone(), relation.into(), "INSERT").await);
709+
assert!(!can(reader.clone(), relation.into(), "SELECT").await);
710+
}
711+
for relation in ["delivery_log_p2026_10", "delivery_log_p_future"] {
712+
assert!(can(reader.clone(), relation.into(), "SELECT").await);
713+
assert!(!can(reader.clone(), relation.into(), "INSERT").await);
714+
}
715+
let before = catalog_snapshot(&pool).await;
716+
maintain_partitions_at(&pool, 1, ADVANCE, fixed_now())
717+
.await
718+
.unwrap();
719+
assert_eq!(catalog_snapshot(&pool).await, before);
720+
}
721+
722+
#[tokio::test]
723+
#[ignore = "requires Postgres"]
724+
async fn cluster_global_reader_grant_failure_rolls_back_partition_replacement() {
725+
let (pool, scratch) = scratch_pool().await;
726+
seed_repaired_layout(&pool, false).await;
727+
sqlx::query("GRANT SELECT ON events TO PUBLIC")
728+
.execute(&pool)
729+
.await
730+
.unwrap();
731+
let before = catalog_snapshot(&pool).await;
732+
sqlx::query(
733+
"CREATE FUNCTION reject_partition_grant() RETURNS event_trigger \
734+
LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected grant failure'; END $$",
735+
)
736+
.execute(&pool)
737+
.await
738+
.unwrap();
739+
execute_ddl(
740+
&mut pool.acquire().await.unwrap(),
741+
format!(
742+
"CREATE EVENT TRIGGER {}_grant_failure ON ddl_command_start \
743+
WHEN TAG IN ('GRANT') EXECUTE FUNCTION reject_partition_grant()",
744+
scratch.name
745+
),
746+
)
747+
.await
748+
.unwrap();
749+
750+
let result = maintain(&pool).await;
751+
assert!(
752+
matches!(result, Err(DbError::InvalidData(ref message))
753+
if message.contains("events error") && message.contains("injected grant failure")),
754+
"{result:?}"
755+
);
756+
let events = |snapshot: Vec<(String, String, String, i64)>| {
757+
snapshot
758+
.into_iter()
759+
.filter(|(name, ..)| name.starts_with("events_"))
760+
.collect::<Vec<_>>()
761+
};
762+
assert_eq!(events(catalog_snapshot(&pool).await), events(before));
763+
}
764+
587765
#[tokio::test]
588766
#[ignore = "requires Postgres"]
589767
async fn populated_catch_all_is_refused_before_any_lock() {

‎docs/partition-catalog-monitoring.md‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,21 @@ later. Once its upper bound is at or before the start of the current month, it i
3030
historical. It remains in the per-child report as `legacy_leaf` but no longer
3131
degrades the table.
3232

33+
## Reader grants on new partitions
34+
35+
When maintenance creates a monthly partition or replaces the empty catch-all,
36+
it copies explicit table-level `SELECT` grants from that parent to the new
37+
children before committing. Group roles and explicit `PUBLIC` grants are
38+
included; the owner's ACL entry, column-only grants, writes, and grant options
39+
are not copied. No additional relay setting is needed. A grant failure rolls
40+
back that table's entire maintenance transaction.
41+
42+
Existing children and manually created or attached partitions still need their
43+
own grants. Maintenance does not reconcile grants on existing tables or revoke
44+
old grants when the parent ACL changes. Keep those permissions aligned through
45+
the database's provisioning process. Initial schema bootstrap runs before
46+
deployment-specific reader grants are provisioned.
47+
3348
## Metrics
3449

3550
Per-table gauges are set only by a successful audit of that table:

0 commit comments

Comments
 (0)