Skip to main content

derec_library/protocol/
protocol_config.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 DeRec Alliance. All rights reserved.
3
4//! [`DeRecProtocolConfig`]: every data setting of a
5//! [`DeRecProtocolBuilder`](crate::protocol::DeRecProtocolBuilder) in one
6//! value an application can load from a config file or a user record.
7
8use std::collections::HashMap;
9use std::time::Duration;
10
11use crate::protocol::types::Timeouts;
12use crate::protocol::{AutoAcceptPolicy, ExpiredChannelCleanup, UnpairAck};
13use crate::protocol_version::ProtocolVersion;
14use crate::transport::TransportProtocol;
15use derec_proto::ParameterRange;
16
17/// Every data setting of a [`DeRecProtocolBuilder`](crate::protocol::DeRecProtocolBuilder),
18/// each one optional, applied in one call by
19/// [`with_config`](crate::protocol::DeRecProtocolBuilder::with_config).
20///
21/// A field left `None` is not applied: the builder keeps what it already
22/// holds. A field that is set is applied through the matching `with_*`
23/// setter and validated by
24/// [`build`](crate::protocol::DeRecProtocolBuilder::build) under exactly
25/// the rules that setter documents. Stores, the delivery transport and the
26/// `secret_id` are not settings and are not carried here.
27///
28/// Configs layer: apply a general config, then a per-user one, then any
29/// individual setter, and the last write wins per field. See
30/// [`with_config`](crate::protocol::DeRecProtocolBuilder::with_config).
31///
32/// # Canonical JSON
33///
34/// With the `serde` feature the struct serializes to, and deserializes from,
35/// one JSON shape — the format for config files and user records, and the
36/// one every SDK accepts:
37///
38/// ```json
39/// {
40///   "threshold": 3,
41///   "max_subshares": "12",
42///   "timeouts": {
43///     "inbound_message_secs": 300,
44///     "sharing_round_secs": 60,
45///     "unpair_ack_secs": 60,
46///     "get_share_response_secs": 300,
47///     "pairing_secs": 30,
48///     "expired_channels": { "enabled": true, "timeout_in_secs": 300 }
49///   },
50///   "parameter_range": { "min_share_size": 1, "max_share_size": 4096 },
51///   "auto_accept": { "pairing": true, "store_share": true },
52///   "auto_respond_on_failure": false,
53///   "auto_reply_to": false,
54///   "unpair_ack": "required",
55///   "unsafe_connection": false,
56///   "communication_info": { "name": "alice" },
57///   "own_transports": [{ "uri": "https://me.example.com/derec", "protocol": "https" }],
58///   "replica_id": "9007199254740993",
59///   "min_protocol_version": { "major": 0, "minor": 1 }
60/// }
61/// ```
62///
63/// - Keys are `snake_case`, and every key is optional: an absent key or a
64///   `null` value leaves that setting unset.
65/// - **Unknown keys are rejected**, at every level, so a misspelled key fails
66///   to parse instead of being ignored.
67/// - `replica_id` and `max_subshares` are `u64` values written as decimal
68///   strings, which survive JSON encoders whose numbers are `f64`.
69/// - `threshold` is a JSON number.
70/// - `timeouts` carries whole seconds; see [`TimeoutsConfig`].
71/// - `parameter_range` mirrors [`derec_proto::ParameterRange`] with
72///   `snake_case` names. Each bound is a JSON number or a decimal string, and
73///   an absent bound is `0` ("no bound").
74/// - `auto_accept` has one boolean per flow, named as on
75///   [`AutoAcceptPolicy`]; an absent flow is `false`.
76/// - `unpair_ack` is `"required"` or `"not_required"`, or the discriminant
77///   `0` or `1`.
78/// - Each `own_transports` entry is `{uri, protocol}`, where `protocol` is
79///   `"https"` or `"grpc"` (any case) or its discriminant `0` or `1`.
80/// - `min_protocol_version` is `{major, minor}`, both JSON numbers.
81///
82/// Serializing writes only the fields that are set, names rather than
83/// discriminants, and every flow of `auto_accept` and every bound of
84/// `parameter_range`.
85#[derive(Clone, Debug, Default, PartialEq)]
86#[cfg_attr(
87    any(feature = "serde", target_arch = "wasm32"),
88    derive(serde::Serialize, serde::Deserialize),
89    serde(try_from = "wire::ConfigWire", into = "wire::ConfigWire")
90)]
91pub struct DeRecProtocolConfig {
92    /// See [`with_threshold`](crate::protocol::DeRecProtocolBuilder::with_threshold).
93    pub threshold: Option<usize>,
94    /// See [`with_max_subshares`](crate::protocol::DeRecProtocolBuilder::with_max_subshares).
95    pub max_subshares: Option<u64>,
96    /// See [`with_timeouts`](crate::protocol::DeRecProtocolBuilder::with_timeouts).
97    /// Merged per field; see [`TimeoutsConfig`].
98    pub timeouts: Option<TimeoutsConfig>,
99    /// See [`with_parameter_range`](crate::protocol::DeRecProtocolBuilder::with_parameter_range).
100    pub parameter_range: Option<ParameterRange>,
101    /// See [`with_auto_accept`](crate::protocol::DeRecProtocolBuilder::with_auto_accept).
102    pub auto_accept: Option<AutoAcceptPolicy>,
103    /// See [`with_auto_respond_on_failure`](crate::protocol::DeRecProtocolBuilder::with_auto_respond_on_failure).
104    pub auto_respond_on_failure: Option<bool>,
105    /// See [`with_auto_reply_to`](crate::protocol::DeRecProtocolBuilder::with_auto_reply_to).
106    pub auto_reply_to: Option<bool>,
107    /// See [`with_unpair_ack`](crate::protocol::DeRecProtocolBuilder::with_unpair_ack).
108    pub unpair_ack: Option<UnpairAck>,
109    /// See [`with_unsafe_connection`](crate::protocol::DeRecProtocolBuilder::with_unsafe_connection).
110    pub unsafe_connection: Option<bool>,
111    /// See [`with_communication_info`](crate::protocol::DeRecProtocolBuilder::with_communication_info).
112    pub communication_info: Option<HashMap<String, String>>,
113    /// See [`with_own_transports`](crate::protocol::DeRecProtocolBuilder::with_own_transports).
114    /// An unknown `protocol` discriminant is rejected when the endpoint is
115    /// parsed; structural checks (URI length, control characters, scheme)
116    /// run later, at `build()`.
117    pub own_transports: Option<Vec<TransportProtocol>>,
118    /// See [`with_replica_id`](crate::protocol::DeRecProtocolBuilder::with_replica_id).
119    pub replica_id: Option<u64>,
120    /// See [`with_min_protocol_version`](crate::protocol::DeRecProtocolBuilder::with_min_protocol_version).
121    pub min_protocol_version: Option<ProtocolVersion>,
122}
123
124/// The four waiting periods of [`Timeouts`], in whole seconds, each one
125/// optional.
126///
127/// Unlike the other nested settings of [`DeRecProtocolConfig`], this one is
128/// merged per field: a field left `None` keeps the value the builder already
129/// holds, so one config can set the sharing round and a later one the
130/// inbound-message window without either undoing the other. The merged
131/// result goes through
132/// [`with_timeouts`](crate::protocol::DeRecProtocolBuilder::with_timeouts),
133/// which clamps every value to at least one second.
134///
135/// In JSON the fields are `inbound_message_secs`, `sharing_round_secs`,
136/// `unpair_ack_secs`, `get_share_response_secs`, `pairing_secs` (non-negative
137/// integers) and
138/// `expired_channels`
139/// (an [`ExpiredChannelsConfig`] object).
140#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
141#[cfg_attr(
142    any(feature = "serde", target_arch = "wasm32"),
143    derive(serde::Serialize, serde::Deserialize),
144    serde(default, deny_unknown_fields)
145)]
146pub struct TimeoutsConfig {
147    /// [`Timeouts::inbound_message`], in seconds.
148    #[cfg_attr(
149        any(feature = "serde", target_arch = "wasm32"),
150        serde(skip_serializing_if = "Option::is_none")
151    )]
152    pub inbound_message_secs: Option<u64>,
153    /// [`Timeouts::sharing_round`], in seconds.
154    #[cfg_attr(
155        any(feature = "serde", target_arch = "wasm32"),
156        serde(skip_serializing_if = "Option::is_none")
157    )]
158    pub sharing_round_secs: Option<u64>,
159    /// [`Timeouts::unpair_ack`], in seconds.
160    #[cfg_attr(
161        any(feature = "serde", target_arch = "wasm32"),
162        serde(skip_serializing_if = "Option::is_none")
163    )]
164    pub unpair_ack_secs: Option<u64>,
165    /// [`Timeouts::get_share_response`], in seconds.
166    #[cfg_attr(
167        any(feature = "serde", target_arch = "wasm32"),
168        serde(skip_serializing_if = "Option::is_none")
169    )]
170    pub get_share_response_secs: Option<u64>,
171    /// [`Timeouts::pairing`], in seconds.
172    #[cfg_attr(
173        any(feature = "serde", target_arch = "wasm32"),
174        serde(skip_serializing_if = "Option::is_none")
175    )]
176    pub pairing_secs: Option<u64>,
177    /// [`Timeouts::expired_channels`].
178    #[cfg_attr(
179        any(feature = "serde", target_arch = "wasm32"),
180        serde(skip_serializing_if = "Option::is_none")
181    )]
182    pub expired_channels: Option<ExpiredChannelsConfig>,
183}
184
185/// Automatic removal of expired `Pending` channels, as the flat pair the
186/// config carries. Converted by [`ExpiredChannelCleanup::new`], which
187/// ignores the timeout when `enabled` is `false`.
188///
189/// Both fields are required in JSON: `{"enabled": true, "timeout_in_secs": 300}`.
190#[derive(Clone, Copy, Debug, PartialEq, Eq)]
191#[cfg_attr(
192    any(feature = "serde", target_arch = "wasm32"),
193    derive(serde::Serialize, serde::Deserialize),
194    serde(deny_unknown_fields)
195)]
196pub struct ExpiredChannelsConfig {
197    /// Whether `process()` sweeps expired `Pending` channels itself.
198    pub enabled: bool,
199    /// Age, in seconds, past which a `Pending` channel is removed.
200    pub timeout_in_secs: u64,
201}
202
203impl TimeoutsConfig {
204    /// `base` with every field this config sets replaced.
205    pub(crate) fn merged_onto(&self, base: Timeouts) -> Timeouts {
206        Timeouts {
207            inbound_message: self
208                .inbound_message_secs
209                .map_or(base.inbound_message, Duration::from_secs),
210            sharing_round: self
211                .sharing_round_secs
212                .map_or(base.sharing_round, Duration::from_secs),
213            unpair_ack: self
214                .unpair_ack_secs
215                .map_or(base.unpair_ack, Duration::from_secs),
216            get_share_response: self
217                .get_share_response_secs
218                .map_or(base.get_share_response, Duration::from_secs),
219            pairing: self.pairing_secs.map_or(base.pairing, Duration::from_secs),
220            expired_channels: self.expired_channels.map_or(base.expired_channels, |e| {
221                ExpiredChannelCleanup::new(e.enabled, e.timeout_in_secs)
222            }),
223        }
224    }
225}
226
227impl DeRecProtocolConfig {
228    /// `top` written over `self`, field by field, as
229    /// [`with_config`](crate::protocol::DeRecProtocolBuilder::with_config)
230    /// applies it to a builder: a set field replaces the held one, an unset
231    /// field keeps it, and `timeouts` merges per field. A binding that holds
232    /// its settings as one config until `build()` layers each call onto it.
233    #[cfg(any(target_arch = "wasm32", test))]
234    pub(crate) fn layer(&mut self, top: Self) {
235        fn over<T>(held: &mut Option<T>, set: Option<T>) {
236            if set.is_some() {
237                *held = set;
238            }
239        }
240        let Self {
241            threshold,
242            max_subshares,
243            timeouts,
244            parameter_range,
245            auto_accept,
246            auto_respond_on_failure,
247            auto_reply_to,
248            unpair_ack,
249            unsafe_connection,
250            communication_info,
251            own_transports,
252            replica_id,
253            min_protocol_version,
254        } = top;
255        over(&mut self.threshold, threshold);
256        over(&mut self.max_subshares, max_subshares);
257        if let Some(t) = timeouts {
258            let TimeoutsConfig {
259                inbound_message_secs,
260                sharing_round_secs,
261                unpair_ack_secs,
262                get_share_response_secs,
263                pairing_secs,
264                expired_channels,
265            } = t;
266            let held = self.timeouts.get_or_insert_with(TimeoutsConfig::default);
267            over(&mut held.inbound_message_secs, inbound_message_secs);
268            over(&mut held.sharing_round_secs, sharing_round_secs);
269            over(&mut held.unpair_ack_secs, unpair_ack_secs);
270            over(&mut held.get_share_response_secs, get_share_response_secs);
271            over(&mut held.pairing_secs, pairing_secs);
272            over(&mut held.expired_channels, expired_channels);
273        }
274        over(&mut self.parameter_range, parameter_range);
275        over(&mut self.auto_accept, auto_accept);
276        over(&mut self.auto_respond_on_failure, auto_respond_on_failure);
277        over(&mut self.auto_reply_to, auto_reply_to);
278        over(&mut self.unpair_ack, unpair_ack);
279        over(&mut self.unsafe_connection, unsafe_connection);
280        over(&mut self.communication_info, communication_info);
281        over(&mut self.own_transports, own_transports);
282        over(&mut self.replica_id, replica_id);
283        over(&mut self.min_protocol_version, min_protocol_version);
284    }
285}
286
287#[cfg(test)]
288mod layer_tests {
289    use std::time::Duration;
290
291    use super::{DeRecProtocolConfig, ExpiredChannelsConfig, TimeoutsConfig};
292    use crate::protocol::UnpairAck;
293    use crate::protocol::types::Timeouts;
294
295    /// Layering B over A keeps every field B leaves unset, takes every
296    /// field B sets, and merges `timeouts` per field, so one held config
297    /// ends where `with_config(A)` then `with_config(B)` leaves a builder.
298    #[test]
299    fn layering_is_last_write_wins_per_field() {
300        let mut held = DeRecProtocolConfig {
301            threshold: Some(3),
302            replica_id: Some(7),
303            auto_reply_to: Some(true),
304            timeouts: Some(TimeoutsConfig {
305                sharing_round_secs: Some(30),
306                expired_channels: Some(ExpiredChannelsConfig {
307                    enabled: false,
308                    timeout_in_secs: 10,
309                }),
310                ..TimeoutsConfig::default()
311            }),
312            ..DeRecProtocolConfig::default()
313        };
314        held.layer(DeRecProtocolConfig {
315            threshold: Some(5),
316            unpair_ack: Some(UnpairAck::NotRequired),
317            timeouts: Some(TimeoutsConfig {
318                inbound_message_secs: Some(90),
319                ..TimeoutsConfig::default()
320            }),
321            ..DeRecProtocolConfig::default()
322        });
323        assert_eq!(
324            held,
325            DeRecProtocolConfig {
326                threshold: Some(5),
327                replica_id: Some(7),
328                auto_reply_to: Some(true),
329                unpair_ack: Some(UnpairAck::NotRequired),
330                timeouts: Some(TimeoutsConfig {
331                    inbound_message_secs: Some(90),
332                    sharing_round_secs: Some(30),
333                    unpair_ack_secs: None,
334                    get_share_response_secs: None,
335                    pairing_secs: None,
336                    expired_channels: Some(ExpiredChannelsConfig {
337                        enabled: false,
338                        timeout_in_secs: 10,
339                    }),
340                }),
341                ..DeRecProtocolConfig::default()
342            }
343        );
344        let t = held.timeouts.expect("set").merged_onto(Timeouts::default());
345        assert_eq!(t.inbound_message, Duration::from_secs(90));
346        assert_eq!(t.sharing_round, Duration::from_secs(30));
347        assert_eq!(t.unpair_ack, Timeouts::default().unpair_ack);
348    }
349
350    /// An empty config layers to no change.
351    #[test]
352    fn layering_an_empty_config_changes_nothing() {
353        let original = DeRecProtocolConfig {
354            threshold: Some(4),
355            timeouts: Some(TimeoutsConfig {
356                unpair_ack_secs: Some(12),
357                ..TimeoutsConfig::default()
358            }),
359            ..DeRecProtocolConfig::default()
360        };
361        let mut held = original.clone();
362        held.layer(DeRecProtocolConfig::default());
363        assert_eq!(held, original);
364    }
365}
366
367/// The serde form of [`DeRecProtocolConfig`]: the canonical JSON, field for
368/// field, converted to and from the public types.
369#[cfg(any(feature = "serde", target_arch = "wasm32"))]
370mod wire {
371    use std::collections::HashMap;
372
373    use derec_proto::ParameterRange;
374    use derec_proto::Protocol;
375    use serde::de;
376    use serde::de::IgnoredAny;
377    use serde::{Deserialize, Serialize};
378
379    use super::{DeRecProtocolConfig, TimeoutsConfig};
380    use crate::interop::protocol_names;
381    use crate::protocol::{AutoAcceptPolicy, UnpairAck};
382    use crate::protocol_version::ProtocolVersion;
383    use crate::transport::TransportProtocol;
384
385    #[derive(Serialize, Deserialize, Default)]
386    #[serde(default, deny_unknown_fields)]
387    pub(super) struct ConfigWire {
388        #[serde(skip_serializing_if = "Option::is_none")]
389        threshold: Option<usize>,
390        #[serde(skip_serializing_if = "Option::is_none")]
391        max_subshares: Option<DecimalU64>,
392        #[serde(skip_serializing_if = "Option::is_none")]
393        timeouts: Option<TimeoutsConfig>,
394        #[serde(skip_serializing_if = "Option::is_none")]
395        parameter_range: Option<ParameterRangeWire>,
396        #[serde(skip_serializing_if = "Option::is_none")]
397        auto_accept: Option<AutoAcceptWire>,
398        #[serde(skip_serializing_if = "Option::is_none")]
399        auto_respond_on_failure: Option<bool>,
400        #[serde(skip_serializing_if = "Option::is_none")]
401        auto_reply_to: Option<bool>,
402        #[serde(skip_serializing_if = "Option::is_none")]
403        unpair_ack: Option<UnpairAckWire>,
404        #[serde(skip_serializing_if = "Option::is_none")]
405        unsafe_connection: Option<bool>,
406        #[serde(skip_serializing_if = "Option::is_none")]
407        communication_info: Option<HashMap<String, String>>,
408        #[serde(skip_serializing_if = "Option::is_none")]
409        own_transports: Option<Vec<OwnTransportWire>>,
410        #[serde(skip_serializing_if = "Option::is_none")]
411        replica_id: Option<DecimalU64>,
412        #[serde(skip_serializing_if = "Option::is_none")]
413        min_protocol_version: Option<VersionWire>,
414    }
415
416    /// A protocol version as `{major, minor}`.
417    #[derive(Serialize, Deserialize)]
418    #[serde(deny_unknown_fields)]
419    struct VersionWire {
420        major: u32,
421        minor: u32,
422    }
423
424    /// One boolean per flow; an absent flow takes the policy default.
425    #[derive(Serialize, Deserialize)]
426    #[serde(default, deny_unknown_fields)]
427    struct AutoAcceptWire {
428        pairing: bool,
429        pre_pair: bool,
430        store_share: bool,
431        verify_share: bool,
432        discovery: bool,
433        get_share: bool,
434        unpair: bool,
435        update_channel_info: bool,
436    }
437
438    impl Default for AutoAcceptWire {
439        fn default() -> Self {
440            AutoAcceptPolicy::default().into()
441        }
442    }
443
444    impl From<AutoAcceptPolicy> for AutoAcceptWire {
445        fn from(p: AutoAcceptPolicy) -> Self {
446            Self {
447                pairing: p.pairing,
448                pre_pair: p.pre_pair,
449                store_share: p.store_share,
450                verify_share: p.verify_share,
451                discovery: p.discovery,
452                get_share: p.get_share,
453                unpair: p.unpair,
454                update_channel_info: p.update_channel_info,
455            }
456        }
457    }
458
459    impl From<AutoAcceptWire> for AutoAcceptPolicy {
460        fn from(p: AutoAcceptWire) -> Self {
461            Self {
462                pairing: p.pairing,
463                pre_pair: p.pre_pair,
464                store_share: p.store_share,
465                verify_share: p.verify_share,
466                discovery: p.discovery,
467                get_share: p.get_share,
468                unpair: p.unpair,
469                update_channel_info: p.update_channel_info,
470            }
471        }
472    }
473
474    /// [`derec_proto::ParameterRange`] with `snake_case` names. Every bound
475    /// defaults to `0`, the proto's "no bound".
476    #[derive(Serialize, Deserialize, Default)]
477    #[serde(default, deny_unknown_fields)]
478    struct ParameterRangeWire {
479        #[serde(deserialize_with = "i64_from_number_or_decimal")]
480        min_share_size: i64,
481        #[serde(deserialize_with = "i64_from_number_or_decimal")]
482        max_share_size: i64,
483        #[serde(deserialize_with = "i64_from_number_or_decimal")]
484        min_time_between_verifications: i64,
485        #[serde(deserialize_with = "i64_from_number_or_decimal")]
486        max_time_between_verifications: i64,
487        #[serde(deserialize_with = "i64_from_number_or_decimal")]
488        min_time_between_share_updates: i64,
489        #[serde(deserialize_with = "i64_from_number_or_decimal")]
490        max_time_between_share_updates: i64,
491        #[serde(deserialize_with = "i64_from_number_or_decimal")]
492        min_unresponsive_deletion_timeout: i64,
493        #[serde(deserialize_with = "i64_from_number_or_decimal")]
494        max_unresponsive_deletion_timeout: i64,
495        #[serde(deserialize_with = "i64_from_number_or_decimal")]
496        min_unresponsive_deactivation_timeout: i64,
497        #[serde(deserialize_with = "i64_from_number_or_decimal")]
498        max_unresponsive_deactivation_timeout: i64,
499    }
500
501    impl From<ParameterRange> for ParameterRangeWire {
502        fn from(r: ParameterRange) -> Self {
503            Self {
504                min_share_size: r.min_share_size,
505                max_share_size: r.max_share_size,
506                min_time_between_verifications: r.min_time_between_verifications,
507                max_time_between_verifications: r.max_time_between_verifications,
508                min_time_between_share_updates: r.min_time_between_share_updates,
509                max_time_between_share_updates: r.max_time_between_share_updates,
510                min_unresponsive_deletion_timeout: r.min_unresponsive_deletion_timeout,
511                max_unresponsive_deletion_timeout: r.max_unresponsive_deletion_timeout,
512                min_unresponsive_deactivation_timeout: r.min_unresponsive_deactivation_timeout,
513                max_unresponsive_deactivation_timeout: r.max_unresponsive_deactivation_timeout,
514            }
515        }
516    }
517
518    impl From<ParameterRangeWire> for ParameterRange {
519        fn from(r: ParameterRangeWire) -> Self {
520            Self {
521                min_share_size: r.min_share_size,
522                max_share_size: r.max_share_size,
523                min_time_between_verifications: r.min_time_between_verifications,
524                max_time_between_verifications: r.max_time_between_verifications,
525                min_time_between_share_updates: r.min_time_between_share_updates,
526                max_time_between_share_updates: r.max_time_between_share_updates,
527                min_unresponsive_deletion_timeout: r.min_unresponsive_deletion_timeout,
528                max_unresponsive_deletion_timeout: r.max_unresponsive_deletion_timeout,
529                min_unresponsive_deactivation_timeout: r.min_unresponsive_deactivation_timeout,
530                max_unresponsive_deactivation_timeout: r.max_unresponsive_deactivation_timeout,
531            }
532        }
533    }
534
535    /// Reads an `i64` written either as a JSON number or as a decimal string.
536    /// The string form carries the full `i64` range through JSON encoders
537    /// whose numbers are `f64`.
538    fn i64_from_number_or_decimal<'de, D>(de: D) -> Result<i64, D::Error>
539    where
540        D: serde::Deserializer<'de>,
541    {
542        #[derive(Deserialize)]
543        #[serde(untagged)]
544        enum NumberOrDecimal {
545            Number(i64),
546            Decimal(String),
547        }
548        match NumberOrDecimal::deserialize(de)? {
549            NumberOrDecimal::Number(n) => Ok(n),
550            NumberOrDecimal::Decimal(s) => s
551                .parse()
552                .map_err(|_| de::Error::custom(format!("{s:?} is not a decimal i64"))),
553        }
554    }
555
556    /// `unpair_ack`: its discriminant or its name.
557    #[derive(Serialize, Deserialize)]
558    #[serde(untagged)]
559    enum UnpairAckWire {
560        Code(i32),
561        Name(String),
562    }
563
564    impl UnpairAckWire {
565        fn resolve(self) -> Result<UnpairAck, String> {
566            match self {
567                Self::Code(0) => Ok(UnpairAck::Required),
568                Self::Code(1) => Ok(UnpairAck::NotRequired),
569                Self::Code(code) => Err(format!("invalid unpair_ack: {code}")),
570                Self::Name(name) => protocol_names::unpair_ack_from_name(&name)
571                    .ok_or_else(|| format!("invalid unpair_ack: {name:?}")),
572            }
573        }
574    }
575
576    /// One `own_transports` entry. `protocol` is read as a name or a
577    /// discriminant and written as a name.
578    #[derive(Serialize, Deserialize)]
579    #[serde(deny_unknown_fields)]
580    struct OwnTransportWire {
581        uri: String,
582        #[serde(
583            deserialize_with = "protocol_names::protocol_from_name_or_discriminant",
584            serialize_with = "protocol_as_name"
585        )]
586        protocol: i32,
587    }
588
589    fn protocol_as_name<S: serde::Serializer>(
590        discriminant: &i32,
591        ser: S,
592    ) -> Result<S::Ok, S::Error> {
593        match protocol_names::protocol_discriminant_to_name(*discriminant) {
594            Some(name) => ser.serialize_str(name),
595            None => ser.serialize_i32(*discriminant),
596        }
597    }
598
599    /// A `u64` field: a decimal string. Any other JSON value is kept only
600    /// so the error can name the field it was found in.
601    #[derive(Serialize, Deserialize)]
602    #[serde(untagged)]
603    enum DecimalU64 {
604        Decimal(String),
605        #[serde(skip_serializing)]
606        NotAString(IgnoredAny),
607    }
608
609    fn decimal_u64(field: &str, value: Option<DecimalU64>) -> Result<Option<u64>, String> {
610        value
611            .map(|v| match v {
612                DecimalU64::Decimal(s) => s
613                    .parse()
614                    .map_err(|_| format!("{field} is not a decimal u64: {s:?}")),
615                DecimalU64::NotAString(_) => {
616                    Err(format!("{field} must be a u64 written as a decimal string"))
617                }
618            })
619            .transpose()
620    }
621
622    impl TryFrom<ConfigWire> for DeRecProtocolConfig {
623        type Error = String;
624
625        fn try_from(w: ConfigWire) -> Result<Self, Self::Error> {
626            let own_transports = w
627                .own_transports
628                .map(|entries| {
629                    entries
630                        .into_iter()
631                        .map(|e| {
632                            let protocol = Protocol::try_from(e.protocol).map_err(|_| {
633                                format!("unknown transport protocol discriminant {}", e.protocol)
634                            })?;
635                            Ok(TransportProtocol::new(e.uri, protocol))
636                        })
637                        .collect::<Result<Vec<_>, String>>()
638                })
639                .transpose()?;
640            Ok(Self {
641                threshold: w.threshold,
642                max_subshares: decimal_u64("max_subshares", w.max_subshares)?,
643                timeouts: w.timeouts,
644                parameter_range: w.parameter_range.map(Into::into),
645                auto_accept: w.auto_accept.map(Into::into),
646                auto_respond_on_failure: w.auto_respond_on_failure,
647                auto_reply_to: w.auto_reply_to,
648                unpair_ack: w.unpair_ack.map(UnpairAckWire::resolve).transpose()?,
649                unsafe_connection: w.unsafe_connection,
650                communication_info: w.communication_info,
651                own_transports,
652                replica_id: decimal_u64("replica_id", w.replica_id)?,
653                min_protocol_version: w.min_protocol_version.map(|v| ProtocolVersion {
654                    major: v.major,
655                    minor: v.minor,
656                }),
657            })
658        }
659    }
660
661    impl From<DeRecProtocolConfig> for ConfigWire {
662        fn from(c: DeRecProtocolConfig) -> Self {
663            Self {
664                threshold: c.threshold,
665                max_subshares: c.max_subshares.map(|v| DecimalU64::Decimal(v.to_string())),
666                timeouts: c.timeouts,
667                parameter_range: c.parameter_range.map(Into::into),
668                auto_accept: c.auto_accept.map(Into::into),
669                auto_respond_on_failure: c.auto_respond_on_failure,
670                auto_reply_to: c.auto_reply_to,
671                unpair_ack: c.unpair_ack.map(|ack| {
672                    UnpairAckWire::Name(protocol_names::unpair_ack_to_name(ack).to_owned())
673                }),
674                unsafe_connection: c.unsafe_connection,
675                communication_info: c.communication_info,
676                own_transports: c.own_transports.map(|entries| {
677                    entries
678                        .into_iter()
679                        .map(|t| OwnTransportWire {
680                            uri: t.uri,
681                            protocol: t.protocol.into(),
682                        })
683                        .collect()
684                }),
685                replica_id: c.replica_id.map(|v| DecimalU64::Decimal(v.to_string())),
686                min_protocol_version: c.min_protocol_version.map(|v| VersionWire {
687                    major: v.major,
688                    minor: v.minor,
689                }),
690            }
691        }
692    }
693}
694
695#[cfg(all(test, any(feature = "serde", target_arch = "wasm32")))]
696mod tests {
697    use super::*;
698    use crate::protocol::{AutoAcceptPolicy, UnpairAck};
699    use derec_proto::Protocol;
700
701    const CANONICAL: &str = r#"{
702        "threshold": 4,
703        "max_subshares": "18446744073709551615",
704        "timeouts": {
705            "inbound_message_secs": 120,
706            "sharing_round_secs": 30,
707            "unpair_ack_secs": 45,
708            "get_share_response_secs": 900,
709            "pairing_secs": 240,
710            "expired_channels": { "enabled": false, "timeout_in_secs": 600 }
711        },
712        "parameter_range": {
713            "min_share_size": 1,
714            "max_share_size": 4096,
715            "min_time_between_verifications": 60,
716            "max_time_between_verifications": 0,
717            "min_time_between_share_updates": 0,
718            "max_time_between_share_updates": 0,
719            "min_unresponsive_deletion_timeout": 0,
720            "max_unresponsive_deletion_timeout": 0,
721            "min_unresponsive_deactivation_timeout": 0,
722            "max_unresponsive_deactivation_timeout": 0
723        },
724        "auto_accept": {
725            "pairing": true,
726            "pre_pair": false,
727            "store_share": true,
728            "verify_share": false,
729            "discovery": false,
730            "get_share": false,
731            "unpair": false,
732            "update_channel_info": false
733        },
734        "auto_respond_on_failure": true,
735        "auto_reply_to": true,
736        "unpair_ack": "not_required",
737        "unsafe_connection": true,
738        "communication_info": { "name": "alice" },
739        "own_transports": [
740            { "uri": "grpcs://me.example.com:443", "protocol": "grpc" },
741            { "uri": "https://me.example.com/derec", "protocol": "https" }
742        ],
743        "replica_id": "9007199254740993"
744    }"#;
745
746    fn parse(json: &str) -> Result<DeRecProtocolConfig, serde_json::Error> {
747        serde_json::from_str(json)
748    }
749
750    fn error_of(json: &str) -> String {
751        parse(json).expect_err("must be rejected").to_string()
752    }
753
754    #[test]
755    fn canonical_json_deserializes_into_every_field() {
756        let c = parse(CANONICAL).expect("canonical config parses");
757        assert_eq!(c.threshold, Some(4));
758        assert_eq!(c.max_subshares, Some(u64::MAX));
759        assert_eq!(
760            c.timeouts,
761            Some(TimeoutsConfig {
762                inbound_message_secs: Some(120),
763                sharing_round_secs: Some(30),
764                unpair_ack_secs: Some(45),
765                get_share_response_secs: Some(900),
766                pairing_secs: Some(240),
767                expired_channels: Some(ExpiredChannelsConfig {
768                    enabled: false,
769                    timeout_in_secs: 600,
770                }),
771            })
772        );
773        let range = c.parameter_range.expect("range present");
774        assert_eq!(range.min_share_size, 1);
775        assert_eq!(range.max_share_size, 4096);
776        assert_eq!(range.min_time_between_verifications, 60);
777        assert_eq!(
778            c.auto_accept,
779            Some(AutoAcceptPolicy {
780                pairing: true,
781                store_share: true,
782                ..Default::default()
783            })
784        );
785        assert_eq!(c.auto_respond_on_failure, Some(true));
786        assert_eq!(c.auto_reply_to, Some(true));
787        assert_eq!(c.unpair_ack, Some(UnpairAck::NotRequired));
788        assert_eq!(c.unsafe_connection, Some(true));
789        assert_eq!(
790            c.communication_info
791                .as_ref()
792                .and_then(|m| m.get("name"))
793                .map(String::as_str),
794            Some("alice")
795        );
796        assert_eq!(
797            c.own_transports,
798            Some(vec![
799                TransportProtocol::new("grpcs://me.example.com:443", Protocol::Grpc),
800                TransportProtocol::new("https://me.example.com/derec", Protocol::Https),
801            ])
802        );
803        assert_eq!(c.replica_id, Some(9_007_199_254_740_993));
804    }
805
806    #[test]
807    fn canonical_json_round_trips() {
808        let c = parse(CANONICAL).expect("canonical config parses");
809        let written = serde_json::to_value(&c).expect("serializes");
810        let original: serde_json::Value = serde_json::from_str(CANONICAL).unwrap();
811        assert_eq!(written, original);
812        assert_eq!(parse(&written.to_string()).expect("re-parses"), c);
813    }
814
815    #[test]
816    fn empty_object_is_the_default_and_serializes_back_to_empty() {
817        let c = parse("{}").expect("empty config parses");
818        assert_eq!(c, DeRecProtocolConfig::default());
819        assert_eq!(serde_json::to_string(&c).unwrap(), "{}");
820    }
821
822    /// `null` reads as "not set", as the FFI config has always accepted.
823    #[test]
824    fn null_fields_read_as_unset() {
825        let c = parse(r#"{ "replica_id": null, "max_subshares": null, "timeouts": null }"#)
826            .expect("nulls parse");
827        assert_eq!(c, DeRecProtocolConfig::default());
828    }
829
830    #[test]
831    fn unknown_keys_are_rejected_at_every_level() {
832        assert!(error_of(r#"{ "treshold": 3 }"#).contains("treshold"));
833        assert!(error_of(r#"{ "secret_id": "1" }"#).contains("secret_id"));
834        assert!(error_of(r#"{ "timeouts": { "sharing_round": 30 } }"#).contains("sharing_round"));
835        assert!(
836            error_of(r#"{ "timeouts": { "expired_channels": { "enabled": true, "timeout_in_secs": 1, "x": 1 } } }"#)
837                .contains('x')
838        );
839        assert!(error_of(r#"{ "auto_accept": { "pair": true } }"#).contains("pair"));
840        assert!(error_of(r#"{ "parameter_range": { "min_size": 1 } }"#).contains("min_size"));
841        assert!(
842            error_of(r#"{ "own_transports": [{ "uri": "https://a.example", "protocol": "https", "port": 1 }] }"#)
843                .contains("port")
844        );
845    }
846
847    /// `u64` values travel as decimal strings so they survive encoders whose
848    /// numbers are `f64`; a bare JSON number or a non-decimal is refused.
849    #[test]
850    fn u64_fields_are_decimal_strings() {
851        let c = parse(r#"{ "replica_id": "18446744073709551615", "max_subshares": "7" }"#)
852            .expect("decimal strings parse");
853        assert_eq!(c.replica_id, Some(u64::MAX));
854        assert_eq!(c.max_subshares, Some(7));
855        assert_eq!(
856            serde_json::to_value(&c).unwrap(),
857            serde_json::json!({ "replica_id": "18446744073709551615", "max_subshares": "7" })
858        );
859
860        assert!(error_of(r#"{ "replica_id": 5 }"#).contains("replica_id"));
861        assert!(error_of(r#"{ "replica_id": "12x" }"#).contains("replica_id"));
862        assert!(error_of(r#"{ "max_subshares": "-1" }"#).contains("max_subshares"));
863    }
864
865    #[test]
866    fn unpair_ack_takes_its_name_or_discriminant() {
867        let read = |v: &str| parse(&format!(r#"{{ "unpair_ack": {v} }}"#)).map(|c| c.unpair_ack);
868        assert_eq!(read("0").unwrap(), Some(UnpairAck::Required));
869        assert_eq!(read("1").unwrap(), Some(UnpairAck::NotRequired));
870        assert_eq!(read(r#""required""#).unwrap(), Some(UnpairAck::Required));
871        assert_eq!(
872            read(r#""not_required""#).unwrap(),
873            Some(UnpairAck::NotRequired)
874        );
875        for bad in ["2", "-1", r#""Required""#, r#""notrequired""#] {
876            assert!(read(bad).is_err(), "{bad} must be refused");
877        }
878    }
879
880    #[test]
881    fn own_transport_protocol_takes_its_name_or_discriminant() {
882        let c = parse(
883            r#"{ "own_transports": [
884                { "uri": "https://a.example", "protocol": 0 },
885                { "uri": "grpcs://a.example:443", "protocol": "GRPC" }
886            ] }"#,
887        )
888        .expect("both spellings parse");
889        let transports = c.own_transports.expect("present");
890        assert_eq!(transports[0].protocol, Protocol::Https);
891        assert_eq!(transports[1].protocol, Protocol::Grpc);
892        assert!(
893            parse(r#"{ "own_transports": [{ "uri": "https://a.example", "protocol": "ftp" }] }"#)
894                .is_err()
895        );
896        assert!(
897            parse(r#"{ "own_transports": [{ "uri": "https://a.example", "protocol": 99 }] }"#)
898                .is_err()
899        );
900    }
901
902    /// A partial `auto_accept` object leaves each unnamed flow at the policy
903    /// default; the object as a whole replaces the builder's policy.
904    #[test]
905    fn partial_auto_accept_defaults_each_absent_flow() {
906        let c = parse(r#"{ "auto_accept": { "pairing": true } }"#).expect("parses");
907        assert_eq!(
908            c.auto_accept,
909            Some(AutoAcceptPolicy {
910                pairing: true,
911                ..Default::default()
912            })
913        );
914    }
915
916    /// Parameter-range bounds accept JSON numbers or decimal strings, and an
917    /// absent bound is `0`.
918    #[test]
919    fn parameter_range_bounds_take_numbers_or_decimal_strings() {
920        let c = parse(
921            r#"{ "parameter_range": {
922                "min_share_size": "9007199254740993",
923                "max_share_size": 4096,
924                "max_unresponsive_deactivation_timeout": "-9223372036854775808"
925            } }"#,
926        )
927        .expect("parses");
928        let range = c.parameter_range.expect("present");
929        assert_eq!(range.min_share_size, 9_007_199_254_740_993);
930        assert_eq!(range.max_share_size, 4096);
931        assert_eq!(range.max_unresponsive_deactivation_timeout, i64::MIN);
932        assert_eq!(range.min_time_between_verifications, 0);
933        assert!(parse(r#"{ "parameter_range": { "min_share_size": "12x" } }"#).is_err());
934    }
935
936    /// Timeouts must be whole, non-negative seconds.
937    #[test]
938    fn timeouts_refuse_fractional_or_negative_seconds() {
939        assert!(parse(r#"{ "timeouts": { "sharing_round_secs": 1.5 } }"#).is_err());
940        assert!(parse(r#"{ "timeouts": { "sharing_round_secs": -1 } }"#).is_err());
941    }
942
943    /// The JSON `derec_protocol_new` has always documented, minus
944    /// `secret_id`, is a valid config.
945    #[test]
946    fn the_documented_ffi_config_shape_is_accepted() {
947        let c = parse(
948            r#"{
949                "own_transports": [{ "uri": "https://example.com/derec", "protocol": "https" }],
950                "threshold": 3,
951                "auto_respond_on_failure": false,
952                "unpair_ack": 0,
953                "auto_reply_to": false,
954                "auto_accept": {
955                    "pairing": false, "pre_pair": false, "store_share": false,
956                    "verify_share": false, "discovery": false, "get_share": false,
957                    "unpair": false, "update_channel_info": false
958                },
959                "timeouts": {
960                    "inbound_message_secs": 300,
961                    "sharing_round_secs": 60,
962                    "unpair_ack_secs": 60,
963                    "expired_channels": { "enabled": true, "timeout_in_secs": 300 }
964                },
965                "unsafe_connection": false,
966                "replica_id": null,
967                "parameter_range": {
968                    "min_share_size": 0, "max_share_size": 0,
969                    "min_time_between_verifications": 0, "max_time_between_verifications": 0,
970                    "min_time_between_share_updates": 0, "max_time_between_share_updates": 0,
971                    "min_unresponsive_deletion_timeout": 0, "max_unresponsive_deletion_timeout": 0,
972                    "min_unresponsive_deactivation_timeout": 0,
973                    "max_unresponsive_deactivation_timeout": 0
974                },
975                "max_subshares": null
976            }"#,
977        )
978        .expect("documented shape parses");
979        assert_eq!(c.threshold, Some(3));
980        assert_eq!(c.unpair_ack, Some(UnpairAck::Required));
981        assert_eq!(c.replica_id, None);
982        assert_eq!(c.max_subshares, None);
983    }
984}