use super::super::{
DeRecChannelStore, DeRecEvent, DeRecSecretStore, DeRecShareStore, DeRecUserSecretStore,
SecretValue, UnpairAck,
types::{
ChannelRecord, ChannelStatus, HelperChannel, HelperInfo, ReplicaMember, ReplicaRole,
Replicas, Secret, Share, UserSecrets,
},
};
use crate::protocol::context::Local;
use crate::protocol::stores::{StoreSet, Stores};
use crate::{
Result,
types::{ChannelId, SharedKey},
};
use std::collections::HashSet;
use crate::extensions::channel_store::ChannelStoreExt as _;
#[cfg(target_arch = "wasm32")]
use crate::interop::wasm::now_secs;
#[cfg(not(target_arch = "wasm32"))]
use crate::utils::now_secs;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum RestoreError {
#[error("user-secret snapshot already exists for secret_id")]
AlreadyRestored,
#[error("restore blocked by pre-existing channels at canonical ids")]
Conflict(Vec<ChannelId>),
#[error("recovered Secret is internally inconsistent: {0}")]
Invariant(&'static str),
}
#[cfg_attr(feature = "logging", tracing::instrument(skip_all))]
pub(in crate::protocol) async fn restore<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
secret: &Secret,
recovered_version: u32,
) -> Result<Vec<DeRecEvent>> {
let (canonical_ids, existing_channels) = check_preconditions(stores, local, secret).await?;
write_helper_channels(stores, local, &secret.helpers, recovered_version).await?;
if let Some(group) = secret.replicas.as_ref().filter(|g| !g.members.is_empty()) {
write_replica_channels(stores, local, group).await?;
}
commit_snapshot(stores, local, secret, recovered_version).await?;
let events = unpair_recovery_channels(stores, local, &existing_channels, &canonical_ids).await;
#[cfg(feature = "logging")]
tracing::info!(
local.secret_id,
helpers_restored = secret.helpers.len(),
replicas_restored = secret.replicas.as_ref().map_or(0, |g| g.members.len()),
user_secrets_restored = secret.secrets.len(),
"DeRecProtocol restored from recovered Secret"
);
Ok(events)
}
async fn check_preconditions<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
secret: &Secret,
) -> Result<(HashSet<u64>, Vec<HelperChannel>)> {
if stores
.user_secrets
.load_latest(local.secret_id)
.await?
.is_some()
{
return Err(RestoreError::AlreadyRestored.into());
}
if let Some(group) = &secret.replicas
&& !group.members.is_empty()
&& group.shared_key.len() != 32
{
return Err(RestoreError::Invariant(
"recovered Secret carries replicas but replicas.shared_key is missing or wrong size",
)
.into());
}
let rosters_have_endpoints = secret
.helpers
.iter()
.map(|h| &h.transports)
.chain(
secret
.replicas
.iter()
.flat_map(|g| g.members.iter().map(|m| &m.transports)),
)
.all(|endpoints| !endpoints.is_empty());
if !rosters_have_endpoints {
return Err(crate::Error::InvalidInput(
"recovered roster has an entry with no transport endpoint",
));
}
let canonical_ids: HashSet<u64> = secret
.helpers
.iter()
.map(|h| h.channel_id)
.chain(secret.replicas.as_ref().map(|g| g.channel_id))
.collect();
let existing_channels = stores
.channels
.helpers_matching(
local.secret_id,
crate::protocol::types::HelperFilter::default(),
)
.await?;
let collisions: Vec<ChannelId> = existing_channels
.iter()
.filter(|c| canonical_ids.contains(&c.channel_id.0))
.map(|c| c.channel_id)
.collect();
if !collisions.is_empty() {
return Err(RestoreError::Conflict(collisions).into());
}
Ok((canonical_ids, existing_channels))
}
async fn write_helper_channels<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
helpers: &[HelperInfo],
recovered_version: u32,
) -> Result<()> {
let secret_id = local.secret_id;
for h in helpers {
let cid = ChannelId(h.channel_id);
let shared_key: SharedKey = h
.shared_key
.as_slice()
.try_into()
.map_err(|_| RestoreError::Invariant("helper.shared_key must be 32 bytes"))?;
stores
.channels
.save(
secret_id,
ChannelRecord::Helper(HelperChannel {
channel_id: cid,
transports: h.transports.clone(),
communication_info: h.communication_info.clone(),
status: ChannelStatus::Paired,
created_at: now_secs(),
peer_role: derec_proto::SenderKind::Helper,
}),
)
.await?;
stores
.secrets
.save(secret_id, cid, SecretValue::SharedKey(shared_key))
.await?;
stores
.shares
.save(
secret_id,
cid,
Share {
secret_id,
version: recovered_version,
bytes: Vec::new(),
},
)
.await?;
}
Ok(())
}
async fn write_replica_channels<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
group: &Replicas,
) -> Result<()> {
let group_key: SharedKey = group.shared_key.as_slice().try_into().map_err(|_| {
RestoreError::Invariant("replicas.shared_key must be 32 bytes when replicas is non-empty")
})?;
let cid = ChannelId(group.channel_id);
for r in &group.members {
stores
.channels
.save(
local.secret_id,
ChannelRecord::Replica(ReplicaMember {
channel_id: cid,
replica_id: crate::types::ReplicaId::try_from(r.replica_id)?,
transports: r.transports.clone(),
communication_info: r.communication_info.clone(),
role: ReplicaRole::from_i32(r.role).ok_or(RestoreError::Invariant(
"roster member carries an unknown role",
))?,
status: ChannelStatus::Paired,
created_at: now_secs(),
}),
)
.await?;
}
stores
.secrets
.save(local.secret_id, cid, SecretValue::SharedKey(group_key))
.await?;
Ok(())
}
async fn commit_snapshot<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
secret: &Secret,
recovered_version: u32,
) -> Result<()> {
stores
.user_secrets
.save_latest(
local.secret_id,
UserSecrets {
version: recovered_version,
secrets: secret.secrets.clone(),
description: None,
replicas: secret.replicas.clone(),
},
)
.await?;
Ok(())
}
async fn unpair_recovery_channels<S: StoreSet>(
stores: &mut Stores<'_, S>,
local: &Local<'_>,
existing_channels: &[HelperChannel],
canonical_ids: &HashSet<u64>,
) -> Vec<DeRecEvent> {
let recovery_ids: Vec<ChannelId> = existing_channels
.iter()
.filter(|c| !canonical_ids.contains(&c.channel_id.0))
.map(|c| c.channel_id)
.collect();
if recovery_ids.is_empty() {
return Vec::new();
}
let now = now_secs();
let round = &crate::protocol::context::Round {
reply_to: &[],
trace_id: crate::derec_message::fresh_trace_id(),
};
let mut events = Vec::new();
for channel_id in recovery_ids {
match super::unpairing::start(
stores,
local,
channel_id,
None,
UnpairAck::NotRequired,
now,
round,
)
.await
{
Ok(mut per_channel) => events.append(&mut per_channel),
Err(e) => {
events.push(DeRecEvent::UnpairFailed {
channel_id,
error: e.to_string(),
});
if super::unpairing::drop_channel_state(stores, local, channel_id)
.await
.is_ok()
{
events.push(DeRecEvent::Unpaired { channel_id });
}
}
}
}
events
}
#[cfg(test)]
mod tests {
use super::*;
use crate::protocol::DeRecProtocolBuilder;
use crate::protocol::traits::{
DeRecChannelStore, DeRecSecretStore, DeRecShareStore, DeRecUserSecretStore,
};
use crate::protocol::types::{
ChannelQuery, ChannelRecord, ChannelStatus, HelperInfo, ReplicaInfo, ReplicaRole, Replicas,
Secret, SecretKind, SecretValue, UserSecret, UserSecrets,
};
use derec_proto::{SenderKind, TransportProtocol};
use std::collections::HashMap;
use crate::protocol::test::{
InMemChannelStore, InMemSecretStore, InMemShareStore, InMemStateStore,
InMemUserSecretStore, NoopTransport, StoreRig, run_async,
};
type TestProto = crate::protocol::DeRecProtocol<
InMemChannelStore,
InMemShareStore,
InMemSecretStore,
InMemUserSecretStore,
InMemStateStore,
NoopTransport,
>;
struct TestRig {
protocol: TestProto,
channel_store: InMemChannelStore,
secret_store: InMemSecretStore,
share_store: InMemShareStore,
user_secret_store: InMemUserSecretStore,
}
fn build_rig(secret_id: u64) -> TestRig {
let rig = StoreRig::new();
let protocol = DeRecProtocolBuilder::new(secret_id)
.with_channel_store(rig.channels.clone())
.with_share_store(rig.shares.clone())
.with_secret_store(rig.secrets.clone())
.with_user_secret_store(rig.user_secrets.clone())
.with_transport(NoopTransport)
.with_state_store(InMemStateStore)
.with_own_transports(["https://owner.example.com"])
.with_threshold(2)
.build()
.expect("test rig builds");
TestRig {
protocol,
channel_store: rig.channels,
secret_store: rig.secrets,
share_store: rig.shares,
user_secret_store: rig.user_secrets,
}
}
fn fixture_secret() -> Secret {
Secret {
helpers: vec![
HelperInfo {
channel_id: 11,
transports: vec![derec_proto::TransportProtocol {
uri: "https://helper-a.example".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
}],
shared_key: vec![0xAA; 32],
communication_info: HashMap::from([("name".to_owned(), "HelperA".to_owned())]),
},
HelperInfo {
channel_id: 12,
transports: vec![derec_proto::TransportProtocol {
uri: "https://helper-b.example".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
}],
shared_key: vec![0xBB; 32],
communication_info: HashMap::new(),
},
],
secrets: vec![
UserSecret {
id: vec![0x01],
name: "wallet".to_owned(),
data: b"correct horse battery staple".to_vec(),
},
UserSecret {
id: vec![0x02],
name: "api token".to_owned(),
data: b"hunter2".to_vec(),
},
],
replicas: Some(Replicas {
channel_id: 21,
members: vec![
ReplicaInfo {
replica_id: 0xBEEF,
transports: vec![derec_proto::TransportProtocol {
uri: "https://owner.example".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
}],
role: ReplicaRole::Source as i32,
communication_info: HashMap::new(),
},
ReplicaInfo {
replica_id: 0xCAFE,
transports: vec![derec_proto::TransportProtocol {
uri: "https://replica.example".to_owned(),
protocol: derec_proto::Protocol::Https as i32,
}],
role: ReplicaRole::Destination as i32,
communication_info: HashMap::new(),
},
],
shared_key: vec![0xCC; 32],
}),
}
}
#[test]
fn restore_happy_path_persists_canonical_state() {
run_async(async {
let secret_id: u64 = 0xDE_2EC;
let mut rig = build_rig(secret_id);
rig.protocol
.restore(&fixture_secret(), 7)
.await
.expect("happy path must succeed");
for hid in [11_u64, 12] {
let ch = rig
.channel_store
.load(
secret_id,
ChannelQuery::Helper {
channel_id: ChannelId(hid),
},
)
.await
.unwrap()
.expect("helper channel must be persisted");
let ChannelRecord::Helper(ch) = ch else {
panic!("a helper query must never return a replica record");
};
assert_eq!(ch.status, ChannelStatus::Paired);
assert_eq!(ch.peer_role, SenderKind::Helper);
let sk = rig
.secret_store
.load(secret_id, ChannelId(hid), SecretKind::SharedKey)
.await
.unwrap()
.expect("helper SharedKey must be persisted");
assert!(matches!(sk, SecretValue::SharedKey(_)));
let shares = rig
.share_store
.load(secret_id, ChannelId(hid), &[])
.await
.unwrap();
assert_eq!(shares.len(), 1);
assert_eq!(shares[0].version, 7);
}
let rep = rig
.channel_store
.load(
secret_id,
ChannelQuery::Replica {
channel_id: ChannelId(21),
replica_id: crate::types::ReplicaId(0xCAFE),
},
)
.await
.unwrap()
.expect("replica member must be persisted");
let ChannelRecord::Replica(rep) = rep else {
panic!("a replica query must never return a helper record");
};
assert_eq!(rep.status, ChannelStatus::Paired);
assert_eq!(rep.role, ReplicaRole::Destination);
assert_eq!(rep.replica_id.0, 0xCAFE);
let rep_sk = rig
.secret_store
.load(secret_id, ChannelId(21), SecretKind::SharedKey)
.await
.unwrap()
.expect("replica group key must be persisted");
match rep_sk {
SecretValue::SharedKey(k) => assert_eq!(k.to_vec(), vec![0xCC; 32]),
_ => panic!("expected SharedKey"),
}
let snapshot = rig
.user_secret_store
.load_latest(secret_id)
.await
.unwrap()
.expect("snapshot must exist");
assert_eq!(snapshot.version, 7);
assert_eq!(snapshot.secrets.len(), 2);
assert_eq!(snapshot.secrets[0].name, "wallet");
assert_eq!(snapshot.secrets[0].data, b"correct horse battery staple");
assert_eq!(snapshot.secrets[1].name, "api token");
assert_eq!(
rig.protocol.replica_id(),
None,
"restore must not adopt the roster source's replica_id"
);
});
}
#[test]
fn a_grpc_peer_is_rehydrated_as_grpc() {
run_async(async {
let secret_id: u64 = 0xDE_2EC;
let mut rig = build_rig(secret_id);
let mut secret = fixture_secret();
secret.helpers[0].transports = vec![derec_proto::TransportProtocol {
uri: "grpcs://helper-a.example:443".to_owned(),
protocol: derec_proto::Protocol::Grpc as i32,
}];
let members = &mut secret
.replicas
.as_mut()
.expect("fixture has a roster")
.members;
members[1].transports = vec![derec_proto::TransportProtocol {
uri: "grpcs://replica.example:443".to_owned(),
protocol: derec_proto::Protocol::Grpc as i32,
}];
rig.protocol
.restore(&secret, 7)
.await
.expect("a grpc roster must restore");
let helper = rig
.channel_store
.load(
secret_id,
ChannelQuery::Helper {
channel_id: ChannelId(11),
},
)
.await
.unwrap()
.expect("helper channel must be persisted");
let ChannelRecord::Helper(helper) = helper else {
panic!("a helper query must never return a replica record");
};
assert_eq!(helper.transports[0].uri, "grpcs://helper-a.example:443");
assert_eq!(
helper.transports[0].protocol,
derec_proto::Protocol::Grpc as i32,
"a grpcs:// helper must come back as Grpc, not the historical \
hardcoded Https"
);
for endpoint in &helper.transports {
crate::transport::TransportProtocol::try_from(endpoint)
.expect("every rehydrated endpoint must be self-consistent");
}
let member = rig
.channel_store
.load(
secret_id,
ChannelQuery::Replica {
channel_id: ChannelId(21),
replica_id: crate::types::ReplicaId(0xCAFE),
},
)
.await
.unwrap()
.expect("replica member must be persisted");
let ChannelRecord::Replica(member) = member else {
panic!("a replica query must never return a helper record");
};
assert_eq!(member.transports[0].uri, "grpcs://replica.example:443");
assert_eq!(
member.transports[0].protocol,
derec_proto::Protocol::Grpc as i32,
"a grpcs:// group member must come back as Grpc"
);
let other = rig
.channel_store
.load(
secret_id,
ChannelQuery::Helper {
channel_id: ChannelId(12),
},
)
.await
.unwrap()
.expect("helper channel must be persisted");
let ChannelRecord::Helper(other) = other else {
panic!("a helper query must never return a replica record");
};
assert_eq!(
other.transports[0].protocol,
derec_proto::Protocol::Https as i32
);
});
}
#[test]
fn a_roster_entry_without_an_endpoint_is_refused_before_any_write() {
run_async(async {
let secret_id: u64 = 0xDE_2EC;
let mut rig = build_rig(secret_id);
let mut secret = fixture_secret();
secret.helpers[1].transports = Vec::new();
let err = rig
.protocol
.restore(&secret, 7)
.await
.expect_err("a peer with no endpoint must not restore silently");
assert!(
matches!(err, crate::Error::InvalidInput(_)),
"expected the precondition refusal, got {err:?}"
);
assert!(
rig.channel_store
.load(
secret_id,
ChannelQuery::Helper {
channel_id: ChannelId(11)
}
)
.await
.unwrap()
.is_none(),
"a precondition failure must leave the stores untouched"
);
assert!(
rig.user_secret_store
.load_latest(secret_id)
.await
.unwrap()
.is_none(),
"a precondition failure must not commit a snapshot"
);
});
}
#[test]
fn restore_unpairs_pre_existing_recovery_channels() {
run_async(async {
let secret_id: u64 = 0xDE_2EC;
let mut rig = build_rig(secret_id);
for rcid in [99_u64, 100] {
rig.channel_store.helper_rows.lock().unwrap().insert(
(secret_id, rcid),
HelperChannel {
channel_id: ChannelId(rcid),
transports: vec![TransportProtocol {
uri: format!("https://recovery-{rcid}.example"),
protocol: 0,
}],
communication_info: HashMap::new(),
status: ChannelStatus::Paired,
created_at: 1,
peer_role: SenderKind::Helper,
},
);
rig.secret_store.data.lock().unwrap().insert(
(secret_id, rcid, SecretKind::SharedKey as u8),
SecretValue::SharedKey([0x77; 32]),
);
}
rig.protocol
.restore(&fixture_secret(), 7)
.await
.expect("restore must succeed despite recovery channels");
for rcid in [99_u64, 100] {
assert!(
rig.channel_store
.load(
secret_id,
ChannelQuery::Helper {
channel_id: ChannelId(rcid),
},
)
.await
.unwrap()
.is_none(),
"recovery channel {rcid} must be unpaired"
);
assert!(
rig.secret_store
.load(secret_id, ChannelId(rcid), SecretKind::SharedKey)
.await
.unwrap()
.is_none()
);
}
assert!(
rig.channel_store
.load(
secret_id,
ChannelQuery::Helper {
channel_id: ChannelId(11),
},
)
.await
.unwrap()
.is_some()
);
});
}
#[test]
fn restore_succeeds_when_recovery_channel_unpair_cannot_be_delivered() {
run_async(async {
let secret_id: u64 = 0xDE_2EC;
let rig = StoreRig::new();
let mut protocol = DeRecProtocolBuilder::new(secret_id)
.with_channel_store(rig.channels.clone())
.with_share_store(rig.shares.clone())
.with_secret_store(rig.secrets.clone())
.with_user_secret_store(rig.user_secrets.clone())
.with_transport(crate::protocol::test::FailingTransport)
.with_state_store(InMemStateStore)
.with_own_transports(["https://owner.example.com"])
.with_threshold(2)
.build()
.expect("test rig builds");
rig.channels.helper_rows.lock().unwrap().insert(
(secret_id, 99),
HelperChannel {
channel_id: ChannelId(99),
transports: vec![TransportProtocol {
uri: "https://gone.example".to_owned(),
protocol: 0,
}],
communication_info: HashMap::new(),
status: ChannelStatus::Paired,
created_at: 1,
peer_role: SenderKind::Helper,
},
);
rig.secrets.data.lock().unwrap().insert(
(secret_id, 99, SecretKind::SharedKey as u8),
SecretValue::SharedKey([0x77; 32]),
);
let events = protocol
.restore(&fixture_secret(), 7)
.await
.expect("an unreachable peer must not fail the restore");
assert!(
events.iter().any(|e| matches!(
e,
DeRecEvent::UnpairFailed { channel_id, .. } if *channel_id == ChannelId(99)
)),
"the undeliverable teardown must be reported, got {events:?}"
);
assert!(
events
.iter()
.any(|e| matches!(e, DeRecEvent::Unpaired { channel_id } if *channel_id == ChannelId(99))),
"local state is dropped regardless, so Unpaired still fires"
);
assert!(
rig.channels
.load(
secret_id,
ChannelQuery::Helper {
channel_id: ChannelId(99),
},
)
.await
.unwrap()
.is_none(),
"the ephemeral channel must not survive a failed send"
);
assert!(
rig.user_secrets
.load_latest(secret_id)
.await
.unwrap()
.is_some(),
"the recovered snapshot stays committed"
);
assert!(
rig.channels
.load(
secret_id,
ChannelQuery::Helper {
channel_id: ChannelId(11),
},
)
.await
.unwrap()
.is_some(),
"canonical helper channels stay in place"
);
});
}
#[test]
fn restore_returns_already_restored_when_snapshot_exists() {
run_async(async {
let secret_id: u64 = 0xDE_2EC;
let mut rig = build_rig(secret_id);
rig.user_secret_store.data.lock().unwrap().insert(
secret_id,
UserSecrets {
version: 1,
secrets: Vec::new(),
description: None,
replicas: None,
},
);
let err = rig
.protocol
.restore(&fixture_secret(), 7)
.await
.unwrap_err();
assert!(matches!(
err,
crate::Error::Restore(RestoreError::AlreadyRestored)
));
assert!(
rig.channel_store
.load(
secret_id,
ChannelQuery::Helper {
channel_id: ChannelId(11),
},
)
.await
.unwrap()
.is_none()
);
});
}
#[test]
fn restore_returns_conflict_on_canonical_id_collision() {
run_async(async {
let secret_id: u64 = 0xDE_2EC;
let mut rig = build_rig(secret_id);
rig.channel_store.helper_rows.lock().unwrap().insert(
(secret_id, 11),
HelperChannel {
channel_id: ChannelId(11),
transports: vec![TransportProtocol {
uri: "https://collision.example".to_owned(),
protocol: 0,
}],
communication_info: HashMap::new(),
status: ChannelStatus::Paired,
created_at: 1,
peer_role: SenderKind::Helper,
},
);
let err = rig
.protocol
.restore(&fixture_secret(), 7)
.await
.unwrap_err();
let crate::Error::Restore(RestoreError::Conflict(ids)) = err else {
panic!("expected Restore(Conflict), got {err:?}");
};
assert_eq!(ids, vec![ChannelId(11)]);
assert!(
rig.user_secret_store
.load_latest(secret_id)
.await
.unwrap()
.is_none()
);
});
}
#[test]
fn restore_invariant_error_when_replicas_present_but_group_key_missing() {
run_async(async {
let secret_id: u64 = 0xDE_2EC;
let mut rig = build_rig(secret_id);
let mut secret = fixture_secret();
if let Some(group) = secret.replicas.as_mut() {
group.shared_key = Vec::new();
}
let err = rig.protocol.restore(&secret, 7).await.unwrap_err();
assert!(matches!(
err,
crate::Error::Restore(RestoreError::Invariant(_))
));
assert!(
rig.channel_store
.load(
secret_id,
ChannelQuery::Helper {
channel_id: ChannelId(11),
},
)
.await
.unwrap()
.is_none()
);
});
}
#[test]
fn restore_does_not_overwrite_explicit_replica_id() {
run_async(async {
let secret_id: u64 = 0xDE_2EC;
let mut protocol = DeRecProtocolBuilder::new(secret_id)
.with_channel_store(InMemChannelStore::default())
.with_share_store(InMemShareStore::default())
.with_secret_store(InMemSecretStore::default())
.with_user_secret_store(InMemUserSecretStore::default())
.with_transport(NoopTransport)
.with_state_store(InMemStateStore)
.with_own_transports(["https://owner.example.com"])
.with_threshold(2)
.with_replica_id(0x1234)
.build()
.expect("build");
protocol.restore(&fixture_secret(), 7).await.unwrap();
assert_eq!(protocol.replica_id(), Some(0x1234));
});
}
}