Skip to main content

syncspin_client/
config.rs

1//! Connection configuration.
2
3use std::fmt;
4use std::sync::Arc;
5use std::time::Duration;
6
7use anyhow::{bail, Result};
8use syncspin_core::noise::Identity;
9
10use crate::client::MAX_VOLUME;
11use crate::storage::Storage;
12
13/// Longest player name the protocol allows, in bytes of UTF-8.
14pub const MAX_PLAYER_NAME_LEN: usize = 64;
15
16/// Number of digits in a static pairing code.
17///
18/// The protocol fixes the length at eight decimal digits, so a configured code is exactly this
19/// many ASCII characters.
20#[cfg(feature = "pairing-code")]
21pub const STATIC_PAIRING_CODE_LEN: usize = 8;
22
23/// Longest `client/pair-pending` message the protocol allows, in bytes of UTF-8.
24#[cfg(feature = "pairing-code")]
25pub const MAX_PAIRING_PENDING_TEXT_LEN: usize = 200;
26
27/// How long an operator-opened pairing window admits attempts.
28///
29/// `pairing.md` recommends five minutes and starts the clock at the gesture, not at the first
30/// attempt.
31#[cfg(feature = "pairing-code")]
32pub const DEFAULT_PAIRING_WINDOW: Duration = Duration::from_secs(300);
33
34/// Emission format of a dynamic pairing code.
35///
36/// `pairing.md` defines two: `digits`, a six-digit decimal code the operator types into the
37/// server, and `qr_code`, a 24-byte code presented as a version-1 pairing token in a QR code. The
38/// format is chosen per connection by the server's `server/activate`, from the formats the client
39/// advertises; it decides how a host presents the code and what CPace's `PRS` is.
40#[cfg(feature = "pairing-code")]
41#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42pub enum CodeFormat {
43    /// Six decimal digits.
44    Digits,
45    /// A 24-byte code as a version-1 pairing token.
46    QrCode,
47}
48
49#[cfg(feature = "pairing-code")]
50impl CodeFormat {
51    /// Returns the identifier the wire and `client/hello` use.
52    pub(crate) fn as_wire(self) -> &'static str {
53        match self {
54            CodeFormat::Digits => "digits",
55            CodeFormat::QrCode => "qr_code",
56        }
57    }
58
59    /// Decodes an emission format from the wire, or `None` for a value this revision does not know.
60    pub(crate) fn from_wire(value: &str) -> Option<CodeFormat> {
61        match value {
62            "digits" => Some(CodeFormat::Digits),
63            "qr_code" => Some(CodeFormat::QrCode),
64            _ => None,
65        }
66    }
67}
68
69/// Channel a dynamic pairing code reaches the operator through.
70///
71/// The client advertises the channels its host can actually drive. `display` covers a screen, an
72/// e-ink panel or a seven-segment display; `speaker` covers a device that speaks the code from
73/// audio it bundles itself. The crate derives the code and emits it; rendering and speaking belong
74/// to the host.
75#[cfg(feature = "pairing-code")]
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77pub enum CodeOutChannel {
78    /// A display the host renders the code on.
79    Display,
80    /// A speaker the host plays the code through.
81    Speaker,
82}
83
84#[cfg(feature = "pairing-code")]
85impl CodeOutChannel {
86    /// Returns the identifier the wire and `client/hello` use.
87    pub(crate) fn as_wire(self) -> &'static str {
88        match self {
89            CodeOutChannel::Display => "display",
90            CodeOutChannel::Speaker => "speaker",
91        }
92    }
93}
94
95/// How the client wants the stream delivered.
96#[derive(Debug, Clone, Copy, PartialEq, Eq)]
97pub enum AudioMode {
98    /// Play raw samples.
99    ///
100    /// The session advertises PCM only, so the server delivers raw samples and the sink receives
101    /// [`AudioFrame::Pcm`](crate::AudioFrame::Pcm). An encoded stream would need a decoder this
102    /// build does not carry, so the session rejects one instead of handing encoded bytes to a
103    /// sink that expects samples.
104    Decode,
105    /// Forward encoded frames.
106    ///
107    /// The session advertises the encoded formats it can forward and the sink receives
108    /// [`AudioFrame::Encoded`](crate::AudioFrame::Encoded). A PCM stream still arrives as
109    /// [`AudioFrame::Pcm`](crate::AudioFrame::Pcm), because there is nothing to decode.
110    Passthrough,
111}
112
113/// Category of a pre-shared key, as the server announces it in Noise message 1.
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub enum PskCategory {
116    /// Long-term pairing key.
117    LongTerm,
118    /// Key for one pairing attempt.
119    Pairing,
120    /// The published key that authenticates nothing.
121    Sentinel,
122}
123
124impl PskCategory {
125    /// Decodes the two-letter category from the wire.
126    pub(crate) fn from_wire(value: &str) -> Option<PskCategory> {
127        match value {
128            "lt" => Some(PskCategory::LongTerm),
129            "pr" => Some(PskCategory::Pairing),
130            "sn" => Some(PskCategory::Sentinel),
131            _ => None,
132        }
133    }
134
135    /// Encodes the category the way the wire and a stored record spell it.
136    ///
137    /// The inverse of [`from_wire`](PskCategory::from_wire), so a backend this crate ships can
138    /// write a record it reads back with the same meaning.
139    #[cfg(feature = "storage-file")]
140    pub(crate) fn as_wire(self) -> &'static str {
141        match self {
142            PskCategory::LongTerm => "lt",
143            PskCategory::Pairing => "pr",
144            PskCategory::Sentinel => "sn",
145        }
146    }
147}
148
149/// Limits the session applies to a volume request.
150///
151/// A request at or below [`threshold`](VolumePolicy::threshold) is applied as asked, whether it
152/// raises or lowers the level. Above the threshold, one request may raise the level by at most
153/// [`max_step`](VolumePolicy::max_step); a lower request is still applied as asked, because the
154/// limit bounds raises only. The configuration validation rejects a policy that cannot describe a
155/// valid level before a connection is attempted.
156///
157/// [`VolumePolicy::default`] is the rule [`clamp_volume`](crate::clamp_volume) implements, so a
158/// host that does not configure a policy keeps the behaviour of earlier releases.
159#[derive(Debug, Clone, Copy, PartialEq, Eq)]
160pub struct VolumePolicy {
161    /// At or below this level a request is applied as is, in the protocol's 0-100 range.
162    pub threshold: u8,
163    /// Above the threshold, at most this much may be added per command.
164    pub max_step: u8,
165    /// Whether a request above the threshold may always rise to the threshold itself.
166    ///
167    /// With `false` a low level creeps up by [`max_step`](VolumePolicy::max_step) per command, so
168    /// 1 + a request for 100 yields 21. With `true` the same request yields the threshold, 40,
169    /// because a level below the threshold may always reach it in one step.
170    pub threshold_floor: bool,
171}
172
173impl Default for VolumePolicy {
174    /// Returns the policy [`clamp_volume`](crate::clamp_volume) implements.
175    fn default() -> Self {
176        Self {
177            threshold: 40,
178            max_step: 20,
179            threshold_floor: false,
180        }
181    }
182}
183
184/// A pre-shared key the host stores for a known server.
185///
186/// Selection after Noise message 1 compares the announced category and key id; a match is only
187/// accepted when `server_id` equals the one in `server/init`. The key itself is never formatted or
188/// logged: `Debug` prints it redacted.
189#[derive(Clone, PartialEq, Eq)]
190pub struct StoredPsk {
191    /// Category the key belongs to.
192    pub category: PskCategory,
193    /// The 32-byte key.
194    pub psk: [u8; 32],
195    /// Static public key of the server this key belongs to, as announced in `server/init`.
196    pub server_id: String,
197}
198
199impl fmt::Debug for StoredPsk {
200    /// Formats the record with the key material redacted.
201    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
202        formatter
203            .debug_struct("StoredPsk")
204            .field("category", &self.category)
205            .field("psk", &"<redacted>")
206            .field("server_id", &self.server_id)
207            .finish()
208    }
209}
210
211/// What the client announces about the device it runs on.
212///
213/// The server shows these values to the operator, so they name the hardware rather than the
214/// protocol: a product name and a manufacturer are always sent, and the software version and MAC
215/// address are sent when the host knows them. The fields are plain text; the crate sends them as
216/// the host provides them, so their content and length belong to the host.
217#[derive(Debug, Clone, Default, PartialEq, Eq)]
218pub struct DeviceInfo {
219    /// Device model or product name.
220    pub product_name: String,
221    /// Device manufacturer.
222    pub manufacturer: String,
223    /// Software version of the host application, not the protocol version.
224    pub software_version: Option<String>,
225    /// Network interface MAC address as lowercase colon-separated bytes.
226    pub mac_address: Option<String>,
227}
228
229/// Everything the client needs to open a session.
230///
231/// The identity is the client's long-lived X25519 keypair. It also becomes the `client_id` the
232/// server sees, so reusing it keeps the player recognisable across reconnects; the crate never
233/// generates or replaces one on its own.
234#[derive(Clone)]
235pub struct ClientConfig {
236    /// Server address as `host:port`, or a full `ws://` URL.
237    ///
238    /// A bare address connects to `ws://<server>/sendspin`. TLS is not part of this build, so a
239    /// `wss://` URL is rejected rather than silently downgraded.
240    pub server: String,
241    /// Friendly name announced to the server, non-empty and at most [`MAX_PLAYER_NAME_LEN`] bytes.
242    pub player_name: String,
243    /// Description of the device the client runs on, announced in `client/hello`.
244    ///
245    /// The server displays it to the operator. A host that does not know the hardware passes
246    /// `None` and no `device_info` object is sent, so the server shows only the player name.
247    pub device_info: Option<DeviceInfo>,
248    /// Long-lived keypair that identifies this client.
249    ///
250    /// Restore a stored keypair with [`Identity::from_secret_base64`]; generating a fresh one
251    /// makes the server treat the player as a new device.
252    pub identity: Identity,
253    /// Where the pairing PSK and the pairing records live, or `None` for a guest-only client.
254    ///
255    /// The host owns the store; see [`Storage`]. With a store the client offers the Pairing PSK
256    /// method, keeps one pairing PSK across restarts and writes a record for every completed
257    /// pairing. Without one it offers no pairing method at all: it never draws a key it cannot
258    /// hand back, and it answers a pairing activation with `pair/abort` reason
259    /// `method_not_supported`. A plain guest session is unchanged either way.
260    pub storage: Option<Arc<dyn Storage>>,
261    /// Whether the sink receives samples or encoded frames.
262    pub audio_mode: AudioMode,
263    /// Output level to start from, in the protocol's 0-100 range.
264    ///
265    /// The session reports this level in its first `client/state` and applies the volume limit
266    /// against it, so a host passes the level it restored instead of an invented one. A host
267    /// without a stored level passes 100, which neither attenuates nor limits an incoming request.
268    pub volume: u8,
269    /// Mute state to start from.
270    ///
271    /// Reported in the first `client/state`; a host without a stored state passes `false`.
272    pub muted: bool,
273    /// Limits applied to every volume request.
274    ///
275    /// The session applies the policy to a command from the server and to a level the host sets
276    /// through [`ControlHandle::set_volume`](crate::ControlHandle::set_volume); the value it
277    /// reports back is always the applied one. [`VolumePolicy::default`] keeps the fixed rule of
278    /// earlier releases.
279    pub volume_policy: VolumePolicy,
280    /// Upper bound for the delay between reconnects.
281    ///
282    /// The connection reports a recommended delay in
283    /// [`Event::Disconnected`](crate::Event::Disconnected) and waits it before the next attempt;
284    /// [`next_backoff`](crate::next_backoff) never returns more than this.
285    pub max_backoff: Duration,
286    /// How long one pairing attempt may run, measured from `client/pair-init`.
287    ///
288    /// On expiry the client sends `pair/abort` with reason `attempt_timeout` and reports
289    /// [`Event::PairingFailed`](crate::Event::PairingFailed). The protocol recommends two minutes,
290    /// which is [`DEFAULT_PAIRING_TIMEOUT`](crate::DEFAULT_PAIRING_TIMEOUT); a host shortens it
291    /// only for tests or for a deployment that wants a tighter bound.
292    pub pairing_timeout: Duration,
293    /// The operator-facing static pairing code, exactly eight decimal digits.
294    ///
295    /// The code is configuration, never generated: a manufacturer provisions one per device, and
296    /// the operator reads it off the device or its leaflet. Offering the static code method in
297    /// `client/hello` depends on this field being set, so a client without a code never advertises
298    /// a method it cannot complete.
299    ///
300    /// The code is a credential: anyone who knows it and can reach the server may pair. It is
301    /// never formatted - [`ClientConfig`]'s `Debug` prints it redacted - and never logged.
302    #[cfg(feature = "pairing-code")]
303    pub static_pairing_code: Option<String>,
304    /// How long an operator-opened pairing window admits attempts, recommended five minutes.
305    ///
306    /// The window runs from [`ControlHandle::open_pairing_window`](crate::ControlHandle::open_pairing_window)
307    /// and does not pause during an attempt. On expiry it closes silently; an attempt already in
308    /// progress runs to its own end.
309    #[cfg(feature = "pairing-code")]
310    pub pairing_window: Duration,
311    /// Sentence sent in `client/pair-pending`, in the host's language.
312    ///
313    /// A host that wants to tell the operator what to do sets it here; without one the message is
314    /// sent with no text, because the crate does not invent operator-facing prose.
315    #[cfg(feature = "pairing-code")]
316    pub pairing_pending_text: Option<String>,
317    /// Emission formats the client offers for a dynamic pairing code.
318    ///
319    /// An empty list offers no dynamic method at all; a non-empty one advertises
320    /// `dynamic_pairing_code` in `client/hello`, together with [`ClientConfig::code_out_channels`].
321    /// Both lists must be set for the method to be offered, because the protocol treats a
322    /// descriptor left without a known format or channel as unrecognized. The code itself is
323    /// derived per attempt, never configured.
324    #[cfg(feature = "pairing-code")]
325    pub code_formats: Vec<CodeFormat>,
326    /// Channels the host can carry a dynamic pairing code through.
327    ///
328    /// The host sets what it can render or speak; the server picks the method's format, and the
329    /// client emits the code through [`Event::PairingCode`](crate::Event::PairingCode).
330    #[cfg(feature = "pairing-code")]
331    pub code_out_channels: Vec<CodeOutChannel>,
332}
333
334impl fmt::Debug for ClientConfig {
335    /// Formats the configuration without the store and without key material.
336    ///
337    /// The store holds the pairing PSK and the records, and its own `Debug` is the host's; the
338    /// identity redacts its secret. Neither is delegated to here, so a `Debug` log of a
339    /// configuration cannot leak a key.
340    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
341        let mut debug = formatter.debug_struct("ClientConfig");
342        debug
343            .field("server", &self.server)
344            .field("player_name", &self.player_name)
345            .field("device_info", &self.device_info)
346            .field("identity", &self.identity)
347            .field("storage", &self.storage.as_ref().map(|_| "<host storage>"))
348            .field("audio_mode", &self.audio_mode)
349            .field("volume", &self.volume)
350            .field("muted", &self.muted)
351            .field("volume_policy", &self.volume_policy)
352            .field("max_backoff", &self.max_backoff)
353            .field("pairing_timeout", &self.pairing_timeout);
354        // The static code is a credential, so it is named but never printed.
355        #[cfg(feature = "pairing-code")]
356        debug
357            .field(
358                "static_pairing_code",
359                &self.static_pairing_code.as_ref().map(|_| "<redacted>"),
360            )
361            .field("pairing_window", &self.pairing_window)
362            .field("pairing_pending_text", &self.pairing_pending_text)
363            .field("code_formats", &self.code_formats)
364            .field("code_out_channels", &self.code_out_channels);
365        debug.finish()
366    }
367}
368
369impl ClientConfig {
370    /// Rejects a configuration that would put invalid fields on the wire.
371    pub(crate) fn validate(&self) -> Result<()> {
372        if self.server.trim().is_empty() {
373            bail!("ClientConfig::server must not be empty");
374        }
375        if self.player_name.trim().is_empty() {
376            bail!("ClientConfig::player_name must not be empty");
377        }
378        if self.player_name.len() > MAX_PLAYER_NAME_LEN {
379            bail!(
380                "ClientConfig::player_name is {} bytes, more than the {MAX_PLAYER_NAME_LEN} the \
381                 protocol allows",
382                self.player_name.len()
383            );
384        }
385        if self.volume > MAX_VOLUME {
386            bail!(
387                "ClientConfig::volume is {}, outside the 0-{MAX_VOLUME} the protocol defines",
388                self.volume
389            );
390        }
391        if self.volume_policy.threshold > MAX_VOLUME {
392            bail!(
393                "ClientConfig::volume_policy.threshold is {}, outside the 0-{MAX_VOLUME} level \
394                 range",
395                self.volume_policy.threshold
396            );
397        }
398        if self.volume_policy.max_step > MAX_VOLUME {
399            bail!(
400                "ClientConfig::volume_policy.max_step is {}, outside the 0-{MAX_VOLUME} step \
401                 range",
402                self.volume_policy.max_step
403            );
404        }
405        if self.max_backoff.is_zero() {
406            bail!("ClientConfig::max_backoff must not be zero");
407        }
408        if self.pairing_timeout.is_zero() {
409            bail!("ClientConfig::pairing_timeout must not be zero");
410        }
411        #[cfg(feature = "pairing-code")]
412        {
413            if let Some(code) = &self.static_pairing_code {
414                if code.len() != STATIC_PAIRING_CODE_LEN
415                    || !code.bytes().all(|byte| byte.is_ascii_digit())
416                {
417                    // The code itself is a credential, so the error names the shape, never the
418                    // value the host passed.
419                    bail!(
420                        "ClientConfig::static_pairing_code must be {STATIC_PAIRING_CODE_LEN} \
421                         ASCII digits"
422                    );
423                }
424            }
425            if self.pairing_window.is_zero() {
426                bail!("ClientConfig::pairing_window must not be zero");
427            }
428            if let Some(text) = &self.pairing_pending_text {
429                if text.len() > MAX_PAIRING_PENDING_TEXT_LEN {
430                    bail!(
431                        "ClientConfig::pairing_pending_text is {} bytes, more than the \
432                         {MAX_PAIRING_PENDING_TEXT_LEN} the protocol allows",
433                        text.len()
434                    );
435                }
436            }
437            // A descriptor with formats but no channel - or the other way round - is one a server
438            // treats as unrecognized, so the client would advertise a method it cannot complete.
439            if self.code_formats.is_empty() != self.code_out_channels.is_empty() {
440                bail!(
441                    "ClientConfig::code_formats and ClientConfig::code_out_channels must both be \
442                     set or both be empty"
443                );
444            }
445        }
446        Ok(())
447    }
448}
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    /// A configuration that passes validation, for tests that change one field.
455    fn valid() -> ClientConfig {
456        ClientConfig {
457            server: "127.0.0.1:1".to_owned(),
458            player_name: "Test player".to_owned(),
459            device_info: None,
460            identity: Identity::generate(),
461            storage: None,
462            audio_mode: AudioMode::Passthrough,
463            volume: 100,
464            muted: false,
465            volume_policy: VolumePolicy::default(),
466            max_backoff: Duration::from_secs(1),
467            pairing_timeout: crate::DEFAULT_PAIRING_TIMEOUT,
468            #[cfg(feature = "pairing-code")]
469            static_pairing_code: None,
470            #[cfg(feature = "pairing-code")]
471            pairing_window: DEFAULT_PAIRING_WINDOW,
472            #[cfg(feature = "pairing-code")]
473            pairing_pending_text: None,
474            #[cfg(feature = "pairing-code")]
475            code_formats: Vec::new(),
476            #[cfg(feature = "pairing-code")]
477            code_out_channels: Vec::new(),
478        }
479    }
480
481    #[test]
482    fn the_pairing_timeout_must_be_positive() {
483        let config = ClientConfig {
484            pairing_timeout: Duration::ZERO,
485            ..valid()
486        };
487        let error = config
488            .validate()
489            .expect_err("a zero timeout would abort every attempt at once");
490        assert!(
491            format!("{error:#}").contains("pairing_timeout"),
492            "the error must name the field, got: {error:#}"
493        );
494        config_with_default_timeout()
495            .validate()
496            .expect("120s is valid");
497    }
498
499    /// A configuration with the protocol's recommended attempt timeout.
500    fn config_with_default_timeout() -> ClientConfig {
501        let config = valid();
502        assert_eq!(config.pairing_timeout, crate::DEFAULT_PAIRING_TIMEOUT);
503        config
504    }
505
506    #[test]
507    fn a_configuration_debug_names_no_key_material() {
508        let store = std::sync::Arc::new(crate::test_support::MemoryStore::holding([7u8; 32]));
509        let config = ClientConfig {
510            storage: Some(store),
511            ..valid()
512        };
513        let text = format!("{config:?}");
514        assert!(text.contains("ClientConfig"), "unexpected format: {text}");
515        assert!(
516            text.contains("<host storage>"),
517            "the store is named but never delegated to: {text}"
518        );
519        assert!(
520            !text.contains(&config.identity.secret_base64()),
521            "the identity secret must stay out of a debug format: {text}"
522        );
523    }
524
525    #[test]
526    fn a_stored_psk_formats_without_its_key_material() {
527        use base64::engine::general_purpose::URL_SAFE_NO_PAD;
528        use base64::Engine as _;
529
530        let psk = [0xab; 32];
531        let record = StoredPsk {
532            category: PskCategory::Pairing,
533            psk,
534            server_id: "B1y4w7z0c3f6i9l2o5r8u1x4a7d0g3j6m9p2s5v8y1b".to_owned(),
535        };
536        let text = format!("{record:?}");
537        assert!(text.contains("StoredPsk"), "unexpected format: {text}");
538        assert!(text.contains("Pairing"), "the category is not key material");
539        assert!(text.contains("B1y4w7z0c3f6i9l2o5r8u1x4a7d0g3j6m9p2s5v8y1b"));
540        assert!(text.contains("<redacted>"));
541        assert!(
542            !text.contains(&URL_SAFE_NO_PAD.encode(psk)),
543            "the key must never appear in a debug format: {text}"
544        );
545        assert!(
546            !text.contains(&format!("{psk:?}")),
547            "not even the raw bytes may appear: {text}"
548        );
549    }
550
551    /// The dynamic method's descriptor needs a format and a channel; one without the other is
552    /// treated as unrecognized by a server, so the configuration refuses it before a connection.
553    #[cfg(feature = "pairing-code")]
554    #[test]
555    fn the_code_descriptor_lists_are_set_together() {
556        let formats_only = ClientConfig {
557            code_formats: vec![CodeFormat::Digits],
558            ..valid()
559        };
560        let error = formats_only
561            .validate()
562            .expect_err("a format without a channel is not a usable descriptor");
563        assert!(
564            format!("{error:#}").contains("code_out_channels"),
565            "the error names the missing list, got: {error:#}"
566        );
567
568        let channels_only = ClientConfig {
569            code_out_channels: vec![CodeOutChannel::Display],
570            ..valid()
571        };
572        let error = channels_only
573            .validate()
574            .expect_err("a channel without a format is not a usable descriptor");
575        assert!(
576            format!("{error:#}").contains("code_formats"),
577            "the error names the missing list, got: {error:#}"
578        );
579
580        ClientConfig {
581            code_formats: vec![CodeFormat::Digits, CodeFormat::QrCode],
582            code_out_channels: vec![CodeOutChannel::Display],
583            ..valid()
584        }
585        .validate()
586        .expect("both lists make the method offerable");
587    }
588
589    /// The identifiers are the ones `client/hello` and `server/activate` spell.
590    #[cfg(feature = "pairing-code")]
591    #[test]
592    fn the_code_types_round_trip_through_their_wire_names() {
593        assert_eq!(CodeFormat::Digits.as_wire(), "digits");
594        assert_eq!(CodeFormat::QrCode.as_wire(), "qr_code");
595        assert_eq!(CodeFormat::from_wire("digits"), Some(CodeFormat::Digits));
596        assert_eq!(CodeFormat::from_wire("qr_code"), Some(CodeFormat::QrCode));
597        assert_eq!(
598            CodeFormat::from_wire("nfc"),
599            None,
600            "a format this revision does not know selects nothing"
601        );
602        assert_eq!(CodeOutChannel::Display.as_wire(), "display");
603        assert_eq!(CodeOutChannel::Speaker.as_wire(), "speaker");
604    }
605
606    #[test]
607    fn an_empty_server_address_is_rejected() {
608        for server in ["", "   "] {
609            let config = ClientConfig {
610                server: server.to_owned(),
611                ..valid()
612            };
613            let error = config.validate().expect_err("an empty address has no host");
614            assert!(
615                format!("{error:#}").contains("server"),
616                "the error must name the address, got: {error:#}"
617            );
618        }
619    }
620
621    #[test]
622    fn a_player_name_is_bounded_by_the_protocol_length() {
623        let longest = ClientConfig {
624            player_name: "a".repeat(MAX_PLAYER_NAME_LEN),
625            ..valid()
626        };
627        longest
628            .validate()
629            .expect("a name at the limit must be accepted");
630
631        let config = ClientConfig {
632            player_name: "a".repeat(MAX_PLAYER_NAME_LEN + 1),
633            ..valid()
634        };
635        let error = config
636            .validate()
637            .expect_err("a name above the limit must be rejected");
638        let message = format!("{error:#}");
639        assert!(
640            message.contains("player_name")
641                && message.contains(&(MAX_PLAYER_NAME_LEN + 1).to_string()),
642            "the error must name the field and the length, got: {message}"
643        );
644
645        let config = ClientConfig {
646            player_name: " \t ".to_owned(),
647            ..valid()
648        };
649        let error = config
650            .validate()
651            .expect_err("a blank name must be rejected");
652        assert!(format!("{error:#}").contains("player_name"));
653    }
654
655    /// The protocol fixes the code at eight decimal digits; anything else cannot be entered.
656    #[cfg(feature = "pairing-code")]
657    #[test]
658    fn a_static_pairing_code_is_exactly_eight_digits() {
659        for code in ["12345678", "00000000", "99999999"] {
660            let config = ClientConfig {
661                static_pairing_code: Some(code.to_owned()),
662                ..valid()
663            };
664            config
665                .validate()
666                .unwrap_or_else(|error| panic!("{code:?} must be accepted: {error:#}"));
667        }
668
669        for code in [
670            "",
671            "1234567",
672            "123456789",
673            "1234 678",
674            "1234567a",
675            "--------",
676            "12345678",
677        ] {
678            let config = ClientConfig {
679                static_pairing_code: Some(code.to_owned()),
680                ..valid()
681            };
682            let error = config
683                .validate()
684                .expect_err("a code that is not eight digits must be rejected");
685            let message = format!("{error:#}");
686            assert!(
687                message.contains("static_pairing_code"),
688                "the error must name the field, got: {message}"
689            );
690            assert!(
691                !message.contains(code) || code.is_empty(),
692                "the code is a credential and must not appear in the error: {message}"
693            );
694        }
695    }
696
697    /// The window has no pause, so a zero lifetime would close it before any attempt could start.
698    #[cfg(feature = "pairing-code")]
699    #[test]
700    fn the_pairing_window_and_pending_text_are_bounded() {
701        let config = ClientConfig {
702            pairing_window: Duration::ZERO,
703            ..valid()
704        };
705        let error = config
706            .validate()
707            .expect_err("a zero window cannot admit an attempt");
708        assert!(
709            format!("{error:#}").contains("pairing_window"),
710            "the error must name the field, got: {error:#}"
711        );
712
713        let longest = ClientConfig {
714            pairing_pending_text: Some("a".repeat(MAX_PAIRING_PENDING_TEXT_LEN)),
715            ..valid()
716        };
717        longest
718            .validate()
719            .expect("a sentence at the limit must be accepted");
720
721        let config = ClientConfig {
722            pairing_pending_text: Some("a".repeat(MAX_PAIRING_PENDING_TEXT_LEN + 1)),
723            ..valid()
724        };
725        let error = config
726            .validate()
727            .expect_err("a sentence above the limit must be rejected");
728        assert!(
729            format!("{error:#}").contains("pairing_pending_text"),
730            "the error must name the field, got: {error:#}"
731        );
732    }
733
734    /// The static code is a credential, so a `Debug` log of the configuration must not print it.
735    #[cfg(feature = "pairing-code")]
736    #[test]
737    fn a_static_pairing_code_is_redacted_in_debug() {
738        let config = ClientConfig {
739            static_pairing_code: Some("12345678".to_owned()),
740            ..valid()
741        };
742        let text = format!("{config:?}");
743        assert!(
744            text.contains("static_pairing_code: Some(\"<redacted>\")"),
745            "the field must be named but redacted: {text}"
746        );
747        assert!(
748            !text.contains("12345678"),
749            "the code must never appear in a debug format: {text}"
750        );
751    }
752}