From 7add66920ddada3e145e7b21982012b506c66532 Mon Sep 17 00:00:00 2001 From: Sanapach Date: Thu, 19 Nov 2026 23:59:08 +0200 Subject: [PATCH] Bind share confirmations to the share decision A privacy confirmation now covers the share decision it was given for, not only the URLs: sharing turned off, or turned on again after a revocation, on any trusted device drops it, so this device asks again before it publishes a feed URL that looks private. Co-Authored-By: Claude Opus 5.5 --- src/app/podcast_runtime.rs | 27 ++-- src/podcasts/discovery_tests.rs | 26 ++-- src/podcasts/publication.rs | 213 ++++++++++++++++++++++++++---- src/podcasts/publication_tests.rs | 169 +++++++++++++++++++++--- 4 files changed, 363 insertions(+), 72 deletions(-) diff --git a/src/app/podcast_runtime.rs b/src/app/podcast_runtime.rs index 42fd9c8..1a1f3ad 100644 --- a/src/app/podcast_runtime.rs +++ b/src/app/podcast_runtime.rs @@ -354,26 +354,27 @@ pub fn perform(state: &mut AppState, runtime: &mut Runtime, effect: Effect) -> O None } -/// Writes a share decision. The local confirmation is recorded before the -/// synced decision, so the reconciler pass the decision triggers already -/// sees it; turning sharing off forgets it. Blocking. +/// Writes a share decision and keeps the local privacy confirmation bound +/// to it (`publication::set_shared`). Blocking. fn set_shared( services: &Services, podcast_id: &music_dht::podcast::PodcastId, shared: bool, confirm: Option, ) -> anyhow::Result<()> { - if let Some(urls) = confirm { - services.confirmations.confirm(podcast_id, urls)?; - } let store = Arc::clone(&services.store); - services - .log - .record(&mut |stamps| store.set_shared(stamps, podcast_id, shared))?; - if !shared { - services.confirmations.forget(podcast_id)?; - } - Ok(()) + publication::set_shared( + &services.store, + &services.confirmations, + podcast_id, + shared, + confirm, + || { + services + .log + .record(&mut |stamps| store.set_shared(stamps, podcast_id, shared)) + }, + ) } fn is_podcast_effect(effect: &Effect) -> bool { diff --git a/src/podcasts/discovery_tests.rs b/src/podcasts/discovery_tests.rs index 8571e07..83d0c91 100644 --- a/src/podcasts/discovery_tests.rs +++ b/src/podcasts/discovery_tests.rs @@ -15,7 +15,7 @@ use super::discovery::{ PODCAST_SEARCH_TIMEOUT, PodcastHit, podcast_hits, preview, resolve_local_ids, search, subscribe_from_hit, test_hit, }; -use super::publication::{Publication, check_share, reconcile}; +use super::publication::{Publication, check_share, reconcile, set_shared}; use super::publication_tests::{Node, wait_for}; use super::refresh::{refresh, subscribe}; use super::test_server::Route; @@ -305,18 +305,22 @@ async fn stranger_subscribes() { .await .unwrap(); let store_a = Arc::clone(&user_a.services.store); - user_a - .services - .log - .record(&mut |stamps| store_a.set_shared(stamps, &shared.podcast_id, true)) - .unwrap(); let confirmations = Arc::clone(&user_a.services.confirmations); let check = check_share(&store_a, &confirmations, &shared.podcast_id).unwrap(); - if check.needs_confirmation() { - confirmations - .confirm(&shared.podcast_id, check.urls) - .unwrap(); - } + set_shared( + &store_a, + &confirmations, + &shared.podcast_id, + true, + check.needs_confirmation().then_some(check.urls), + || { + user_a + .services + .log + .record(&mut |stamps| store_a.set_shared(stamps, &shared.podcast_id, true)) + }, + ) + .unwrap(); let report = reconcile( &a.dht, Some(Arc::clone(&store_a)), diff --git a/src/podcasts/publication.rs b/src/podcasts/publication.rs index 89fd5f8..a2be2c9 100644 --- a/src/podcasts/publication.rs +++ b/src/podcasts/publication.rs @@ -27,7 +27,10 @@ //! (`PodcastCardSpec::privacy_warnings`). FRID leaves this confirmation to //! the client and does not sync it: every device asks its own user before //! it publishes such a URL under its own identity. A confirmation is bound -//! to the exact URLs shown, so a feed that moves to another URL asks again. +//! to the exact URLs shown, so a feed that moves to another URL asks again, +//! and to the share decision it was given for (the share register's +//! operation), so a decision taken anywhere later — sharing turned off, +//! unsubscribing, sharing again — asks again too. //! //! Logging stays free of private data: only counts are logged, never feed //! URLs, titles or ids of podcasts that are not shared. @@ -40,7 +43,7 @@ use std::time::Duration; use anyhow::{Context, Result}; use furumi_library::podcasts::{PodcastListFilter, PodcastStore, PodcastSummary}; -use music_dht::podcast::{FeedUrl, PodcastId, SubscriptionRecord, effective_share}; +use music_dht::podcast::{FeedUrl, PodcastId, ShareRecord, SubscriptionRecord, effective_share}; use music_dht::podcast_dht::{ FeedUrlPrivacyWarning, PodcastCardSpec, PodcastDht, PodcastDhtSyncStats, PodcastShareState, }; @@ -49,8 +52,9 @@ use tokio::sync::{Notify, watch}; /// Local file with the privacy confirmations, next to `podcasts.sqlite3`. pub const CONFIRMATIONS_FILE: &str = "podcast-share-confirmations.json"; -/// Format version of [`CONFIRMATIONS_FILE`]. -const CONFIRMATIONS_VERSION: u32 = 1; +/// Format version of [`CONFIRMATIONS_FILE`]. Version 1 (URLs only, never +/// released) is read as empty: the user is asked again. +const CONFIRMATIONS_VERSION: u32 = 2; /// Periodic reconciliation (on top of the triggers). Cards are re-signed by /// the overlay's own maintenance every 10 minutes; this pass catches share /// decisions that changed while the overlay was busy or unreachable. @@ -79,19 +83,77 @@ impl ConfirmedUrls { } } +/// The share decision a confirmation was given for. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(tag = "state", rename_all = "snake_case")] +enum Decision { + /// Confirmed before this device recorded its share decision: covers the + /// first share decision newer than the share register seen then + /// (`after`, its order key; `None`: no register yet). + Pending { after: Option<(u64, i64, String)> }, + /// Covers exactly the share decision written by operation `op_id`. + Bound { op_id: String }, +} + +/// One confirmation: the URLs shown and the decision it was given for. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +struct Confirmation { + urls: ConfirmedUrls, + decision: Decision, +} + +impl Confirmation { + /// Whether the confirmation covers the merged share register `share`. + fn covers(&self, share: Option<&ShareRecord>) -> bool { + let Some(share) = share.filter(|share| share.shared) else { + return false; + }; + match &self.decision { + Decision::Bound { op_id } => *op_id == share.op_id, + Decision::Pending { after } => is_after(after.as_ref(), share), + } + } + + /// A newer share decision than the confirmed one exists: sharing was + /// turned off, or turned on again after a revocation, here or on + /// another trusted device. Unsubscribing never changes the share + /// register, but sharing after subscribing again writes a new decision. + fn superseded(&self, share: Option<&ShareRecord>) -> bool { + match (&self.decision, share) { + (Decision::Bound { op_id }, Some(share)) => *op_id != share.op_id, + (Decision::Pending { after }, Some(share)) => { + !share.shared && is_after(after.as_ref(), share) + } + (_, None) => false, + } + } +} + +/// `share` is newer than the register order key `after` (`None`: there was +/// no register). +fn is_after(after: Option<&(u64, i64, String)>, share: &ShareRecord) -> bool { + after.is_none_or(|(generation, hlc, op)| share.order_key() > (*generation, *hlc, op.as_str())) +} + #[derive(Debug, Default, Serialize, Deserialize)] struct ConfirmationsFile { version: u32, - confirmed: BTreeMap, + confirmed: BTreeMap, } /// Device-local record of "publish this feed URL although it looks /// private" (`PodcastShareState::privacy_confirmed`). Not synced. +/// +/// A confirmation covers the URLs shown and one share decision: it is +/// recorded before the decision is written (pending), bound to the share +/// register's operation once written ([`ShareConfirmations::bind`]), and +/// dropped when a newer decision supersedes it — including decisions taken +/// on other trusted devices ([`ShareConfirmations::prune`]). #[derive(Debug)] pub struct ShareConfirmations { /// `None`: in memory only (tests, or the podcast store is unavailable). path: Option, - confirmed: Mutex>, + confirmed: Mutex>, } impl ShareConfirmations { @@ -135,42 +197,105 @@ impl ShareConfirmations { } } - /// Whether the user confirmed publishing exactly these feed URLs. - pub fn is_confirmed(&self, card: &PodcastCardSpec) -> bool { + /// Whether the user confirmed publishing exactly these feed URLs for + /// the current share decision `share` (the merged share register). + pub fn is_confirmed(&self, card: &PodcastCardSpec, share: Option<&ShareRecord>) -> bool { self.lock() .get(&card.podcast_id) - .is_some_and(|urls| *urls == ConfirmedUrls::of(card)) + .is_some_and(|confirmation| { + confirmation.urls == ConfirmedUrls::of(card) && confirmation.covers(share) + }) } - /// Records the confirmation of `urls` (replacing an older one). - /// Blocking (writes the file). - pub fn confirm(&self, podcast_id: &PodcastId, urls: ConfirmedUrls) -> Result<()> { - let mut confirmed = self.lock(); - if confirmed.get(podcast_id) == Some(&urls) { + /// Records the confirmation of `urls` for the next share decision after + /// `share` (the merged share register now, before this device writes + /// its decision), replacing an older one. Blocking (writes the file). + pub fn confirm( + &self, + podcast_id: &PodcastId, + urls: ConfirmedUrls, + share: Option<&ShareRecord>, + ) -> Result<()> { + let after = share.map(|share| { + let (generation, hlc, op) = share.order_key(); + (generation, hlc, op.to_string()) + }); + self.update(podcast_id, |entry| { + *entry = Some(Confirmation { + urls, + decision: Decision::Pending { after }, + }); + }) + } + + /// Binds the confirmation of a podcast to the share decision `share` + /// this device just wrote (or found already written, when it confirms + /// a podcast shared elsewhere). No-op without a confirmation or when + /// `share` does not share. Blocking. + pub fn bind(&self, podcast_id: &PodcastId, share: &ShareRecord) -> Result<()> { + if !share.shared { return Ok(()); } - let mut next = confirmed.clone(); - next.insert(podcast_id.clone(), urls); - self.save(&next)?; - *confirmed = next; - Ok(()) + self.update(podcast_id, |entry| { + if let Some(confirmation) = entry { + confirmation.decision = Decision::Bound { + op_id: share.op_id.clone(), + }; + } + }) + } + + /// Drops a confirmation that a newer share decision superseded (taken + /// here or on another trusted device), and binds a pending one to the + /// decision it now covers. Blocking. + pub fn prune(&self, podcast_id: &PodcastId, share: Option<&ShareRecord>) -> Result<()> { + self.update(podcast_id, |entry| { + let Some(confirmation) = entry else { + return; + }; + if confirmation.superseded(share) { + *entry = None; + } else if let (Decision::Pending { .. }, Some(share)) = (&confirmation.decision, share) + && confirmation.covers(Some(share)) + { + confirmation.decision = Decision::Bound { + op_id: share.op_id.clone(), + }; + } + }) } /// Drops the confirmation of a podcast (sharing turned off or /// unsubscribed here): sharing it again asks again. Blocking. pub fn forget(&self, podcast_id: &PodcastId) -> Result<()> { + self.update(podcast_id, |entry| *entry = None) + } + + /// Applies `change` to the entry of `podcast_id` and saves the file when + /// the entry changed. + fn update( + &self, + podcast_id: &PodcastId, + change: impl FnOnce(&mut Option), + ) -> Result<()> { let mut confirmed = self.lock(); - if !confirmed.contains_key(podcast_id) { + let current = confirmed.get(podcast_id).cloned(); + let mut entry = current.clone(); + change(&mut entry); + if entry == current { return Ok(()); } let mut next = confirmed.clone(); - next.remove(podcast_id); + match entry { + Some(confirmation) => next.insert(podcast_id.clone(), confirmation), + None => next.remove(podcast_id), + }; self.save(&next)?; *confirmed = next; Ok(()) } - fn save(&self, confirmed: &BTreeMap) -> Result<()> { + fn save(&self, confirmed: &BTreeMap) -> Result<()> { let Some(path) = &self.path else { return Ok(()); }; @@ -182,7 +307,7 @@ impl ShareConfirmations { .with_context(|| format!("saving {}", path.display())) } - fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap> { + fn lock(&self) -> std::sync::MutexGuard<'_, BTreeMap> { self.confirmed .lock() .unwrap_or_else(PoisonError::into_inner) @@ -288,19 +413,50 @@ pub fn check_share( ) -> Result { let card = share_card(store, podcast_id)? .with_context(|| "the podcast is not subscribed".to_string())?; + let share = store.share(podcast_id)?; Ok(ShareCheck { urls: ConfirmedUrls::of(&card), warnings: card.privacy_warnings(), - confirmed: confirmations.is_confirmed(&card), + confirmed: confirmations.is_confirmed(&card, share.as_ref()), }) } +/// Writes a share decision with `record` (the synced `podcast_share_set` +/// operation). The confirmation of `confirm` is recorded first (pending: it +/// covers the next share decision), so a reconciler pass the decision +/// triggers already sees it, and is then bound to the decision in force — +/// the one just written, or, for a podcast shared elsewhere and held back +/// here, the one already there (`set_shared` writes nothing then). Turning +/// sharing off forgets it. Blocking. +pub fn set_shared( + store: &PodcastStore, + confirmations: &ShareConfirmations, + podcast_id: &PodcastId, + shared: bool, + confirm: Option, + record: impl FnOnce() -> Result<()>, +) -> Result<()> { + if let Some(urls) = confirm { + let share = store.share(podcast_id)?; + confirmations.confirm(podcast_id, urls, share.as_ref())?; + } + record()?; + if !shared { + return confirmations.forget(podcast_id); + } + match store.share(podcast_id)? { + Some(share) => confirmations.bind(podcast_id, &share), + None => Ok(()), + } +} + /// One `PodcastShareState` per podcast with a subscription register, the /// input of `PodcastDht::sync_shares`. Blocking. /// /// Only podcasts for which `effective_share` holds get a card; for every /// other podcast `card` is `None` and `privacy_confirmed` false, so no -/// private metadata is prepared for publication at all. +/// private metadata is prepared for publication at all. Confirmations that +/// a newer share decision superseded (on any device) are dropped here. pub fn share_states( store: &PodcastStore, confirmations: &ShareConfirmations, @@ -312,6 +468,11 @@ pub fn share_states( continue; }; let share = store.share(podcast_id)?; + if let Err(err) = confirmations.prune(podcast_id, share.as_ref()) { + // Not dropping it only keeps a confirmation that no longer + // covers the current decision (`is_confirmed` checks that). + tracing::warn!("podcast share confirmation not updated: {err:#}"); + } let shared = effective_share(Some(&subscription), share.as_ref()); // A card that cannot be built from the catalog falls back to the // one `sync_shares` derives from the register (and fails there, @@ -325,7 +486,7 @@ pub fn share_states( }; let privacy_confirmed = card .as_ref() - .is_some_and(|card| confirmations.is_confirmed(card)); + .is_some_and(|card| confirmations.is_confirmed(card, share.as_ref())); states.push(PodcastShareState { subscription, share, diff --git a/src/podcasts/publication_tests.rs b/src/podcasts/publication_tests.rs index 788886c..698c27d 100644 --- a/src/podcasts/publication_tests.rs +++ b/src/podcasts/publication_tests.rs @@ -16,7 +16,7 @@ use music_dht::{MusicDhtConfig, MusicDhtService, NetworkId}; use super::publication::{ Discovery, Publication, PublicationReport, ShareConfirmations, check_share, reconcile, - share_card, share_states, summarize, warning_ru, + set_shared, share_card, share_states, summarize, warning_ru, }; const SHOW_URL: &str = "https://feeds.example.test/rust-radio.xml"; @@ -109,6 +109,27 @@ impl Device { } } +/// The user confirms the URLs the dialog shows for a podcast that is +/// already shared (held back here): no new decision is written, the +/// confirmation is bound to the one in force (as the runtime does). +fn confirm_shown(store: &PodcastStore, confirmations: &ShareConfirmations, id: &PodcastId) { + let check = check_share(store, confirmations, id).unwrap(); + set_shared(store, confirmations, id, true, Some(check.urls), || Ok(())).unwrap(); +} + +/// Whether this device would publish `id` with its privacy confirmed. +fn confirmed_here( + store: &PodcastStore, + confirmations: &ShareConfirmations, + id: &PodcastId, +) -> bool { + share_states(store, confirmations) + .unwrap() + .into_iter() + .find(|state| state.subscription.podcast_id == *id) + .is_some_and(|state| state.is_shared() && state.privacy_confirmed) +} + fn shared_ids(store: &PodcastStore, confirmations: &ShareConfirmations) -> Vec { share_states(store, confirmations) .unwrap() @@ -216,7 +237,20 @@ fn privacy_confirmations_are_local_and_bound_to_the_urls() { warning_ru(&check.warnings[0]), "в адресе ленты есть параметр «token», похожий на ключ доступа" ); - confirmations.confirm(&secret, check.urls.clone()).unwrap(); + // The user confirms in the dialog; the decision is written after the + // (pending) confirmation, which is then bound to it. + set_shared( + &store, + &confirmations, + &secret, + true, + Some(check.urls.clone()), + || { + device.set_shared(&store, &secret, true); + Ok(()) + }, + ) + .unwrap(); // Persisted on this device, read again after a restart. let reopened = ShareConfirmations::open(path.clone()); @@ -238,24 +272,121 @@ fn privacy_confirmations_are_local_and_bound_to_the_urls() { id_feed_url: Some(card.feed_url.clone()), ..card.clone() }; - assert!(reopened.is_confirmed(&card)); - assert!(!reopened.is_confirmed(&moved)); + let share = store.share(&secret).unwrap(); + assert!(reopened.is_confirmed(&card, share.as_ref())); + assert!(!reopened.is_confirmed(&moved, share.as_ref())); - // Shared but held: the confirmation is used by the share state. - device.set_shared(&store, &secret, true); - let state = share_states(&store, &reopened) - .unwrap() - .into_iter() - .find(|state| state.subscription.podcast_id == secret) - .unwrap(); - assert!(state.privacy_confirmed); + // The share state uses the confirmation. + assert!(confirmed_here(&store, &reopened, &secret)); reopened.forget(&secret).unwrap(); - assert!(!ShareConfirmations::open(path.clone()).is_confirmed(&card)); + assert!(!ShareConfirmations::open(path.clone()).is_confirmed(&card, share.as_ref())); // A corrupt file asks again instead of failing. std::fs::write(&path, b"{not json").unwrap(); - assert!(!ShareConfirmations::open(path).is_confirmed(&card)); + assert!(!ShareConfirmations::open(path).is_confirmed(&card, share.as_ref())); +} + +#[test] +fn a_confirmation_does_not_outlive_a_revocation_on_another_device() { + let temp = tempfile::tempdir().unwrap(); + let store = PodcastStore::open_in_memory().unwrap(); + let confirmations = ShareConfirmations::open(temp.path().join("confirmations.json")); + let mut device = Device::new("device-a"); + let secret = device.subscribe(&store, SECRET_URL, "Members Only"); + let other = PodcastStore::open_in_memory().unwrap(); + let mut device_b = Device::new("device-b"); + let sync = |from: &[SyncOpWire], to: &PodcastStore| { + for op in from { + to.apply_remote_op(op).unwrap(); + } + }; + + // A: the dialog, confirmed; the confirmation covers A's decision. + let check = check_share(&store, &confirmations, &secret).unwrap(); + assert!(check.needs_confirmation()); + set_shared( + &store, + &confirmations, + &secret, + true, + Some(check.urls), + || { + device.set_shared(&store, &secret, true); + Ok(()) + }, + ) + .unwrap(); + assert!(confirmed_here(&store, &confirmations, &secret)); + + // B turns sharing off and on again (confirming on B). A must ask its + // user again: the confirmation was given for the revoked decision. + sync(&device.ops, &other); + let ops = [ + device_b.set_shared(&other, &secret, false), + device_b.set_shared(&other, &secret, true), + ] + .concat(); + sync(&ops, &store); + assert!( + !confirmed_here(&store, &confirmations, &secret), + "held back again" + ); + let check = check_share(&store, &confirmations, &secret).unwrap(); + assert!(check.needs_confirmation()); + assert!( + !ShareConfirmations::open(temp.path().join("confirmations.json")).is_confirmed( + &share_card(&store, &secret).unwrap().unwrap(), + store.share(&secret).unwrap().as_ref() + ), + "the superseded confirmation is dropped from the file" + ); + + // A confirms again (no new decision: B's is in force) ... + confirm_shown(&store, &confirmations, &secret); + assert!(confirmed_here(&store, &confirmations, &secret)); + // ... and B only turns sharing off: when it is shared again later + // (from either device), A asks again. + let off = device_b.set_shared(&other, &secret, false); + sync(&off, &store); + assert!(shared_ids(&store, &confirmations).is_empty()); + let check = check_share(&store, &confirmations, &secret).unwrap(); + assert!(check.needs_confirmation(), "sharing again asks again"); + + // Shared again on B and confirmed on A; then B unsubscribes, subscribes + // again and shares: a new decision, A asks again. + let on = device_b.set_shared(&other, &secret, true); + sync(&on, &store); + confirm_shown(&store, &confirmations, &secret); + assert!(confirmed_here(&store, &confirmations, &secret)); + device_b.unsubscribe(&other, &secret); + device_b.subscribe(&other, SECRET_URL, "Members Only"); + let on = device_b.set_shared(&other, &secret, true); + assert!(!on.is_empty()); + sync(&device_b.ops, &store); + assert!(!confirmed_here(&store, &confirmations, &secret)); + + // A pending confirmation (the decision is not written yet) covers + // nothing until a newer share decision exists. + let fresh = device.subscribe( + &store, + "https://feeds.example.test/vip.xml?key=0123456789abcdef", + "VIP", + ); + let check = check_share(&store, &confirmations, &fresh).unwrap(); + confirmations + .confirm(&fresh, check.urls, store.share(&fresh).unwrap().as_ref()) + .unwrap(); + assert!( + !check_share(&store, &confirmations, &fresh) + .unwrap() + .confirmed + ); + device.set_shared(&store, &fresh, true); + assert!( + confirmed_here(&store, &confirmations, &fresh), + "covers the next decision" + ); } #[test] @@ -467,8 +598,7 @@ async fn two_nodes() { assert!(c.dht.search("members only", 10).await.unwrap().is_empty()); // Confirming exactly the URLs shown publishes the held-back podcast. - let check = check_share(&store, &confirmations, &secret).unwrap(); - confirmations.confirm(&secret, check.urls).unwrap(); + confirm_shown(&store, &confirmations, &secret); let report = reconcile(&a.dht, Some(Arc::clone(&store)), Arc::clone(&confirmations)).await; assert_eq!(publication(&report, &secret), Some(Publication::Published)); wait_for("the confirmed card", async || { @@ -506,12 +636,7 @@ async fn two_nodes() { // Without a podcast store (it failed to open) every own card is revoked. device.subscribe(&store, SECRET_URL, "Members Only Show"); device.set_shared(&store, &secret, true); - confirmations - .confirm( - &secret, - check_share(&store, &confirmations, &secret).unwrap().urls, - ) - .unwrap(); + confirm_shown(&store, &confirmations, &secret); let report = reconcile(&a.dht, Some(Arc::clone(&store)), Arc::clone(&confirmations)).await; assert_eq!(publication(&report, &secret), Some(Publication::Published)); wait_for("the republished card", async || {