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
1 change: 1 addition & 0 deletions apple/changelog.d/4823.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Ask Another Device… no longer waits until the request expires on a Mac a key change left out.
6 changes: 6 additions & 0 deletions core/crates/sync/src/api/key_flows.rs
Original file line number Diff line number Diff line change
Expand Up @@ -274,6 +274,12 @@ pub trait ApprovalFlows: Send + Sync {
let _ = request;
unimplemented("keys.resume_approval")
}

// N's own session runs, from its request until its approval merges or the session ends. Its steps and the approval
// arrive only in the personal scope, which a locked device reads for nothing else.
async fn asks_for_approval(&self) -> Result<bool, SyncError> {
Ok(false)
}
}

// K7-2: Rotation, Removing a device, Recovery.
Expand Down
6 changes: 6 additions & 0 deletions core/crates/sync/src/keys/approval/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,12 @@ impl ApprovalFlows for KeyService {
}
self.drive(&mut record).await
}

async fn asks_for_approval(&self) -> Result<bool, SyncError> {
let _serial = self.serialized().await;
let mut txn = self.begin().await?;
self.own_session_runs(txn.as_mut()).await
}
}

// A key change set whose push failed this way may have applied, or goes through once tried again, so it is queued for
Expand Down
10 changes: 10 additions & 0 deletions core/crates/sync/src/keys/approval/steps.rs
Original file line number Diff line number Diff line change
Expand Up @@ -160,6 +160,16 @@ impl KeyService {
}))
}

// A confirmed N waits for the approval past `expires_at`, since the server may have taken it before then.
pub(super) async fn own_session_runs(&self, txn: &mut dyn StateTxn) -> Result<bool, SyncError> {
let now = self.now_us();
Ok(self.session_records(txn).await?.iter().any(|record| {
record.role == Role::NewDevice
&& record.live()
&& (record.state == tablepro_keys::sas::SessionState::Confirmed || now < record.expires_at_us)
}))
}

pub(super) async fn revoke_owed(&self, txn: &mut dyn StateTxn) -> Result<bool, SyncError> {
Ok(self
.session_records(txn)
Expand Down
19 changes: 16 additions & 3 deletions core/crates/sync/src/service/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,8 @@ struct PassCtx {
adopt: Vec<(ScopeName, EpochId, Vec<LineageEpoch>)>,
// Nothing personal syncs while the device is locked, and no secret goes up under a stopped or ended key.
locked: bool,
// A locked device that asks to be approved again pulls the personal scope for its session's steps.
asking: bool,
approved: bool,
// This device's own key state says it holds its keys, whatever the server says: only then is an envelope checked
// or sealed.
Expand Down Expand Up @@ -976,6 +978,7 @@ impl ServiceSync {
pushed_back: None,
adopt: Vec::new(),
locked: false,
asking: false,
approved,
keys_ready: false,
named,
Expand Down Expand Up @@ -1093,6 +1096,14 @@ impl ServiceSync {
self.hooks.refresh(lock, stopped, ended);
ctx.locked = self.hooks.locked().is_some();
ctx.keys_ready = !ctx.locked && matches!(state, Ok(KeyState::Approved { .. }));
ctx.asking = ctx.locked
&& match self.keys.asks_for_approval().await {
Ok(asking) => asking,
Err(error) => {
tracing::debug!(code = error.code(), "a locked device's session could not be read");
false
}
};
Ok(())
}

Expand Down Expand Up @@ -1147,16 +1158,18 @@ impl ServiceSync {
Ok(())
}

// Personal and history calls need this device's key, and nothing personal syncs on a locked device. The history
// scope takes no call before approval (0051, Whole-request refusals).
// Personal and history calls need this device's key, and nothing personal syncs on a locked device. One that asks to
// be approved again still pulls the personal scope, since its session's steps and the approval arrive there and
// nowhere else (0056, Rotation, A device left out). It opens no record there: each waits, or is read again once it
// can. The history scope takes no call before approval (0051, Whole-request refusals).
fn reachable(&self, ctx: &PassCtx) -> Vec<ScopeInfo> {
let locked = ctx.locked;
ctx.body
.scopes
.iter()
.filter(|info| match info.scope {
ScopeName::Team(_) => !self.team_library_off(),
ScopeName::Personal => ctx.keyed && !locked,
ScopeName::Personal => ctx.keyed && (!locked || ctx.asking),
ScopeName::History => {
ctx.mode == ServiceMode::Personal && ctx.keyed && !locked && info.approved == Some(true)
}
Expand Down
16 changes: 13 additions & 3 deletions core/crates/sync/src/service/pull/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,10 @@ struct Pull {
seen: HashSet<(String, String)>,
// A locked or unapproved device holds no key to check an envelope with: it keeps each one until it can.
can_open: bool,
// Such a device reads only the personal scope's key objects, whatever the server serves it: it takes no record, no
// refill and no held record again, counts no kind as read and settles no base, store or epoch, so the first pull
// once it can open reads the records again (0056, A locked device; 0051, Before approval).
keys_only: bool,
// The bytes of key objects and envelopes a snapshot keeps until it is caught up.
buffered: usize,
// The kinds this build reads in the scope, which the row keeps once a snapshot read them all.
Expand Down Expand Up @@ -394,10 +398,11 @@ impl ServiceSync {
&& waited.get(&scope) != Some(&key_mark(&self.state, scope, can_open, rebuilding).await?);
// A build that reads a kind the last pull did not fetches again what it held for it (0054, Rules).
// A kind this device turned off is not read, so turning it on reads it again the same way.
let keys_only = scope == ScopeName::Personal && !can_open;
let mut reading: Vec<KindName> = adapters
.iter()
.map(|adapter| adapter.kind())
.filter(|kind| categories.syncs(*kind))
.filter(|kind| categories.syncs(*kind) && !keys_only)
.map(KindName::of)
.collect();
reading.sort();
Expand All @@ -416,6 +421,7 @@ impl ServiceSync {
held_envelopes: Vec::new(),
seen: HashSet::new(),
can_open,
keys_only,
buffered: 0,
reading,
new_waits: false,
Expand Down Expand Up @@ -445,7 +451,7 @@ impl ServiceSync {
if stored.as_ref() != Some(&row) {
self.commit_page(PageWrites::default(), Some(&row)).await?;
}
if !pull.snapshot {
if !pull.snapshot && !pull.keys_only {
self.retry_held(ctx, &mut pull, &adapters).await?;
}
let caught_up = self.pull_pages(ctx, &mut pull, &adapters, &mut row).await?;
Expand Down Expand Up @@ -712,6 +718,9 @@ impl ServiceSync {
// Sealed personal records in order since the last run of key objects, each judged at its place.
let mut sealed: Vec<(PulledRecord, Place)> = Vec::new();
for mut record in records {
if pull.keys_only && family(pull.scope, &record.kind).is_none() {
continue;
}
pull.seen
.insert((record.kind.as_str().to_owned(), record.record_id.clone()));
// A personal record is read only sealed, and only by a pull that can open it (0114). A kind turned off is read
Expand Down Expand Up @@ -1494,7 +1503,7 @@ impl ServiceSync {
self.take_sealed(pull, adapters, sealed, &mut writes, &mut opened)
.await?;
// Before approval a personal pull serves key objects only: it settles no base, store or epoch.
let whole = pull.scope != ScopeName::Personal || info.approved == Some(true);
let whole = (pull.scope != ScopeName::Personal || info.approved == Some(true)) && !pull.keys_only;
if whole {
self.refill_from_floors(pull, adapters, &mut writes).await?;
}
Expand Down Expand Up @@ -1600,6 +1609,7 @@ impl ServiceSync {
held_envelopes: Vec::new(),
seen: HashSet::new(),
can_open: self.history_opens_now().await,
keys_only: false,
buffered: 0,
reading: Vec::new(),
new_waits: false,
Expand Down
58 changes: 57 additions & 1 deletion core/crates/sync/tests/core_engine/approval.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// device).

use tablepro_keys::encoding::TeamId;
use tablepro_sync::api::key_flows::{ApprovalFlows, KeyState, SessionPhase, TeamFlows};
use tablepro_sync::api::key_flows::{ApprovalFlows, KeyState, LockCause, SessionPhase, TeamFlows};
use tablepro_sync::api::scopes::Role;
use tablepro_sync_testing::FakeServer;

Expand Down Expand Up @@ -80,3 +80,59 @@ async fn an_approval_confirmed_before_it_arrived_is_taken_by_the_pass_after_a_re
n.key_state().await
);
}

// Replace Recovery Key leaves N out, so N locks and asks again from A. The server no longer approves the key device N
// holds, so its passes read the personal scope's key objects only: A's `nonce` step, then its approval (0056, Rotation,
// A device left out; 0051, Before approval).
#[tokio::test]
async fn a_device_a_rotation_left_out_asks_again_and_is_approved() {
let server = FakeServer::new();
let account = new_account();
let a = Device::new(&server, account, "dev_a").await;
let recovery = a.genesis().await;
let n = Device::new(&server, account, "dev_n").await;
n.pass().await;
let first = n.keys.request_approval().await.unwrap();
a.pass().await;
a.keys.choose_request(first).await.unwrap();
n.pass().await;
n.keys.approval_session(first).await.unwrap();
a.pass().await;
a.keys.approval_session(first).await.unwrap();
a.keys.confirm_session(first).await.unwrap();
n.pass().await;
n.keys.confirm_session(first).await.unwrap();
n.approve().await;
n.pass().await;
a.replace(recovery).await;
a.pass().await;
server.unapprove(&n.row);
n.pass().await;
let locked = n.key_state().await;

let request = n.keys.request_approval().await.unwrap();
a.pass().await;
a.keys.choose_request(request).await.unwrap();
n.pass().await;
let n_words = n.keys.approval_session(request).await.unwrap().phase;
a.pass().await;
let a_words = a.keys.approval_session(request).await.unwrap().phase;
a.keys.confirm_session(request).await.unwrap();
n.pass().await;
let approved = n.keys.confirm_session(request).await.unwrap().phase;

assert_eq!(
locked,
KeyState::Locked {
cause: LockCause::LeftOutOfRotation
}
);
assert!(matches!(n_words, SessionPhase::Compare { .. }), "{n_words:?}");
assert_eq!(n_words, a_words);
assert_eq!(approved, SessionPhase::Approved);
assert!(
matches!(n.key_state().await, KeyState::Approved { av, .. } if av.get() == 2),
"{:?}",
n.key_state().await
);
}
23 changes: 21 additions & 2 deletions core/crates/sync/tests/engine/harness.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ use tablepro_sync::api::error::{AdapterError, StateError, SyncError};
use tablepro_sync::api::ids::{ChangeTag, DeviceRowId, IdempotencyKey, KindName, RecordKey, ScopeName};
use tablepro_sync::api::key_flows::{
AccountDevice, AccountFlows, ApprovalFlows, ApprovalRequest, ArrivalOrder, DeviceFlows, KeyApplied, KeyArrival,
KeyChangeSet, KeyState, OpenedEnvelope, OpenedRecords, PushBackVerdict, RecordBody, RecordIds, RecordToOpen,
RecordToSeal, ResetFlows, RestoreFlows, Roster, SealedOut, StopAction, StopFlows, TeamFlows,
KeyChangeSet, KeyState, LockCause, OpenedEnvelope, OpenedRecords, PushBackVerdict, RecordBody, RecordIds,
RecordToOpen, RecordToSeal, ResetFlows, RestoreFlows, Roster, SealedOut, StopAction, StopFlows, TeamFlows,
};
use tablepro_sync::api::scopes::ScopesAnswer;
use tablepro_sync::api::state::{
Expand Down Expand Up @@ -568,6 +568,9 @@ pub struct KeyLog {
newest: Mutex<BTreeMap<String, u32>>,
waiting_for_approval: AtomicBool,
rebuilding: AtomicBool,
// A lock the flows report, and whether this device's own approval session runs meanwhile.
locked: Mutex<Option<LockCause>>,
asking: AtomicBool,
// The device's key, which the builder sets.
proof: Mutex<Option<DpopKey>>,
// The key devices the account certifies, as another device's approval or removal leaves them.
Expand Down Expand Up @@ -607,6 +610,12 @@ impl KeyLog {
self.waiting_for_approval.store(false, Ordering::SeqCst);
}

// Locked for `cause`, asking to be approved again when `asking`; `None` clears the lock as an approval does.
pub fn lock_for(&self, cause: Option<LockCause>, asking: bool) {
*lock(&self.locked) = cause;
self.asking.store(asking, Ordering::SeqCst);
}

// The personal keys this device holds: PK at each version up to the newest, a rotation's version record included.
pub fn personal(&self) -> TestPersonalKeys {
let applied = lock(&self.newest)
Expand Down Expand Up @@ -634,6 +643,9 @@ impl KeyLog {
}

fn can_open_records(&self) -> Result<(), SyncError> {
if let Some(cause) = *lock(&self.locked) {
return Err(SyncError::Locked { cause });
}
if self.waiting_for_approval.load(Ordering::SeqCst) || self.rebuilding.load(Ordering::SeqCst) {
return Err(SyncError::NotAllowed {
what: "open a personal record before holding the personal key",
Expand Down Expand Up @@ -752,6 +764,9 @@ impl KeyLog {
#[async_trait]
impl AccountFlows for KeyLog {
async fn key_state(&self) -> Result<KeyState, SyncError> {
if let Some(cause) = *lock(&self.locked) {
return Ok(KeyState::Locked { cause });
}
Ok(if self.waiting_for_approval.load(Ordering::SeqCst) {
KeyState::NeedsApproval { request: None }
} else {
Expand Down Expand Up @@ -849,6 +864,10 @@ impl ApprovalFlows for KeyLog {
async fn approval_requests(&self) -> Result<Vec<ApprovalRequest>, SyncError> {
Ok(lock(&self.requests).clone())
}

async fn asks_for_approval(&self) -> Result<bool, SyncError> {
Ok(self.asking.load(Ordering::SeqCst))
}
}

#[async_trait]
Expand Down
81 changes: 78 additions & 3 deletions core/crates/sync/tests/engine/keys.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,16 @@ use tablepro_records::Kind;
use tablepro_sync::api::control::SyncControl;
use tablepro_sync::api::error::SyncError;
use tablepro_sync::api::ids::{EpochId, KindName, ScopeName};
use tablepro_sync::api::key_flows::{ArrivalOrder, KeyChangeSet, PushBackVerdict};
use tablepro_sync::api::key_flows::{ArrivalOrder, KeyChangeSet, LockCause, PushBackVerdict};
use tablepro_sync::api::scopes::Role;
use tablepro_sync::api::state::{HeldReason, KeyPendingRow, KeyVersionRow, KeyVersionState, PendingFlow, Row, RowKey};
use tablepro_sync::api::transport::{ChangeOutcome, DpopKey, TransportError};
use tablepro_sync::api::transport::{ChangeOp, ChangeOutcome, DpopKey, TransportError};
use tablepro_sync_testing::FakeServer;
use uuid::Uuid;

use super::harness::{
ACCOUNT, Device, DeviceBuilder, KeyEvent, KeyLog, MemoryAdapter, StoreFile, account, connection, id, write,
ACCOUNT, Device, DeviceBuilder, KeyEvent, KeyLog, MemoryAdapter, StoreFile, account, connection, id, personal,
write,
};

fn version_id(version: u32) -> String {
Expand Down Expand Up @@ -748,3 +749,77 @@ async fn a_pass_whose_push_fails_keeps_the_longer_wait_a_key_flow_was_told() {

assert_eq!(passed.err(), Some(limited));
}

// A locked device that asks to be approved again reads the personal scope for its session's key objects only. The
// server, which still approves the key device it holds, serves a password's deletion there too, and it waits until the
// lock clears (0056, A locked device).
#[tokio::test]
async fn a_locked_device_that_asks_again_takes_no_envelope_until_the_lock_clears() {
let server = FakeServer::new();
let other = Device::new(&server, "dev_other").await;
rotate(&other, 1).await;
seal(&other, 1, 1).await;
let keys = Arc::new(KeyLog::default());
let secrets = envelopes();
let mini = DeviceBuilder::new(&server, "dev_mini")
.keys(Arc::clone(&keys))
.adapter(ScopeName::Personal, Arc::clone(&secrets))
.build()
.await;
mini.sync().await;
let taken = secrets.get(&envelope_id(1));
keys.lock_for(Some(LockCause::Unanchored), true);
let stored = server.stored(personal(), "secret_envelope", &envelope_id(1)).unwrap();
let mut deletion = write("secret_envelope", &envelope_id(1), Some(stored.change_tag()), json!({}));
deletion.op = ChangeOp::Delete;
let deleted = other.push_raw(ScopeName::Personal, vec![deletion]).await;

mini.sync().await;
let while_locked = secrets.get(&envelope_id(1));
keys.lock_for(None, false);
mini.sync().await;

assert!(matches!(deleted[0], ChangeOutcome::Applied { .. }), "{deleted:?}");
assert_eq!(taken, Some(sealed(1)));
assert_eq!(while_locked, Some(sealed(1)));
assert_eq!(secrets.get(&envelope_id(1)), None);
}

// A password the keys took and only the store refused waits on a locked device that asks to be approved again: its pull
// takes no held record again, and the password lands once the lock clears (0056, A locked device).
#[tokio::test]
async fn an_envelope_the_store_refused_waits_while_the_device_is_locked_and_lands_once_the_lock_clears() {
let server = FakeServer::new();
let (mac_secrets, other_secrets) = (envelopes(), envelopes());
let keys = Arc::new(KeyLog::default());
let mac = DeviceBuilder::new(&server, "dev_mac")
.personal_key_unserved()
.keys(Arc::clone(&keys))
.adapter(ScopeName::Personal, Arc::clone(&mac_secrets))
.build()
.await;
let other = DeviceBuilder::new(&server, "dev_other")
.personal_key_unserved()
.adapter(ScopeName::Personal, Arc::clone(&other_secrets))
.build()
.await;
rotate(&other, 1).await;
mac_secrets.put(&envelope_id(1), sealed(1));
mac.sync().await;
other.sync().await;
let changed = json!({"suite": "tp1", "kv": 1, "nonce": "n2", "ct": "c2"});
other_secrets.put(&envelope_id(1), changed.clone());
other.sync().await;
mac_secrets.hide(&envelope_id(1));
mac.sync().await;
keys.lock_for(Some(LockCause::PersonalStopped), true);
mac_secrets.show(&envelope_id(1));

mac.sync().await;
let while_locked = mac_secrets.get(&envelope_id(1));
keys.lock_for(None, false);
mac.sync().await;

assert_eq!(while_locked, Some(sealed(1)));
assert_eq!(mac_secrets.get(&envelope_id(1)), Some(changed));
}
Loading
Loading