From d04f306ddb69c8d071e83e45d97031b902e44cf9 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 02:54:24 +0000 Subject: [PATCH 1/4] feat(id): note-granularity read-authority resolution order (#12751) Implements the #5678 read-resolution order (object -> user default -> server config -> public) as a shared, tested resolver in id-store::read_authority, so the journal/database/outline/graph projections and transclusion rendering apply one order instead of re-deriving it. Unknown notes are denied (no existence leak, invariant 6); a known note with no recorded policy falls through the defaults. NoteCheckpoints::effective_role now delegates to the shared grant logic; recorded_access exposes the object level without the public default. Refs #12751 --- pkgs/id/crates/id-store/src/lib.rs | 1 + .../crates/id-store/src/note_checkpoints.rs | 45 +- pkgs/id/crates/id-store/src/read_authority.rs | 512 ++++++++++++++++++ 3 files changed, 535 insertions(+), 23 deletions(-) create mode 100644 pkgs/id/crates/id-store/src/read_authority.rs diff --git a/pkgs/id/crates/id-store/src/lib.rs b/pkgs/id/crates/id-store/src/lib.rs index 67ab9210b6..385b68313a 100644 --- a/pkgs/id/crates/id-store/src/lib.rs +++ b/pkgs/id/crates/id-store/src/lib.rs @@ -42,6 +42,7 @@ pub mod note_links; pub mod notes; pub mod policy; pub mod range; +pub mod read_authority; pub mod search; pub mod session_checkpoint; pub mod store; diff --git a/pkgs/id/crates/id-store/src/note_checkpoints.rs b/pkgs/id/crates/id-store/src/note_checkpoints.rs index 49d1e702e8..0c03111314 100644 --- a/pkgs/id/crates/id-store/src/note_checkpoints.rs +++ b/pkgs/id/crates/id-store/src/note_checkpoints.rs @@ -361,13 +361,33 @@ impl NoteCheckpoints { Some((owner, NoteAccess::Public)) } + /// A note's recorded access policy, if the log holds one for + /// it. `None` both for a note the log does not have and for a + /// known note with no recorded policy — unlike [`Self::access`], + /// which reports the latter as [`NoteAccess::Public`]. Callers + /// that must tell those apart (the #5678 resolution order in + /// [`crate::read_authority` falls a known note with no recorded + /// policy through to the user default, then the server default) + /// use this; callers that only need the effective policy use + /// `access`. + #[must_use] + pub fn recorded_access(&self, note: Hash) -> Option<(AuthorKey, NoteAccess)> { + self.policies + .get(¬e) + .map(|policy| (policy.owner, policy.access.clone())) + } + /// The role `author` effectively holds on `note`: the owner is /// always [`NoteRole::Admin`]; on a public note every author /// holds [`NoteRole::Write`] (read included); on a scoped note /// the best matching grant wins — a direct user grant, or a /// group grant the `groups` resolver answers for. `None` when /// the author holds nothing on a scoped note, or the note is - /// unknown. + /// unknown. The grant logic lives in + /// [`crate::read_authority::role_for`]; this applies it to the + /// note's recorded policy (a note with no recorded policy reads + /// as [`NoteAccess::Public`] — the full #5678 order, with the + /// user and server defaults, is [`crate::read_authority::may_read`]). #[must_use] pub fn effective_role( &self, @@ -376,28 +396,7 @@ impl NoteCheckpoints { groups: &GroupRoles, ) -> Option { let (owner, access) = self.access(note)?; - if author == owner { - return Some(NoteRole::Admin); - } - match access { - NoteAccess::Public => Some(NoteRole::Write), - NoteAccess::Scoped(grants) => { - let mut best: Option = None; - for grant in &grants { - let role = match grant.principal { - NotePrincipal::User(user) if user == author => Some(grant.role), - NotePrincipal::Group(group) => groups - .role(group, author) - .map(|resolved| resolved.min(grant.role)), - _ => None, - }; - if let Some(role) = role { - best = Some(best.map_or(role, |b: NoteRole| b.max(role))); - } - } - best - } - } + crate::read_authority::role_for(owner, &access, author, groups) } /// Whether `author` may read `note` (any role at all on a diff --git a/pkgs/id/crates/id-store/src/read_authority.rs b/pkgs/id/crates/id-store/src/read_authority.rs new file mode 100644 index 0000000000..a9ecf463fa --- /dev/null +++ b/pkgs/id/crates/id-store/src/read_authority.rs @@ -0,0 +1,512 @@ +//! Note-granularity read authority (#12751, #5678 ruling, #5839 §6): +//! the resolution order every projection (journal, database, outline, +//! graph, search) and transclusion rendering must apply before a note — +//! or its existence — reaches a reader. +//! +//! The order, first set level wins: +//! +//! 1. object — the note's own recorded [`NoteAccess`]; +//! 2. user default — the note owner's default access for their notes; +//! 3. server config — the host's configured default; +//! 4. public — the #5678 default when nothing above says otherwise. +//! +//! "User default" is the note owner's default, not the reader's: a +//! reader's preference cannot make another owner's note readable to +//! them. That reading is recorded on #12751 (decide-and-proceed, +//! FDR-0013); the ruling's words alone do not say whose default it is. +//! +//! The resolver is pure: it takes the three levels as inputs and +//! returns which level won and the access it carries, so a test can +//! observe the order directly instead of trusting a boolean. +//! [`may_read`] composes it with a [`NoteCheckpoints`] log. Unknown +//! notes are denied — a read check must not leak existence (design +//! invariant 6) — and a known note with no recorded policy falls +//! through to the user default, then the server default, then public. +//! +//! This module decides reads only. It wires into no projection yet: +//! the journal view is the first caller (next slice on #12751), and +//! the other projections follow it instead of re-deriving the order. + +use p2panda_core::Hash; + +use id_core::waiting::AuthorKey; + +use crate::note_checkpoints::{GroupRoles, NoteAccess, NoteCheckpoints, NoteRole}; + +/// Which level of the #5678 resolution order won a read decision. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ReadLevel { + /// The note's own recorded access policy decided. + Object, + /// The note owner's default decided (no object policy recorded). + UserDefault, + /// The host's configured default decided (neither of the above set). + ServerConfig, + /// Nothing above was set: the #5678 public default decided. + Public, +} + +/// A resolved read: the winning level and the access it carries. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ResolvedRead { + /// Which level of the order won. + pub level: ReadLevel, + /// The access that level carries. + pub access: NoteAccess, +} + +/// The two fall-through levels of the #5678 order, as the host +/// supplies them: the note owner's default and the server's +/// configured default. Either may be unset, in which case that level +/// is skipped. There is no server-config type in this crate yet; the +/// host fills these in from its own configuration when it calls +/// [`resolve_read`] or [`may_read`]. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ReadDefaults { + /// The note owner's default access for their notes, when set. + pub user_default: Option, + /// The host's configured default access, when set. + pub server_default: Option, +} + +impl ReadDefaults { + /// No defaults at any level: everything falls through to public. + #[must_use] + pub fn none() -> Self { + Self::default() + } + + /// Only the owner's default is set. + #[must_use] + pub fn user(access: NoteAccess) -> Self { + Self { + user_default: Some(access), + server_default: None, + } + } + + /// Only the server's default is set. + #[must_use] + pub fn server(access: NoteAccess) -> Self { + Self { + user_default: None, + server_default: Some(access), + } + } + + /// Both defaults are set; the owner's wins over the server's. + #[must_use] + pub fn both(user: NoteAccess, server: NoteAccess) -> Self { + Self { + user_default: Some(user), + server_default: Some(server), + } + } +} + +/// Resolves the #5678 read order over the three levels: the object's +/// own policy wins when recorded; otherwise the owner's default, then +/// the server's default, then public. The first set level wins — +/// a later level never overrides an earlier one. +#[must_use] +pub fn resolve_read(object: Option<&NoteAccess>, defaults: &ReadDefaults) -> ResolvedRead { + if let Some(access) = object { + return ResolvedRead { + level: ReadLevel::Object, + access: access.clone(), + }; + } + if let Some(access) = &defaults.user_default { + return ResolvedRead { + level: ReadLevel::UserDefault, + access: access.clone(), + }; + } + if let Some(access) = &defaults.server_default { + return ResolvedRead { + level: ReadLevel::ServerConfig, + access: access.clone(), + }; + } + ResolvedRead { + level: ReadLevel::Public, + access: NoteAccess::Public, + } +} + +/// The role `reader` effectively holds under one resolved access: +/// the owner is always [`NoteRole::Admin`]; on a public note every +/// reader holds [`NoteRole::Write`] (read included); on a scoped note +/// the best matching grant wins — a direct user grant, or a group +/// grant the `groups` resolver answers for, capped at the grant's +/// role. `None` when the reader holds nothing on a scoped note. +/// This is the grant logic [`NoteCheckpoints::effective_role`] +/// applies to a note's recorded policy, factored out so projections +/// and transclusion rendering resolve it over a [`ResolvedRead`] +/// instead of re-deriving it. +#[must_use] +pub fn role_for( + owner: AuthorKey, + access: &NoteAccess, + reader: AuthorKey, + groups: &GroupRoles, +) -> Option { + if reader == owner { + return Some(NoteRole::Admin); + } + match access { + NoteAccess::Public => Some(NoteRole::Write), + NoteAccess::Scoped(grants) => { + let mut best: Option = None; + for grant in grants { + let role = match grant.principal { + NotePrincipal::User(user) if user == reader => Some(grant.role), + NotePrincipal::Group(group) => groups + .role(group, reader) + .map(|resolved| resolved.min(grant.role)), + _ => None, + }; + if let Some(role) = role { + best = Some(best.map_or(role, |b: NoteRole| b.max(role))); + } + } + best + } + } +} + +/// The resolved read access for a note in a log: `None` when the log +/// has no such note. A known note with no recorded policy resolves +/// through the defaults, exactly as [`may_read`] checks it. +#[must_use] +pub fn resolve_for( + notes: &NoteCheckpoints, + note: Hash, + defaults: &ReadDefaults, +) -> Option { + if notes.access(note).is_none() { + return None; + } + Some(match notes.recorded_access(note) { + Some((_, access)) => ResolvedRead { + level: ReadLevel::Object, + access, + }, + None => resolve_read(None, defaults), + }) +} + +/// Whether `reader` may read `note` under the #5678 order: the +/// note's recorded policy, else the owner's default, else the +/// server's default, else public. Unknown notes are denied — a +/// read check never confirms a note exists (design invariant 6). +#[must_use] +pub fn may_read( + notes: &NoteCheckpoints, + note: Hash, + reader: AuthorKey, + groups: &GroupRoles, + defaults: &ReadDefaults, +) -> bool { + let Some((owner, _)) = notes.access(note) else { + return false; + }; + let Some(resolved) = resolve_for(notes, note, defaults) else { + return false; + }; + role_for(owner, &resolved.access, reader, groups).is_some() +} + +#[cfg(test)] +#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)] +mod tests { + use super::*; + use crate::documents::DocumentRef; + use crate::note_checkpoints::{NoteGrant, NotePrincipal}; + + fn hash(byte: u8) -> Hash { + Hash::from_bytes([byte; 32]) + } + + fn author(byte: u8) -> AuthorKey { + [byte; 32] + } + + fn content(bytes: &[u8]) -> DocumentRef { + DocumentRef::for_bytes("text/markdown", bytes).unwrap() + } + + fn grant(user: AuthorKey, role: NoteRole) -> NoteGrant { + NoteGrant { + principal: NotePrincipal::User(user), + role, + } + } + + fn group_grant(group: Hash, role: NoteRole) -> NoteGrant { + NoteGrant { + principal: NotePrincipal::Group(group), + role, + } + } + + /// Three access values, one per order level, distinct so the + /// winner is observable: object denies everyone, the user + /// default is public, the server default grants one reader. + fn level_policies() -> (NoteAccess, NoteAccess, NoteAccess) { + ( + NoteAccess::Scoped(vec![]), + NoteAccess::Public, + NoteAccess::Scoped(vec![grant(author(9), NoteRole::Read)]), + ) + } + + #[test] + fn test_resolution_order_first_set_level_wins() { + let (object, user, server) = level_policies(); + // All eight presence combinations, exhaustively: the order + // property's whole input space is three presence bits. + let cases: [( + Option, + Option, + Option, + ReadLevel, + NoteAccess, + ); 8] = [ + ( + Some(object.clone()), + Some(user.clone()), + Some(server.clone()), + ReadLevel::Object, + object.clone(), + ), + ( + Some(object.clone()), + Some(user.clone()), + None, + ReadLevel::Object, + object.clone(), + ), + ( + Some(object.clone()), + None, + Some(server.clone()), + ReadLevel::Object, + object.clone(), + ), + ( + Some(object.clone()), + None, + None, + ReadLevel::Object, + object.clone(), + ), + ( + None, + Some(user.clone()), + Some(server.clone()), + ReadLevel::UserDefault, + user.clone(), + ), + ( + None, + Some(user.clone()), + None, + ReadLevel::UserDefault, + user.clone(), + ), + ( + None, + None, + Some(server.clone()), + ReadLevel::ServerConfig, + server.clone(), + ), + (None, None, None, ReadLevel::Public, NoteAccess::Public), + ]; + for (object, user, server, want_level, want_access) in cases { + let defaults = ReadDefaults { + user_default: user, + server_default: server, + }; + let resolved = resolve_read(object.as_ref(), &defaults); + assert_eq!(resolved.level, want_level); + assert_eq!(resolved.access, want_access); + } + } + + #[test] + fn test_a_later_level_never_overrides_an_earlier_one() { + // Object says scoped-deny-all; both defaults say public. + // The stranger stays denied: the defaults do not reopen it. + let mut log = NoteCheckpoints::new(); + log.create_with_access( + hash(10), + author(1), + content(b"scoped"), + NoteAccess::Scoped(vec![]), + ) + .unwrap(); + let defaults = ReadDefaults::both(NoteAccess::Public, NoteAccess::Public); + assert!(!may_read( + &log, + hash(10), + author(2), + &GroupRoles::none(), + &defaults + )); + assert_eq!( + resolve_for(&log, hash(10), &defaults).unwrap().level, + ReadLevel::Object + ); + } + + #[test] + fn test_may_read_denies_an_unknown_note_without_leaking_existence() { + let log = NoteCheckpoints::new(); + // Even with public defaults, a note the log does not have + // reads as denied — and resolves to nothing, not to public. + let defaults = ReadDefaults::both(NoteAccess::Public, NoteAccess::Public); + assert!(!may_read( + &log, + hash(99), + author(2), + &GroupRoles::none(), + &defaults + )); + assert_eq!(resolve_for(&log, hash(99), &defaults), None); + } + + #[test] + fn test_a_note_with_no_policy_falls_through_to_the_user_default() { + let mut log = NoteCheckpoints::new(); + log.create(hash(10), author(1), content(b"plain")).unwrap(); + // The owner's default scopes the note: a stranger is denied, + // the owner still reads, and the level says so. + let defaults = ReadDefaults::user(NoteAccess::Scoped(vec![])); + assert!(!may_read( + &log, + hash(10), + author(2), + &GroupRoles::none(), + &defaults + )); + assert!(may_read( + &log, + hash(10), + author(1), + &GroupRoles::none(), + &defaults + )); + assert_eq!( + resolve_for(&log, hash(10), &defaults).unwrap(), + ResolvedRead { + level: ReadLevel::UserDefault, + access: NoteAccess::Scoped(vec![]), + } + ); + } + + #[test] + fn test_a_note_with_no_policy_and_no_user_default_falls_to_the_server_default() { + let mut log = NoteCheckpoints::new(); + log.create(hash(10), author(1), content(b"plain")).unwrap(); + // The server default grants only reader 9: reader 9 reads, + // any other stranger does not, and the owner still reads. + let defaults = + ReadDefaults::server(NoteAccess::Scoped(vec![grant(author(9), NoteRole::Read)])); + assert!(may_read( + &log, + hash(10), + author(9), + &GroupRoles::none(), + &defaults + )); + assert!(!may_read( + &log, + hash(10), + author(2), + &GroupRoles::none(), + &defaults + )); + assert!(may_read( + &log, + hash(10), + author(1), + &GroupRoles::none(), + &defaults + )); + assert_eq!( + resolve_for(&log, hash(10), &defaults).unwrap().level, + ReadLevel::ServerConfig + ); + } + + #[test] + fn test_a_note_with_nothing_set_is_public() { + let mut log = NoteCheckpoints::new(); + log.create(hash(10), author(1), content(b"plain")).unwrap(); + let defaults = ReadDefaults::none(); + assert!(may_read( + &log, + hash(10), + author(2), + &GroupRoles::none(), + &defaults + )); + assert_eq!( + resolve_for(&log, hash(10), &defaults).unwrap(), + ResolvedRead { + level: ReadLevel::Public, + access: NoteAccess::Public, + } + ); + } + + #[test] + fn test_a_group_grant_in_the_resolved_default_still_reads() { + let mut log = NoteCheckpoints::new(); + log.create(hash(10), author(1), content(b"plain")).unwrap(); + // No object policy; the user default grants group 7 Read. + // A member of group 7 reads through the resolver; a + // non-member does not — the group path survives resolution. + let defaults = ReadDefaults::user(NoteAccess::Scoped(vec![group_grant( + hash(7), + NoteRole::Read, + )])); + let groups = GroupRoles::new(|group, member| { + if group == hash(7) && member == author(3) { + Some(NoteRole::Write) + } else { + None + } + }); + assert!(may_read(&log, hash(10), author(3), &groups, &defaults)); + assert!(!may_read(&log, hash(10), author(4), &groups, &defaults)); + } + + #[test] + fn test_the_owner_reads_under_every_level() { + let mut log = NoteCheckpoints::new(); + log.create(hash(10), author(1), content(b"plain")).unwrap(); + // Scoped at every level, granting nobody: the owner still + // reads — ownership is Admin at the role layer, not a grant. + let defaults = ReadDefaults::both(NoteAccess::Scoped(vec![]), NoteAccess::Scoped(vec![])); + assert!(may_read( + &log, + hash(10), + author(1), + &GroupRoles::none(), + &defaults + )); + assert_eq!( + role_for( + author(1), + &NoteAccess::Scoped(vec![]), + author(1), + &GroupRoles::none() + ), + Some(NoteRole::Admin) + ); + } +} From 4f9fee1d112dd0016bd4c5e130f976259348901c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 03:07:36 +0000 Subject: [PATCH 2/4] fix(id): import NotePrincipal for role_for in read_authority role_for matches on NotePrincipal in non-test code; the import was left in the test module only, so id-store failed to compile. --- pkgs/id/crates/id-store/src/read_authority.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkgs/id/crates/id-store/src/read_authority.rs b/pkgs/id/crates/id-store/src/read_authority.rs index a9ecf463fa..ace13b027e 100644 --- a/pkgs/id/crates/id-store/src/read_authority.rs +++ b/pkgs/id/crates/id-store/src/read_authority.rs @@ -31,7 +31,7 @@ use p2panda_core::Hash; use id_core::waiting::AuthorKey; -use crate::note_checkpoints::{GroupRoles, NoteAccess, NoteCheckpoints, NoteRole}; +use crate::note_checkpoints::{GroupRoles, NoteAccess, NoteCheckpoints, NotePrincipal, NoteRole}; /// Which level of the #5678 resolution order won a read decision. #[derive(Clone, Copy, Debug, PartialEq, Eq)] @@ -222,7 +222,7 @@ pub fn may_read( mod tests { use super::*; use crate::documents::DocumentRef; - use crate::note_checkpoints::{NoteGrant, NotePrincipal}; + use crate::note_checkpoints::NoteGrant; fn hash(byte: u8) -> Hash { Hash::from_bytes([byte; 32]) From b424a462fa7fbb934594f70e4c920c181006865c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 03:57:13 +0000 Subject: [PATCH 3/4] fix(id): create() records no access policy; only recorded policies are observable MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A plain create() inserted a Public policy entry, which made recorded_access() report Some(Public) for a note with no policy set and stopped the #5678 resolution order at the object level — the user and server defaults were unreachable. create() now records no policy: the note reads as Public (the Q3 default) through access(), while recorded_access() stays None so read_authority falls the note through to the user default, then the server default, before public. The policies map now holds only recorded policies, so a log rebuilt from its events agrees with the live log on what is recorded. Refs #12751 --- .../crates/id-store/src/note_checkpoints.rs | 30 +++++++++++-------- 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/pkgs/id/crates/id-store/src/note_checkpoints.rs b/pkgs/id/crates/id-store/src/note_checkpoints.rs index 0c03111314..43fa630228 100644 --- a/pkgs/id/crates/id-store/src/note_checkpoints.rs +++ b/pkgs/id/crates/id-store/src/note_checkpoints.rs @@ -199,9 +199,14 @@ struct NotePolicy { #[derive(Clone, Debug, Default, PartialEq, Eq)] pub struct NoteCheckpoints { events: Vec, - /// Per-note access policies, keyed by note ID. A note with no - /// entry is owner-created (by its create event's author) and - /// [`NoteAccess::Public`]: the Q3 default. + /// Per-note access policies, keyed by note ID. Only a note with + /// an explicitly set policy has an entry (see + /// [`Self::create_with_access`], [`Self::set_access`]). A note + /// with no entry is owner-created (by its create event's author) + /// and [`NoteAccess::Public`]: the Q3 default — that is what + /// [`Self::access`] reports. [`crate::read_authority`] instead + /// falls such a note through to the user default, then the server + /// default, before public, so "no policy set" stays observable. policies: HashMap, } @@ -275,6 +280,14 @@ impl NoteCheckpoints { /// Establishes a note in the log: records the `note.create` event /// whose ID is the note's stable ID, carrying its first content. /// The create is also the note's first revision and its only head. + /// It records no access policy: the note reads as + /// [`NoteAccess::Public`] (the Q3 default) until a policy is set + /// with [`Self::create_with_access`] or [`Self::set_access`] — or + /// a default applies through [`crate::read_authority`], which + /// falls a note with no recorded policy through to the user + /// default, then the server default, before public. Recording + /// the default here would make "no policy set" unobservable and + /// the #5678 fall-through unreachable. /// /// # Errors /// @@ -294,13 +307,6 @@ impl NoteCheckpoints { author, op, })?; - self.policies.insert( - event_id, - NotePolicy { - owner: author, - access: NoteAccess::Public, - }, - ); // A just-created note always folds; should it not, report the // note as unknown rather than panic. self.record(event_id)? @@ -322,8 +328,8 @@ impl NoteCheckpoints { /// this note or the event ID is already in the log. On any error /// the log is unchanged. /// Establishes a note with an access policy (see - /// [`Self::create`], which is this with the Q3 default, - /// [`NoteAccess::Public`]). The creator is recorded as the + /// [`Self::create`], which records no policy: a note with none + /// reads as [`NoteAccess::Public`]). The creator is recorded as the /// note's owner. /// /// # Errors From d6915eae7ff3932c4cd7233a870a1fcace2a5ce8 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 04:01:33 +0000 Subject: [PATCH 4/4] fix(id): policies() snapshots only recorded policies (#12751, #3819) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Merged main brought #12637, whose policies() snapshots the effective policy of every note — including a Public record for a note with no recorded policy. After this slice's create() fix, that re-states a phantom Public entry on rebuild and makes 'no policy set' unobservable again, closing the #5678 fall-through (user default, then server default) after a restart. policies() now snapshots only recorded policies; a note with none contributes no record and still reads as Public through access(). Updated the #12637 tests that assumed a Public record per note (seed refusal, restored-owner, snapshot-file restart, seed-before- events) and added: test_policies_snapshots_only_recorded_policies and test_a_rebuild_keeps_a_note_with_no_policy_falling_through. Refs #12751 --- .../crates/id-store/src/note_checkpoints.rs | 81 ++++++++++++++----- pkgs/id/crates/id-store/src/read_authority.rs | 37 +++++++++ pkgs/id/crates/id-web/src/collab.rs | 31 +++++-- 3 files changed, 121 insertions(+), 28 deletions(-) diff --git a/pkgs/id/crates/id-store/src/note_checkpoints.rs b/pkgs/id/crates/id-store/src/note_checkpoints.rs index b7648f44db..44914fdc6c 100644 --- a/pkgs/id/crates/id-store/src/note_checkpoints.rs +++ b/pkgs/id/crates/id-store/src/note_checkpoints.rs @@ -288,12 +288,16 @@ impl NoteCheckpoints { &self.events } - /// The effective access policy of every note in the log, in note - /// ID order: the durable form of the policies, to persist + /// The recorded access policy of every note that has one, in + /// note ID order: the durable form of the policies, to persist /// alongside [`Self::events`] and re-state with - /// [`Self::seed_policies`] after a rebuild. A note with no - /// recorded policy is reported with its create event's author as - /// owner and [`NoteAccess::Public`]. + /// [`Self::seed_policies`] after a rebuild. Only recorded + /// policies appear — a note with none is absent, not reported + /// as [`NoteAccess::Public`]: reporting the effective policy + /// here would re-state a Public entry on rebuild and make "no + /// policy set" unobservable, closing the #5678 fall-through + /// (user default, then server default) after a restart. A note + /// with no record still reads as Public through [`Self::access`]. /// /// # Errors /// @@ -303,14 +307,13 @@ impl NoteCheckpoints { pub fn policies(&self) -> Result, CheckpointError> { let mut records = Vec::new(); for record in self.notes()? { - let (owner, access) = self - .access(record.id) - .ok_or(CheckpointError::UnknownNote(record.id))?; - records.push(NotePolicyRecord { - note: record.id, - owner, - access, - }); + if let Some((owner, access)) = self.recorded_access(record.id) { + records.push(NotePolicyRecord { + note: record.id, + owner, + access, + }); + } } Ok(records) } @@ -1124,10 +1127,17 @@ mod tests { let (log, note) = scoped_log(); let events = log.events().to_vec(); let mut rebuilt = NoteCheckpoints::from_events(events).unwrap(); - // Before any seeding the rebuild treats the note as public. + // Before any seeding the rebuild holds no recorded policy + // for the note: it reads as public through access(), but + // the snapshot is empty — a note with no recorded policy + // contributes no record. let unseeded = rebuilt.policies().unwrap(); - assert_eq!(unseeded.len(), 1); - assert_eq!(unseeded[0].access, NoteAccess::Public); + assert!(unseeded.is_empty()); + assert_eq!(rebuilt.recorded_access(note), None); + assert_eq!( + rebuilt.access(note).unwrap(), + (author(1), NoteAccess::Public) + ); // A policy for a note the rebuilt log does not have: the // host seeded policies before events, or the wrong log. let unknown = NotePolicyRecord { @@ -1171,18 +1181,21 @@ mod tests { "the fixture really does put another author's revision first" ); let groups = GroupRoles::none(); - // The live log names the creator through its recorded policy. + // The live log names the creator through access(): a note + // with no recorded policy falls back to its create event's + // author, and the snapshot carries no record for it. assert_eq!(log.access(note).unwrap().0, author(1)); - assert_eq!(log.policies().unwrap()[0].owner, author(1)); + assert!(log.policies().unwrap().is_empty()); // Restart: the events rebuild the log with no policies, and - // the persisted snapshot must re-state. Deriving the owner - // from the first sorted revision refused this snapshot. + // the snapshot for a plain note is empty — the owner still + // comes from the create event, never from the first sorted + // revision. let events = log.events().to_vec(); let policies = log.policies().unwrap(); let rebuilt = NoteCheckpoints::from_events(events.clone()).unwrap(); assert_eq!(rebuilt.access(note).unwrap().0, author(1)); - assert_eq!(rebuilt.policies().unwrap()[0].owner, author(1)); + assert!(rebuilt.policies().unwrap().is_empty()); let restored = NoteCheckpoints::from_events_with_policies(events, policies).unwrap(); assert_eq!(restored.access(note).unwrap().0, author(1)); assert!(restored.may_append(note, author(1), &groups)); @@ -1200,4 +1213,30 @@ mod tests { let restored: Vec = serde_json::from_str(&json).unwrap(); assert_eq!(restored, policies); } + + #[test] + fn test_policies_snapshots_only_recorded_policies() { + // A scoped note and a plain note: the snapshot carries one + // record — the scoped note's. The plain note reads as Public + // through access() but contributes no record, so a rebuild + // re-states nothing for it and its fall-through survives. + let (mut log, scoped) = scoped_log(); + let plain = log + .create(hash(20), author(1), content(b"plain")) + .unwrap() + .id; + let policies = log.policies().unwrap(); + assert_eq!(policies.len(), 1); + assert_eq!(policies[0].note, scoped); + assert_eq!(log.recorded_access(plain), None); + + let rebuilt = + NoteCheckpoints::from_events_with_policies(log.events().to_vec(), policies).unwrap(); + assert_eq!( + rebuilt.recorded_access(scoped), + log.recorded_access(scoped) + ); + assert_eq!(rebuilt.recorded_access(plain), None); + assert_eq!(rebuilt.policies().unwrap(), log.policies().unwrap()); + } } diff --git a/pkgs/id/crates/id-store/src/read_authority.rs b/pkgs/id/crates/id-store/src/read_authority.rs index ace13b027e..f121c9a812 100644 --- a/pkgs/id/crates/id-store/src/read_authority.rs +++ b/pkgs/id/crates/id-store/src/read_authority.rs @@ -407,6 +407,43 @@ mod tests { ); } + #[test] + fn test_a_rebuild_keeps_a_note_with_no_policy_falling_through() { + // The #12751 + #3819 composition: a note with no recorded + // policy falls through to the user default on the live log, + // and still does after a restart rebuild — the policies + // snapshot carries no record for it, so seeding it back + // must not invent a Public entry that would close the + // fall-through at the object level. + let mut log = NoteCheckpoints::new(); + log.create(hash(10), author(1), content(b"plain")).unwrap(); + let defaults = ReadDefaults::user(NoteAccess::Scoped(vec![])); + let rebuilt = NoteCheckpoints::from_events_with_policies( + log.events().to_vec(), + log.policies().unwrap(), + ) + .unwrap(); + assert!(rebuilt.policies().unwrap().is_empty()); + assert!(!may_read( + &rebuilt, + hash(10), + author(2), + &GroupRoles::none(), + &defaults + )); + assert!(may_read( + &rebuilt, + hash(10), + author(1), + &GroupRoles::none(), + &defaults + )); + assert_eq!( + resolve_for(&rebuilt, hash(10), &defaults).unwrap().level, + ReadLevel::UserDefault + ); + } + #[test] fn test_a_note_with_no_policy_and_no_user_default_falls_to_the_server_default() { let mut log = NoteCheckpoints::new(); diff --git a/pkgs/id/crates/id-web/src/collab.rs b/pkgs/id/crates/id-web/src/collab.rs index f363b5c218..56fc429774 100644 --- a/pkgs/id/crates/id-web/src/collab.rs +++ b/pkgs/id/crates/id-web/src/collab.rs @@ -727,10 +727,12 @@ impl CollabState { self.note_log.lock().await.events().to_vec() } - /// The effective access policy of every note in the checkpoint - /// log, in note ID order (#3819): the durable form of the - /// policies, to persist alongside [`Self::note_events`] and - /// re-state with [`Self::seed_note_policies`] after a rebuild. + /// The recorded access policy of every note that has one, in + /// note ID order (#3819): the durable form of the policies, to + /// persist alongside [`Self::note_events`] and re-state with + /// [`Self::seed_note_policies`] after a rebuild. A note with no + /// recorded policy contributes no record — it reads as public + /// through the fall-through, and must not be re-stated as one. /// /// # Errors /// @@ -3249,11 +3251,12 @@ mod tests { .unwrap(); // The mutations reached the file: it parses as a snapshot - // holding both notes' events and both policies. + // holding both notes' events and the one recorded policy — + // the public note has none, so it contributes no record. let persisted: NoteCheckpointSnapshot = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap(); assert_eq!(persisted.events.len(), 2); - assert_eq!(persisted.policies.len(), 2); + assert_eq!(persisted.policies.len(), 1); let heads_before = live.note_heads(note).await.unwrap(); // Restart: a fresh state over the same file. @@ -3329,9 +3332,13 @@ mod tests { #[tokio::test] async fn test_seed_note_policies_before_events_is_refused() { + use id_store::note_checkpoints::{NoteGrant, NotePrincipal, NoteRole}; + // Policies name notes; a policy for a note the log has no // create event for is a failed restart, never a note - // silently reopened to public. + // silently reopened to public. The live note needs a + // recorded policy for the snapshot to carry a record at + // all — a plain note contributes none. let note = Hash::from_bytes([43u8; 32]); let key = note_session_key(¬e); let owner: AuthorKey = [7u8; 32]; @@ -3339,6 +3346,16 @@ mod tests { live.get_or_create_for_note(¬e, "", Some(b"# First"), Some("n.md")) .await; live.publish_note_checkpoint(&key, owner).await.unwrap(); + live.set_note_access( + note, + owner, + NoteAccess::Scoped(vec![NoteGrant { + principal: NotePrincipal::User(owner), + role: NoteRole::Read, + }]), + ) + .await + .unwrap(); let policies = live.note_policies().await.unwrap(); let restarted = CollabState::new();