use std::collections::HashMap;
use std::time::Duration;
use prost::Message as _;
use crate::extensions::communication_info::CommunicationInfoExt as _;
use crate::interop::ffi::error::{
DEREC_CODE_FFI_BAD_PROTO, DEREC_CODE_FFI_INVALID_ENUM, DEREC_CODE_FFI_NULL_PTR, DeRecError,
ffi_error, success,
};
use crate::interop::ffi::protocol::stores::{
ChannelStoreCallbacks, DotnetChannelStore, DotnetSecretStore, DotnetShareStore,
DotnetStateStore, DotnetTransport, DotnetUserSecretStore, SecretStoreCallbacks,
ShareStoreCallbacks, StateStoreCallbacks, TransportCallbacks, UserSecretStoreCallbacks,
};
use crate::protocol::DeRecProtocolBuilder;
mod config;
mod flow;
mod pairing;
pub(super) type Protocol = crate::protocol::DeRecProtocol<
DotnetChannelStore,
DotnetShareStore,
DotnetSecretStore,
DotnetUserSecretStore,
DotnetStateStore,
DotnetTransport,
>;
pub struct DeRecProtocolHandle {
pub(super) runtime: tokio::runtime::Runtime,
pub(super) inner: std::sync::Mutex<Protocol>,
}
impl DeRecProtocolHandle {
pub(super) fn lock_inner(&self) -> std::sync::MutexGuard<'_, Protocol> {
self.inner
.lock()
.unwrap_or_else(|poisoned| poisoned.into_inner())
}
}
pub(super) fn validate_transport(
uri: &str,
protocol: i32,
) -> Result<crate::transport::TransportProtocol, DeRecError> {
let proto = derec_proto::TransportProtocol {
uri: uri.to_owned(),
protocol,
};
crate::transport::TransportProtocol::try_from(&proto)
.map_err(|e| crate::interop::ffi::error::from_lib_error(crate::Error::Transport(e)))
}
#[repr(C)]
pub struct DeRecProtocolNewResult {
pub error: DeRecError,
pub handle: *mut DeRecProtocolHandle,
}
impl From<DeRecError> for DeRecProtocolNewResult {
fn from(error: DeRecError) -> Self {
Self {
error,
handle: std::ptr::null_mut(),
}
}
}
#[derive(serde::Deserialize)]
#[serde(default)]
struct AutoAcceptConfig {
pairing: bool,
pre_pair: bool,
store_share: bool,
verify_share: bool,
discovery: bool,
get_share: bool,
unpair: bool,
update_channel_info: bool,
}
impl Default for AutoAcceptConfig {
fn default() -> Self {
let p = crate::protocol::AutoAcceptPolicy::default();
Self {
pairing: p.pairing,
pre_pair: p.pre_pair,
store_share: p.store_share,
verify_share: p.verify_share,
discovery: p.discovery,
get_share: p.get_share,
unpair: p.unpair,
update_channel_info: p.update_channel_info,
}
}
}
impl From<AutoAcceptConfig> for crate::protocol::AutoAcceptPolicy {
fn from(p: AutoAcceptConfig) -> Self {
Self {
pairing: p.pairing,
pre_pair: p.pre_pair,
store_share: p.store_share,
verify_share: p.verify_share,
discovery: p.discovery,
get_share: p.get_share,
unpair: p.unpair,
update_channel_info: p.update_channel_info,
}
}
}
#[derive(serde::Deserialize)]
struct RemoveExpiredChannelsConfig {
enabled: bool,
timeout_in_secs: u64,
}
#[derive(serde::Deserialize, Default)]
struct TimeoutsConfig {
#[serde(default)]
inbound_message_secs: Option<u64>,
#[serde(default)]
sharing_round_secs: Option<u64>,
#[serde(default)]
unpair_ack_secs: Option<u64>,
#[serde(default)]
expired_channels: Option<RemoveExpiredChannelsConfig>,
}
impl TimeoutsConfig {
fn to_timeouts(&self) -> crate::protocol::types::Timeouts {
let d = crate::protocol::types::Timeouts::default();
crate::protocol::types::Timeouts {
inbound_message: self
.inbound_message_secs
.map_or(d.inbound_message, Duration::from_secs),
sharing_round: self
.sharing_round_secs
.map_or(d.sharing_round, Duration::from_secs),
unpair_ack: self
.unpair_ack_secs
.map_or(d.unpair_ack, Duration::from_secs),
expired_channels: self
.expired_channels
.as_ref()
.map_or(d.expired_channels, |e| {
crate::protocol::ExpiredChannelCleanup::new(e.enabled, e.timeout_in_secs)
}),
}
}
}
#[derive(serde::Deserialize, Default)]
#[serde(default)]
struct ParameterRangeConfig {
#[serde(deserialize_with = "i64_from_number_or_decimal")]
min_share_size: i64,
#[serde(deserialize_with = "i64_from_number_or_decimal")]
max_share_size: i64,
#[serde(deserialize_with = "i64_from_number_or_decimal")]
min_time_between_verifications: i64,
#[serde(deserialize_with = "i64_from_number_or_decimal")]
max_time_between_verifications: i64,
#[serde(deserialize_with = "i64_from_number_or_decimal")]
min_time_between_share_updates: i64,
#[serde(deserialize_with = "i64_from_number_or_decimal")]
max_time_between_share_updates: i64,
#[serde(deserialize_with = "i64_from_number_or_decimal")]
min_unresponsive_deletion_timeout: i64,
#[serde(deserialize_with = "i64_from_number_or_decimal")]
max_unresponsive_deletion_timeout: i64,
#[serde(deserialize_with = "i64_from_number_or_decimal")]
min_unresponsive_deactivation_timeout: i64,
#[serde(deserialize_with = "i64_from_number_or_decimal")]
max_unresponsive_deactivation_timeout: i64,
}
fn i64_from_number_or_decimal<'de, D>(de: D) -> Result<i64, D::Error>
where
D: serde::Deserializer<'de>,
{
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum NumberOrDecimal {
Number(i64),
Decimal(String),
}
match <NumberOrDecimal as serde::Deserialize>::deserialize(de)? {
NumberOrDecimal::Number(n) => Ok(n),
NumberOrDecimal::Decimal(s) => s
.parse()
.map_err(|_| serde::de::Error::custom(format!("{s:?} is not a decimal i64"))),
}
}
impl From<&ParameterRangeConfig> for derec_proto::ParameterRange {
fn from(c: &ParameterRangeConfig) -> Self {
Self {
min_share_size: c.min_share_size,
max_share_size: c.max_share_size,
min_time_between_verifications: c.min_time_between_verifications,
max_time_between_verifications: c.max_time_between_verifications,
min_time_between_share_updates: c.min_time_between_share_updates,
max_time_between_share_updates: c.max_time_between_share_updates,
min_unresponsive_deletion_timeout: c.min_unresponsive_deletion_timeout,
max_unresponsive_deletion_timeout: c.max_unresponsive_deletion_timeout,
min_unresponsive_deactivation_timeout: c.min_unresponsive_deactivation_timeout,
max_unresponsive_deactivation_timeout: c.max_unresponsive_deactivation_timeout,
}
}
}
#[derive(serde::Deserialize)]
struct OwnTransportConfig {
uri: String,
#[serde(
deserialize_with = "crate::interop::protocol_names::protocol_from_name_or_discriminant"
)]
protocol: i32,
}
#[derive(serde::Deserialize)]
struct ProtocolConfig {
secret_id: String,
#[serde(default)]
own_transports: Vec<OwnTransportConfig>,
#[serde(default = "default_threshold")]
threshold: u32,
#[serde(default)]
auto_respond_on_failure: bool,
#[serde(default)]
unpair_ack: Option<UnpairAckConfig>,
#[serde(default)]
auto_reply_to: bool,
#[serde(default)]
auto_accept: AutoAcceptConfig,
#[serde(default)]
timeouts: TimeoutsConfig,
#[serde(default)]
unsafe_connection: bool,
#[serde(default)]
replica_id: Option<String>,
#[serde(default)]
parameter_range: Option<ParameterRangeConfig>,
#[serde(default)]
communication_info: Option<HashMap<String, String>>,
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn derec_protocol_new(
config_json_ptr: *const u8,
config_json_len: usize,
communication_info_ptr: *const u8,
communication_info_len: usize,
channel_store_cb: *const ChannelStoreCallbacks,
secret_store_cb: *const SecretStoreCallbacks,
share_store_cb: *const ShareStoreCallbacks,
user_secret_store_cb: *const UserSecretStoreCallbacks,
state_store_cb: *const StateStoreCallbacks,
transport_cb: *const TransportCallbacks,
) -> DeRecProtocolNewResult {
if config_json_ptr.is_null() {
return ffi_error(DEREC_CODE_FFI_NULL_PTR, "config_json_ptr is null").into();
}
let json_bytes = unsafe { std::slice::from_raw_parts(config_json_ptr, config_json_len) };
let config: ProtocolConfig = match serde_json::from_slice(json_bytes) {
Ok(c) => c,
Err(e) => {
return ffi_error(
DEREC_CODE_FFI_BAD_PROTO,
format!("config_json is not valid: {e}"),
)
.into();
}
};
let secret_id: u64 = match config.secret_id.parse() {
Ok(id) => id,
Err(_) => {
return ffi_error(DEREC_CODE_FFI_BAD_PROTO, "secret_id is not a valid u64").into();
}
};
let replica_id: Option<u64> = match config.replica_id {
Some(s) => match s.parse() {
Ok(id) => Some(id),
Err(_) => {
return ffi_error(DEREC_CODE_FFI_BAD_PROTO, "replica_id is not a valid u64").into();
}
},
None => None,
};
let mut own_transports = Vec::with_capacity(config.own_transports.len());
for entry in config.own_transports {
match validate_transport(&entry.uri, entry.protocol) {
Ok(tp) => own_transports.push(tp),
Err(e) => return e.into(),
}
}
let info = match unsafe {
resolve_communication_info(
config.communication_info,
communication_info_ptr,
communication_info_len,
)
} {
Ok(i) => i,
Err(e) => return e.into(),
};
let unpair_ack_value = match config.unpair_ack.map(UnpairAckConfig::resolve) {
None => crate::protocol::UnpairAck::default(),
Some(Ok(ack)) => ack,
Some(Err(e)) => return e.into(),
};
let unsafe_connection = config.unsafe_connection;
unsafe {
construct_protocol(
secret_id,
own_transports,
config.threshold,
info,
config.timeouts.to_timeouts(),
unsafe_connection,
config.auto_respond_on_failure,
unpair_ack_value,
config.auto_reply_to,
config.auto_accept.into(),
replica_id,
config.parameter_range.as_ref().map(Into::into),
channel_store_cb,
secret_store_cb,
share_store_cb,
user_secret_store_cb,
state_store_cb,
transport_cb,
)
}
}
#[unsafe(no_mangle)]
pub unsafe extern "C" fn derec_protocol_free(handle: *mut DeRecProtocolHandle) {
if handle.is_null() {
return;
}
unsafe {
drop(Box::from_raw(handle));
}
}
unsafe fn resolve_communication_info(
from_config: Option<HashMap<String, String>>,
ptr: *const u8,
len: usize,
) -> Result<HashMap<String, String>, DeRecError> {
match from_config {
Some(_) if len != 0 => Err(ffi_error(
DEREC_CODE_FFI_BAD_PROTO,
"communication_info supplied both in config_json and as a proto buffer",
)),
Some(map) => Ok(map),
None => unsafe { decode_communication_info(ptr, len) },
}
}
unsafe fn decode_communication_info(
ptr: *const u8,
len: usize,
) -> Result<HashMap<String, String>, DeRecError> {
if len == 0 {
return Ok(HashMap::new());
}
if ptr.is_null() {
return Err(ffi_error(
DEREC_CODE_FFI_NULL_PTR,
"communication_info_ptr is null but length is non-zero",
));
}
let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };
match derec_proto::CommunicationInfo::decode(bytes) {
Ok(c) => Ok(c.to_map()),
Err(_) => Err(ffi_error(
DEREC_CODE_FFI_BAD_PROTO,
"communication_info is not a valid CommunicationInfo proto",
)),
}
}
#[allow(clippy::too_many_arguments)]
unsafe fn construct_protocol(
secret_id: u64,
own_transports: Vec<crate::transport::TransportProtocol>,
threshold: u32,
communication_info: HashMap<String, String>,
timeouts: crate::protocol::types::Timeouts,
unsafe_connection: bool,
auto_respond_on_failure: bool,
unpair_ack: crate::protocol::UnpairAck,
auto_reply_to: bool,
auto_accept: crate::protocol::AutoAcceptPolicy,
replica_id: Option<u64>,
parameter_range: Option<derec_proto::ParameterRange>,
channel_store_cb: *const ChannelStoreCallbacks,
secret_store_cb: *const SecretStoreCallbacks,
share_store_cb: *const ShareStoreCallbacks,
user_secret_store_cb: *const UserSecretStoreCallbacks,
state_store_cb: *const StateStoreCallbacks,
transport_cb: *const TransportCallbacks,
) -> DeRecProtocolNewResult {
if channel_store_cb.is_null()
|| secret_store_cb.is_null()
|| share_store_cb.is_null()
|| user_secret_store_cb.is_null()
|| state_store_cb.is_null()
|| transport_cb.is_null()
{
return ffi_error(
DEREC_CODE_FFI_NULL_PTR,
"store/transport callback pointer is null",
)
.into();
}
let channel_store = DotnetChannelStore {
cb: unsafe { std::ptr::read(channel_store_cb) },
};
let secret_store = DotnetSecretStore {
cb: unsafe { std::ptr::read(secret_store_cb) },
};
let share_store = DotnetShareStore {
cb: unsafe { std::ptr::read(share_store_cb) },
};
let user_secret_store = DotnetUserSecretStore {
cb: unsafe { std::ptr::read(user_secret_store_cb) },
};
let state_store = DotnetStateStore {
cb: unsafe { std::ptr::read(state_store_cb) },
};
let transport = DotnetTransport {
cb: unsafe { std::ptr::read(transport_cb) },
};
let mut builder = DeRecProtocolBuilder::new(secret_id)
.with_channel_store(channel_store)
.with_share_store(share_store)
.with_secret_store(secret_store)
.with_user_secret_store(user_secret_store)
.with_state_store(state_store)
.with_transport(transport)
.with_own_transports(own_transports)
.with_threshold(threshold as usize)
.with_communication_info(communication_info)
.with_timeouts(timeouts)
.with_unsafe_connection(unsafe_connection)
.with_auto_respond_on_failure(auto_respond_on_failure)
.with_unpair_ack(unpair_ack)
.with_auto_reply_to(auto_reply_to)
.with_auto_accept(auto_accept);
if let Some(replica_id) = replica_id {
builder = builder.with_replica_id(replica_id);
}
if let Some(parameter_range) = parameter_range {
builder = builder.with_parameter_range(parameter_range);
}
let inner = match builder.build() {
Ok(p) => p,
Err(e) => return crate::interop::ffi::error::from_lib_error(e).into(),
};
let runtime = match tokio::runtime::Builder::new_current_thread().build() {
Ok(rt) => rt,
Err(e) => {
return ffi_error(
DEREC_CODE_FFI_BAD_PROTO,
format!("failed to build tokio runtime: {e}"),
)
.into();
}
};
let handle = Box::new(DeRecProtocolHandle {
runtime,
inner: std::sync::Mutex::new(inner),
});
DeRecProtocolNewResult {
error: success(),
handle: Box::into_raw(handle),
}
}
fn default_threshold() -> u32 {
crate::protocol::DEFAULT_THRESHOLD as u32
}
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum UnpairAckConfig {
Code(i32),
Name(String),
}
impl UnpairAckConfig {
fn resolve(self) -> Result<crate::protocol::UnpairAck, DeRecError> {
let resolved = match &self {
Self::Code(0) => Some(crate::protocol::UnpairAck::Required),
Self::Code(1) => Some(crate::protocol::UnpairAck::NotRequired),
Self::Code(_) => None,
Self::Name(name) => crate::interop::protocol_names::unpair_ack_from_name(name),
};
resolved.ok_or_else(|| {
let shown = match self {
Self::Code(code) => code.to_string(),
Self::Name(name) => format!("{name:?}"),
};
ffi_error(
DEREC_CODE_FFI_INVALID_ENUM,
format!("invalid unpair_ack: {shown}"),
)
})
}
}
#[cfg(test)]
mod protocol_config_defaults_tests {
use super::*;
#[test]
fn minimal_config_json_matches_builder_defaults() {
let minimal = r#"{
"secret_id": "1"
}"#;
let config: ProtocolConfig =
serde_json::from_str(minimal).expect("minimal config must deserialize");
assert_eq!(config.threshold, crate::protocol::DEFAULT_THRESHOLD as u32);
assert!(!config.auto_respond_on_failure);
assert!(config.unpair_ack.is_none());
assert!(!config.auto_reply_to);
assert_eq!(
crate::protocol::AutoAcceptPolicy::from(config.auto_accept),
crate::protocol::AutoAcceptPolicy::default()
);
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn unpair_ack_accepts_code_or_name_and_refuses_the_rest() {
let resolve = |value: &str| {
let config: ProtocolConfig =
serde_json::from_str(&format!(r#"{{"secret_id": "1", "unpair_ack": {value}}}"#))
.expect("parses");
config.unpair_ack.map(UnpairAckConfig::resolve)
};
use crate::protocol::UnpairAck::{NotRequired, Required};
assert!(matches!(resolve("0"), Some(Ok(Required))));
assert!(matches!(resolve("1"), Some(Ok(NotRequired))));
assert!(matches!(resolve(r#""required""#), Some(Ok(Required))));
assert!(matches!(
resolve(r#""not_required""#),
Some(Ok(NotRequired))
));
for bad in ["2", "-1", r#""Required""#, r#""notrequired""#] {
match resolve(bad) {
Some(Err(e)) => assert_eq!(e.code, DEREC_CODE_FFI_INVALID_ENUM, "{bad}"),
_ => panic!("{bad} must be refused"),
}
}
}
#[test]
fn config_json_reads_the_plaintext_flag() {
let set: ProtocolConfig = serde_json::from_str(
r#"{
"secret_id": "1",
"unsafe_connection": true
}"#,
)
.expect("parses");
assert!(set.unsafe_connection);
let absent: ProtocolConfig = serde_json::from_str(
r#"{
"secret_id": "1"
}"#,
)
.expect("parses");
assert!(!absent.unsafe_connection);
}
fn config_with(extra: &str) -> ProtocolConfig {
let json = format!(
r#"{{
"secret_id": "1",
"own_transport_uri": "",
"own_transport_protocol": 1
{extra}
}}"#
);
serde_json::from_str(&json).expect("config parses")
}
#[test]
fn partial_auto_accept_defaults_each_absent_flow() {
let config = config_with(r#", "auto_accept": { "pairing": true }"#);
let policy = crate::protocol::AutoAcceptPolicy::from(config.auto_accept);
let expected = crate::protocol::AutoAcceptPolicy {
pairing: true,
..crate::protocol::AutoAcceptPolicy::default()
};
assert_eq!(policy, expected);
let empty = config_with(r#", "auto_accept": {}"#);
assert_eq!(
crate::protocol::AutoAcceptPolicy::from(empty.auto_accept),
crate::protocol::AutoAcceptPolicy::default()
);
}
#[test]
fn parameter_range_accepts_decimal_strings_and_numbers() {
let config = config_with(
r#", "parameter_range": {
"min_share_size": "9007199254740993",
"max_share_size": 4096,
"max_unresponsive_deactivation_timeout": "-9223372036854775808"
}"#,
);
let range = derec_proto::ParameterRange::from(
config.parameter_range.as_ref().expect("range present"),
);
assert_eq!(range.min_share_size, 9_007_199_254_740_993);
assert_eq!(range.max_share_size, 4096);
assert_eq!(range.max_unresponsive_deactivation_timeout, i64::MIN);
assert_eq!(range.min_time_between_verifications, 0);
let bad = serde_json::from_str::<ProtocolConfig>(
r#"{
"secret_id": "1",
"own_transport_uri": "",
"own_transport_protocol": 1,
"parameter_range": { "min_share_size": "12x" }
}"#,
);
assert!(bad.is_err());
}
#[test]
fn communication_info_comes_from_exactly_one_source() {
let config = config_with(r#", "communication_info": { "name": "alice" }"#);
let from_json =
unsafe { resolve_communication_info(config.communication_info, std::ptr::null(), 0) }
.unwrap_or_else(|e| panic!("json map refused: {}", e.code));
assert_eq!(from_json.get("name").map(String::as_str), Some("alice"));
let mut map = HashMap::new();
map.insert("name".to_owned(), "bob".to_owned());
let proto = derec_proto::CommunicationInfo::from_map(&map).encode_to_vec();
let from_proto = unsafe { resolve_communication_info(None, proto.as_ptr(), proto.len()) }
.unwrap_or_else(|e| panic!("proto buffer refused: {}", e.code));
assert_eq!(from_proto, map);
let neither = unsafe { resolve_communication_info(None, std::ptr::null(), 0) }
.unwrap_or_else(|e| panic!("absent refused: {}", e.code));
assert!(neither.is_empty());
let both = unsafe {
resolve_communication_info(Some(HashMap::new()), proto.as_ptr(), proto.len())
};
let mut err = both.expect_err("both sources rejected");
assert_eq!(err.code, DEREC_CODE_FFI_BAD_PROTO);
unsafe { crate::interop::ffi::error::derec_free_error(&mut err) };
}
}