Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 37 additions & 4 deletions core/crates/sync/src/adapters/categories.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
// The categories this device syncs (0054, Rules for both providers): a kind turned off sends nothing and takes nothing,
// and the password switch does the same for envelopes. What a pull passed over while a kind was off is read again
// once it is on, so a deletion pulled meanwhile lands then.
// and the password switch does the same for envelopes. An envelope also goes with its record's kind (0114, An envelope
// follows its record's category). What a pull passed over while a kind was off is read again once it is on, so a
// deletion pulled meanwhile lands then.

use std::collections::BTreeSet;

use tablepro_records::Kind;
use tablepro_records::record_id::parse_envelope_id;

use crate::api::control::SyncCategories;
use crate::api::ids::KindName;
Expand All @@ -15,6 +17,8 @@ pub struct DeviceCategories {
passwords: bool,
// A kind this build does not know is held by id for a newer build (0054, Rules for both providers).
unknown: bool,
// The kinds the person turned off, whose records keep their secrets on the device with them.
kept: BTreeSet<Kind>,
}

// Everything syncs until the app says otherwise.
Expand All @@ -24,15 +28,18 @@ impl Default for DeviceCategories {
off: BTreeSet::new(),
passwords: true,
unknown: true,
kept: BTreeSet::new(),
}
}
}

impl From<&SyncCategories> for DeviceCategories {
fn from(categories: &SyncCategories) -> Self {
// A kind this build does not know has no store to turn off.
let off: BTreeSet<Kind> = categories.off.iter().filter_map(|kind| kind.known()).collect();
Self {
// A kind this build does not know has no store to turn off.
off: categories.off.iter().filter_map(|kind| kind.known()).collect(),
kept: off.clone(),
off,
passwords: categories.passwords,
unknown: true,
}
Expand All @@ -51,6 +58,14 @@ impl DeviceCategories {
!self.off.contains(&kind)
}

// Whether the record at `record_id` syncs: as its kind does, and for an envelope only while the person has its
// record's kind on too. A kind off only until the device can seal its records leaves their envelopes as they were.
pub fn syncs_record(&self, kind: Kind, record_id: &str) -> bool {
self.syncs(kind)
&& (kind != Kind::SecretEnvelope
|| parse_envelope_id(record_id).is_none_or(|(parent, _, _)| !self.kept.contains(&parent)))
}

// Every kind off but the key objects, and the passwords with them: the personal scope of a device whose personal
// provider is not TablePro Sync. A kind off is read again once it is on, so turning personal sync on later takes
// what came meanwhile (0054, Providers; Rules for both providers).
Expand All @@ -59,6 +74,7 @@ impl DeviceCategories {
off: Kind::ALL.into_iter().filter(|kind| !kind.is_key()).collect(),
passwords: false,
unknown: false,
kept: BTreeSet::new(),
}
}

Expand Down Expand Up @@ -105,6 +121,23 @@ mod tests {
assert!(DeviceCategories::default().syncs(Kind::SecretEnvelope));
}

#[test]
fn an_envelope_goes_with_its_record_s_kind_as_the_person_set_it() {
let profiles_off = DeviceCategories::from(&SyncCategories {
off: vec![KindName::of(Kind::SshProfile)],
passwords: true,
});
let profile = "ssh_profile/6F1C2A9E-0B4D-4C8E-9A51-3D7E2B1F0C01/ssh_password";
let connection = "connection/6F1C2A9E-0B4D-4C8E-9A51-3D7E2B1F0C02/password";

assert!(!profiles_off.syncs_record(Kind::SecretEnvelope, profile));
assert!(profiles_off.syncs_record(Kind::SecretEnvelope, connection));
assert!(!profiles_off.syncs_record(Kind::SshProfile, "6F1C2A9E-0B4D-4C8E-9A51-3D7E2B1F0C01"));
assert!(profiles_off.syncs_record(Kind::SecretEnvelope, "an id this build does not read"));
let unsealed = DeviceCategories::default().without_personal_data();
assert!(unsealed.syncs_record(Kind::SecretEnvelope, connection));
}

#[test]
fn keys_only_turns_off_every_kind_but_the_key_objects() {
let categories = DeviceCategories::keys_only();
Expand Down
46 changes: 27 additions & 19 deletions core/crates/sync/src/adapters/envelopes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,8 @@ impl EnvelopeAdapter {
}

// The parents whose store holds a copy a restore left and the refill could not replace, which the engine holds
// under its local id and never sends (0114, A store in refill).
// under its local id and never sends (0114, A store in refill). A kind that only owes its refill is no sign of a
// restore, as a store the state never saw owes one too, and its refill runs in the pull before anything goes up.
async fn restored(&self) -> Result<HashSet<(Kind, Uuid)>, AdapterError> {
let mut txn = self.state.begin().await.map_err(state_error)?;
let rows = txn
Expand Down Expand Up @@ -312,16 +313,21 @@ impl EnvelopeAdapter {
}
};
let dest = destination(reference.parent, &reference.secret, fields);
let restored = reading.restored.contains(&(reference.parent, reference.parent_id));
let Some(held) = held else {
// Held back while its record points elsewhere than it was sealed for, or while its landing is not settled,
// which is no deletion (0114, A pulled destination does not take a stored secret). Removed here otherwise:
// its envelope goes, as the diff reads a base with no record.
let sealed_for = match base {
Some(base) => self.known(envelope, record_id, base).await,
None => None,
};
let held_back =
sealed_for.is_some_and(|known| known.dest != dest) || reading.landings.contains_key(record_id);
// Held back while its record points elsewhere than it was sealed for, while its landing is not settled, or
// while its record is a copy a restore left, none of which is the person's removal (0114, A pulled
// destination does not take a stored secret; A store in refill). Removed here otherwise: its envelope goes,
// as the diff reads a base with no record.
let held_back = restored
|| reading.landings.contains_key(record_id)
|| match base {
Some(base) => self
.known(envelope, record_id, base)
.await
.is_some_and(|known| known.dest != dest),
None => false,
};
return match base.filter(|_| held_back) {
// Read as the copy the server holds, so nothing goes up and a newer copy still lands.
Some(base) => Listed::Copy(base.clone()),
Expand All @@ -332,9 +338,7 @@ impl EnvelopeAdapter {
// (`parent_landing`), so one held beside another destination than its envelope's was set there by the person,
// or they moved the record here. A copy a restore left is no move of theirs: until the refill replaces it, only
// a secret the person changed here goes up, and the rest stays as the server holds it, not sealed again.
if reading.restored.contains(&(reference.parent, reference.parent_id))
&& !self.changed_here((envelope, record_id), &held, base).await
{
if restored && !self.changed_here((envelope, record_id), &held, base).await {
return base.map_or(Listed::Unlisted, |base| Listed::Copy(base.clone()));
}
match self
Expand All @@ -346,8 +350,8 @@ impl EnvelopeAdapter {
}
}

// The secret differs from the one its envelope synced. Not when the envelope is gone or does not open now, as after
// a re-seal that never went up, since nothing then tells.
// The secret differs from the one its envelope synced. Not when the envelope is gone or does not open now, since
// nothing then tells.
async fn changed_here(
&self,
(envelope, record_id): (&EnvelopeId, &str),
Expand Down Expand Up @@ -893,7 +897,7 @@ impl RecordAdapter for EnvelopeAdapter {
}
}
for record_id in bases.keys().filter(|record_id| !listed.contains(*record_id)) {
if !gone(self, &parents, record_id) {
if !gone(self, &parents, &reading.restored, record_id) {
out.unreadable.push(record_id.clone());
}
}
Expand Down Expand Up @@ -1072,13 +1076,17 @@ async fn stored(

// Whether a base the parents' secrets did not list stands for a secret removed here: its record is gone, or the
// record is here and the device keeps that secret kind but no longer holds it. A kind this device does not keep, a
// record it cannot read and an id it does not read are sent back unchanged, never deleted.
fn gone(adapter: &EnvelopeAdapter, parents: &Parents, record_id: &str) -> bool {
// record it cannot read, a record a restore left or lost and an id it does not read are sent back unchanged, never
// deleted.
fn gone(adapter: &EnvelopeAdapter, parents: &Parents, restored: &HashSet<(Kind, Uuid)>, record_id: &str) -> bool {
let Some((parent, parent_id, secret)) = parse_envelope_id(record_id) else {
return false;
};
let key = (parent, parent_id.to_owned());
if adapter.parent(parent).is_none() || parents.unreadable.contains(&key) {
if adapter.parent(parent).is_none()
|| parents.unreadable.contains(&key)
|| parse_uuid(parent_id).is_some_and(|id| restored.contains(&(parent, id)))
{
return false;
}
!parents.held.contains(&key) || adapter.keeps(parent, &secret)
Expand Down
1 change: 1 addition & 0 deletions core/crates/sync/src/keys/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ use crate::state::integrity::{Reading, rebuild_shown};

pub use account::{AccountObjectsPlan, HeldDeviceKeys, KeptDevice, OwnAccount, ResetKeys};
pub use personal::{CurrentPersonal, ScopeKeyPlan};
pub(crate) use personal_envelopes::keep_taken_envelope;
pub use pins::{IkStanding, PinChange};
pub use replaced_row::{erase_left_sign_in, open_service_state};
// The restore tests' state in memory and the vectors' world, for the unit tests of other modules.
Expand Down
38 changes: 27 additions & 11 deletions core/crates/sync/src/keys/personal_envelopes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,8 @@ impl KeyService {
let key = self.personal_key(txn.as_mut(), KeyPurpose::Personal, kv).await?;
let dest = to_json_value(dest)?;
let plaintext = envelope_plaintext(secret.expose_secret(), &dest, None)?;
// The floor waits for the server to take this copy (`keep_taken_envelope`): a copy that never goes up leaves
// the one the server holds opening.
let sealed = seal_envelope(
&key,
&self.origin,
Expand All @@ -110,17 +112,6 @@ impl KeyService {
kv,
&plaintext,
)?;
let record_id = envelope.to_wire();
let held = self.held_envelope(txn.as_mut(), &record_id).await?;
if held.is_none_or(|held| held < kv) {
txn.put(Row::KeyEnvelope(KeyEnvelopeRow {
scope: ScopeName::Personal,
record_id,
kv,
}))
.await?;
}
txn.commit().await?;
sealed_fields(&sealed)
}

Expand Down Expand Up @@ -220,6 +211,31 @@ impl KeyService {
}
}

// The server took this device's copy of a personal envelope, so the copy held is that one: the envelope's floor moves up
// to its version in the commit that takes the answer, and never down (0056, Rollback, Per envelope).
pub(crate) async fn keep_taken_envelope(
txn: &mut dyn StateTxn,
record_id: &str,
fields: &Value,
) -> Result<(), SyncError> {
let Ok(sealed) = parse_fields(fields) else {
return Ok(());
};
let key = RowKey::KeyEnvelope(ScopeName::Personal, record_id.to_owned());
if let Some(Row::KeyEnvelope(row)) = txn.get(&key).await?
&& row.kv >= sealed.kv
{
return Ok(());
}
txn.put(Row::KeyEnvelope(KeyEnvelopeRow {
scope: ScopeName::Personal,
record_id: record_id.to_owned(),
kv: sealed.kv,
}))
.await?;
Ok(())
}

fn to_json_value(value: &Value) -> Result<JsonValue, SyncError> {
let text = serde_json::to_vec(value).map_err(|_| SyncError::Malformed { what: "JSON value" })?;
Ok(json::parse(&text)?)
Expand Down
11 changes: 6 additions & 5 deletions core/crates/sync/src/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -803,17 +803,18 @@ impl ServiceSync {
let mut plan = MovePlan::default();
for adapter in self.adapters.in_scope(ScopeName::Personal) {
let kind = adapter.kind();
let on = categories.syncs(kind);
let local = adapter.records(ScopeName::Personal).await?;
// Before the keys exist nothing is sealed yet, so the secrets the move will seal read as held.
if kind == Kind::SecretEnvelope {
let held = u64::try_from(local.unreadable.len()).unwrap_or(u64::MAX);
match on {
true => plan.secrets_to_seal += held,
false => plan.turned_off += held,
for id in &local.unreadable {
match categories.syncs_record(kind, id) {
true => plan.secrets_to_seal += 1,
false => plan.turned_off += 1,
}
}
}
for record in local.records {
let on = categories.syncs_record(kind, &record.record_id);
match (record.standing, on, kind) {
(Standing::Syncs, true, Kind::SecretEnvelope) => plan.secrets_to_seal += 1,
(Standing::Syncs, true, _) => plan.records += 1,
Expand Down
24 changes: 17 additions & 7 deletions core/crates/sync/src/service/pull/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -284,7 +284,11 @@ fn keep_repairs(pull: &Pull, locals: &HashMap<usize, LocalIndex>, writes: &mut P
.get(index)
.and_then(|local| local.records.get(&record.record_id))
.is_some_and(|stored| stored.standing == Standing::LocalOnly);
!kept_here && record.kind.known().is_some_and(|kind| pull.categories.syncs(kind))
!kept_here
&& record
.kind
.known()
.is_some_and(|kind| pull.categories.syncs_record(kind, &record.record_id))
});
}

Expand Down Expand Up @@ -748,9 +752,14 @@ impl ServiceSync {
arrival.marked(&key, marker);
}
// A kind this device turned off takes nothing of its store, so the snapshot that follows turning it on
// settles what came meanwhile, deletions included (0054, Rules for both providers). Only a refill reads it
// now, for what the refill decides that the store need not take yet.
if let Some(kind) = record.kind.known().filter(|kind| !pull.categories.syncs(*kind)) {
// settles what came meanwhile, deletions included (0054, Rules for both providers). An envelope goes with its
// record's kind, which reads it again the same way (0114). Only a refill reads it now, for what the refill
// decides that the store need not take yet.
if let Some(kind) = record
.kind
.known()
.filter(|kind| !pull.categories.syncs_record(*kind, &record.record_id))
{
if pull.cut.is_some() || pull.pull_wins.contains(&kind) {
to_settle.push(record);
}
Expand Down Expand Up @@ -987,15 +996,16 @@ impl ServiceSync {
.deferred
.get(&key)
.is_some_and(|deferred| deferred.fields.is_some());
if judgement == Judgement::PullWins && kept_copy && pull.categories.syncs(kind) {
let on = pull.categories.syncs_record(kind, &key.record_id);
if judgement == Judgement::PullWins && kept_copy && on {
judgement = Judgement::Merge;
}
// An open conflict waits for the person in a personal record too, whatever pass brings it (0104).
if judgement == Judgement::Merge && inputs.conflicts.contains_key(&key) {
judgement = Judgement::Contest;
}
let stored = local.and_then(|local| local.records.get(&key.record_id));
if !pull.categories.syncs(kind) {
if !on {
Self::while_off(&key, kind, judgement, base, stored, &record, writes);
continue;
}
Expand Down Expand Up @@ -1676,7 +1686,7 @@ impl ServiceSync {
_ => None,
})
.filter(|key| {
(key.kind == KindName::of(sealed) && categories.syncs(sealed))
(key.kind == KindName::of(sealed) && categories.syncs_record(sealed, &key.record_id))
|| (records && is_sealed(scope, &key.kind))
})
.collect())
Expand Down
Loading
Loading