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/// Largest `min_buffer_ms` a configuration may pin, in milliseconds.
17///
18/// `roles/player/v1.md` bounds the reported buffer to 0-5000 ms, so a pinned value outside that
19/// range could not be reported; the shared configuration validation refuses it before a connection
20/// is attempted.
21const MAX_MIN_BUFFER_MS: u32 = 5_000;
22
23/// Longest delay between reconnect attempts a configuration starts with.
24///
25/// [`ClientConfig::new`] uses it; a host that wants a longer or shorter ceiling sets
26/// [`ClientConfig::max_backoff`] itself.
27pub const DEFAULT_MAX_BACKOFF: Duration = Duration::from_secs(30);
28
29/// Number of digits in a static pairing code.
30///
31/// The protocol fixes the length at eight decimal digits, so a configured code is exactly this
32/// many ASCII characters.
33#[cfg(feature = "pairing-code")]
34pub const STATIC_PAIRING_CODE_LEN: usize = 8;
35
36/// Longest `client/pair-pending` message the protocol allows, in bytes of UTF-8.
37#[cfg(feature = "pairing-code")]
38pub const MAX_PAIRING_PENDING_TEXT_LEN: usize = 200;
39
40/// How long an operator-opened pairing window admits attempts.
41///
42/// `pairing.md` recommends five minutes and starts the clock at the gesture, not at the first
43/// attempt.
44#[cfg(feature = "pairing-code")]
45pub const DEFAULT_PAIRING_WINDOW: Duration = Duration::from_secs(300);
46
47/// Emission format of a dynamic pairing code.
48///
49/// `pairing.md` defines two: `digits`, a six-digit decimal code the operator types into the
50/// server, and `qr_code`, a 24-byte code presented as a version-1 pairing token in a QR code. The
51/// format is chosen per connection by the server's `server/activate`, from the formats the client
52/// advertises; it decides how a host presents the code and what CPace's `PRS` is.
53#[cfg(feature = "pairing-code")]
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum CodeFormat {
56 /// Six decimal digits.
57 Digits,
58 /// A 24-byte code as a version-1 pairing token.
59 QrCode,
60}
61
62#[cfg(feature = "pairing-code")]
63impl CodeFormat {
64 /// Returns the identifier the wire and `client/hello` use.
65 pub(crate) fn as_wire(self) -> &'static str {
66 match self {
67 CodeFormat::Digits => "digits",
68 CodeFormat::QrCode => "qr_code",
69 }
70 }
71
72 /// Decodes an emission format from the wire, or `None` for a value this revision does not know.
73 pub(crate) fn from_wire(value: &str) -> Option<CodeFormat> {
74 match value {
75 "digits" => Some(CodeFormat::Digits),
76 "qr_code" => Some(CodeFormat::QrCode),
77 _ => None,
78 }
79 }
80}
81
82/// Channel a dynamic pairing code reaches the operator through.
83///
84/// The client advertises the channels its host can actually drive. `display` covers a screen, an
85/// e-ink panel or a seven-segment display; `speaker` covers a device that speaks the code from
86/// audio it bundles itself. The crate derives the code and emits it; rendering and speaking belong
87/// to the host.
88#[cfg(feature = "pairing-code")]
89#[derive(Debug, Clone, Copy, PartialEq, Eq)]
90pub enum CodeOutChannel {
91 /// A display the host renders the code on.
92 Display,
93 /// A speaker the host plays the code through.
94 Speaker,
95}
96
97#[cfg(feature = "pairing-code")]
98impl CodeOutChannel {
99 /// Returns the identifier the wire and `client/hello` use.
100 pub(crate) fn as_wire(self) -> &'static str {
101 match self {
102 CodeOutChannel::Display => "display",
103 CodeOutChannel::Speaker => "speaker",
104 }
105 }
106}
107
108/// How the client wants the stream delivered.
109#[derive(Debug, Clone, Copy, PartialEq, Eq)]
110pub enum AudioMode {
111 /// Play raw samples.
112 ///
113 /// The session advertises PCM only, so the server delivers raw samples and the sink receives
114 /// [`AudioFrame::Pcm`](crate::AudioFrame::Pcm). An encoded stream would need a decoder this
115 /// build does not carry, so the session rejects one instead of handing encoded bytes to a
116 /// sink that expects samples.
117 Decode,
118 /// Forward encoded frames.
119 ///
120 /// The session advertises the encoded formats it can forward and the sink receives
121 /// [`AudioFrame::Encoded`](crate::AudioFrame::Encoded). A PCM stream still arrives as
122 /// [`AudioFrame::Pcm`](crate::AudioFrame::Pcm), because there is nothing to decode.
123 Passthrough,
124}
125
126/// Category of a pre-shared key, as the server announces it in Noise message 1.
127#[derive(Debug, Clone, Copy, PartialEq, Eq)]
128pub enum PskCategory {
129 /// Long-term pairing key.
130 LongTerm,
131 /// Key for one pairing attempt.
132 Pairing,
133 /// The published key that authenticates nothing.
134 Sentinel,
135}
136
137impl PskCategory {
138 /// Decodes the two-letter category from the wire.
139 pub(crate) fn from_wire(value: &str) -> Option<PskCategory> {
140 match value {
141 "lt" => Some(PskCategory::LongTerm),
142 "pr" => Some(PskCategory::Pairing),
143 "sn" => Some(PskCategory::Sentinel),
144 _ => None,
145 }
146 }
147
148 /// Encodes the category the way the wire and a stored record spell it.
149 ///
150 /// The inverse of [`from_wire`](PskCategory::from_wire), so a backend this crate ships can
151 /// write a record it reads back with the same meaning.
152 #[cfg(feature = "storage-file")]
153 pub(crate) fn as_wire(self) -> &'static str {
154 match self {
155 PskCategory::LongTerm => "lt",
156 PskCategory::Pairing => "pr",
157 PskCategory::Sentinel => "sn",
158 }
159 }
160}
161
162/// Limits the session applies to a volume request.
163///
164/// A request at or below [`threshold`](VolumePolicy::threshold) is applied as asked, whether it
165/// raises or lowers the level. Above the threshold, one request may raise the level by at most
166/// [`max_step`](VolumePolicy::max_step); a lower request is still applied as asked, because the
167/// limit bounds raises only. The configuration validation rejects a policy that cannot describe a
168/// valid level before a connection is attempted.
169///
170/// [`VolumePolicy::default`] is the rule [`clamp_volume`](crate::clamp_volume) implements, so a
171/// host that does not configure a policy keeps the behaviour of earlier releases.
172#[derive(Debug, Clone, Copy, PartialEq, Eq)]
173pub struct VolumePolicy {
174 /// At or below this level a request is applied as is, in the protocol's 0-100 range.
175 pub threshold: u8,
176 /// Above the threshold, at most this much may be added per command.
177 pub max_step: u8,
178 /// Whether a request above the threshold may always rise to the threshold itself.
179 ///
180 /// With `false` a low level creeps up by [`max_step`](VolumePolicy::max_step) per command, so
181 /// 1 + a request for 100 yields 21. With `true` the same request yields the threshold, 40,
182 /// because a level below the threshold may always reach it in one step.
183 pub threshold_floor: bool,
184}
185
186impl Default for VolumePolicy {
187 /// Returns the policy [`clamp_volume`](crate::clamp_volume) implements.
188 fn default() -> Self {
189 Self {
190 threshold: 40,
191 max_step: 20,
192 threshold_floor: false,
193 }
194 }
195}
196
197/// A pre-shared key the host stores for a known server.
198///
199/// Selection after Noise message 1 compares the announced category and key id; a match is only
200/// accepted when `server_id` equals the one in `server/init`. The key itself is never formatted or
201/// logged: `Debug` prints it redacted.
202#[derive(Clone, PartialEq, Eq)]
203pub struct StoredPsk {
204 /// Category the key belongs to.
205 pub category: PskCategory,
206 /// The 32-byte key.
207 pub psk: [u8; 32],
208 /// Static public key of the server this key belongs to, as announced in `server/init`.
209 pub server_id: String,
210}
211
212impl fmt::Debug for StoredPsk {
213 /// Formats the record with the key material redacted.
214 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
215 formatter
216 .debug_struct("StoredPsk")
217 .field("category", &self.category)
218 .field("psk", &"<redacted>")
219 .field("server_id", &self.server_id)
220 .finish()
221 }
222}
223
224/// What the client announces about the device it runs on.
225///
226/// The server shows these values to the operator, so they name the hardware rather than the
227/// protocol: a product name and a manufacturer are always sent, and the software version and MAC
228/// address are sent when the host knows them. The fields are plain text; the crate sends them as
229/// the host provides them, so their content and length belong to the host.
230#[derive(Debug, Clone, Default, PartialEq, Eq)]
231pub struct DeviceInfo {
232 /// Device model or product name.
233 pub product_name: String,
234 /// Device manufacturer.
235 pub manufacturer: String,
236 /// Software version of the host application, not the protocol version.
237 pub software_version: Option<String>,
238 /// Network interface MAC address as lowercase colon-separated bytes.
239 pub mac_address: Option<String>,
240}
241
242/// Everything the client needs to open a session.
243///
244/// The identity is the client's long-lived X25519 keypair. It also becomes the `client_id` the
245/// server sees, so reusing it keeps the player recognisable across reconnects; the crate never
246/// generates or replaces one on its own.
247#[derive(Clone)]
248pub struct ClientConfig {
249 /// Server address as `host:port`, or a full `ws://` URL.
250 ///
251 /// A bare address connects to `ws://<server>/sendspin`. TLS is not part of this build, so a
252 /// `wss://` URL is rejected rather than silently downgraded.
253 pub server: String,
254 /// Friendly name announced to the server, non-empty and at most [`MAX_PLAYER_NAME_LEN`] bytes.
255 pub player_name: String,
256 /// Description of the device the client runs on, announced in `client/hello`.
257 ///
258 /// The server displays it to the operator. A host that does not know the hardware passes
259 /// `None` and no `device_info` object is sent, so the server shows only the player name.
260 pub device_info: Option<DeviceInfo>,
261 /// Long-lived keypair that identifies this client.
262 ///
263 /// Restore a stored keypair with [`Identity::from_secret_base64`]; generating a fresh one
264 /// makes the server treat the player as a new device.
265 pub identity: Identity,
266 /// Where the pairing PSK and the pairing records live, or `None` for a guest-only client.
267 ///
268 /// The host owns the store; see [`Storage`]. With a store the client offers the Pairing PSK
269 /// method, keeps one pairing PSK across restarts and writes a record for every completed
270 /// pairing. Without one it offers no pairing method at all: it never draws a key it cannot
271 /// hand back, and it answers a pairing activation with `pair/abort` reason
272 /// `method_not_supported`. A plain guest session is unchanged either way.
273 pub storage: Option<Arc<dyn Storage>>,
274 /// Whether the sink receives samples or encoded frames.
275 pub audio_mode: AudioMode,
276 /// Output level to start from, in the protocol's 0-100 range.
277 ///
278 /// The session reports this level in its first `client/state` and applies the volume limit
279 /// against it, so a host passes the level it restored instead of an invented one. A host
280 /// without a stored level passes 100, which neither attenuates nor limits an incoming request.
281 pub volume: u8,
282 /// Mute state to start from.
283 ///
284 /// Reported in the first `client/state`; a host without a stored state passes `false`.
285 pub muted: bool,
286 /// Minimum start-up lead the server must give this player, in milliseconds.
287 ///
288 /// This is the host's own start-up cost: launching the output (`gst-launch`, `pacat`), the
289 /// decoder's warm-up, and whatever the backend needs before the first sample is audible. The
290 /// client asks the server to schedule the first sample of a stream this far ahead of the
291 /// playout deadline; the value is a hint, and the server in this workspace ignores it until
292 /// `docs/spec-deviations.md` #17 closes.
293 ///
294 /// A host must keep it at least as large as the buffer its backend still plays after a
295 /// `stream/clear`: the clear discards that audio, and a shorter lead would schedule the
296 /// replacement audio while the old audio is still audible.
297 ///
298 /// The default is 250, the value every release before this field reported, which covers a
299 /// pipeline that starts within a quarter of a second. The protocol gives the field no upper
300 /// bound beyond the type, so the configuration accepts every `u32`.
301 pub required_lead_time_ms: u32,
302 /// Buffer duration the server should keep filled, in milliseconds, or `None` to derive it.
303 ///
304 /// `Some(n)` pins the value: every `client/state` reports `n` and the session never derives one
305 /// from arriving audio. A host pins it when it knows its backend's tolerance and wants the
306 /// value to stay put. The protocol bounds the reported buffer to 0-5000 ms, and a configuration
307 /// outside that range is refused before a connection is attempted.
308 ///
309 /// `None` leaves the value to the session, which derives it from the arrival delay of audio
310 /// chunks as `roles/player/v1.md` asks: the first report is 250, and the value follows the
311 /// upper tail of the measured distribution once enough samples exist.
312 pub min_buffer_ms: Option<u32>,
313 /// Limits applied to every volume request.
314 ///
315 /// The session applies the policy to a command from the server and to a level the host sets
316 /// through [`ControlHandle::set_volume`](crate::ControlHandle::set_volume); the value it
317 /// reports back is always the applied one. [`VolumePolicy::default`] keeps the fixed rule of
318 /// earlier releases.
319 pub volume_policy: VolumePolicy,
320 /// Upper bound for the delay between reconnects.
321 ///
322 /// The connection reports a recommended delay in
323 /// [`Event::Disconnected`](crate::Event::Disconnected) and waits it before the next attempt;
324 /// [`next_backoff`](crate::next_backoff) never returns more than this.
325 pub max_backoff: Duration,
326 /// Whether a `group_id` outside the spec's 43 base64url characters closes the connection.
327 ///
328 /// The spec makes such a value a protocol error, and with `true` the client behaves that way:
329 /// the attempt ends and [`Event::Disconnected`](crate::Event::Disconnected) reports why.
330 ///
331 /// The default is `false`. A non-canonical but well-formed identifier - non-empty, at most 128
332 /// bytes, valid UTF-8 without control characters - is then accepted as an opaque string and
333 /// reported once per connection as [`Event::GroupIdNotCanonical`](crate::Event::GroupIdNotCanonical).
334 /// That tolerance exists because a real server sends a UUID instead; see
335 /// `docs/spec-deviations.md`. A host that talks to a conformant server, or that wants the
336 /// spec's rule enforced, sets this to `true`.
337 pub strict_group_id: bool,
338 /// Whether this client admits a server with no pairing record.
339 ///
340 /// The value is advertised in `client/hello` as `unpaired_access.enabled` and both sides act on
341 /// it. With `false` this client refuses to activate a session that is not keyed by a long-term
342 /// PSK for playback: such a `server/activate` ends the connection with `client/goodbye` reason
343 /// `pairing_required`. A server that honours the advertisement grants no roles to an unpaired
344 /// client whose hello says `false`. Pairing is unaffected: the setting gates only roles and the
345 /// `playback` activity, never pairing.
346 ///
347 /// The value can change while the client runs:
348 /// [`ControlHandle::set_unpaired_access`](crate::ControlHandle::set_unpaired_access) stores a new
349 /// value, which the next `client/hello` advertises and the activation guard enforces. Enabling it
350 /// on an unpaired session forces that hello by reconnecting. This field is the value each
351 /// `connect` call starts from.
352 ///
353 /// `pairing.md` leaves the default to the manufacturer and recommends `false` for a client whose
354 /// input a stranger could reach, such as a microphone. The default here is `true`, which is what
355 /// every release before this setting did.
356 pub unpaired_access: bool,
357 /// How long one pairing attempt may run, measured from `client/pair-init`.
358 ///
359 /// On expiry the client sends `pair/abort` with reason `attempt_timeout` and reports
360 /// [`Event::PairingFailed`](crate::Event::PairingFailed). The protocol recommends two minutes,
361 /// which is [`DEFAULT_PAIRING_TIMEOUT`](crate::DEFAULT_PAIRING_TIMEOUT); a host shortens it
362 /// only for tests or for a deployment that wants a tighter bound.
363 pub pairing_timeout: Duration,
364 /// The operator-facing static pairing code, exactly eight decimal digits.
365 ///
366 /// The code is configuration, never generated: a manufacturer provisions one per device, and
367 /// the operator reads it off the device or its leaflet. Offering the static code method in
368 /// `client/hello` depends on this field being set, so a client without a code never advertises
369 /// a method it cannot complete.
370 ///
371 /// The code is a credential: anyone who knows it and can reach the server may pair. It is
372 /// never formatted - [`ClientConfig`]'s `Debug` prints it redacted - and never logged.
373 #[cfg(feature = "pairing-code")]
374 pub static_pairing_code: Option<String>,
375 /// How long an operator-opened pairing window admits attempts, recommended five minutes.
376 ///
377 /// The window runs from [`ControlHandle::open_pairing_window`](crate::ControlHandle::open_pairing_window)
378 /// and does not pause during an attempt. On expiry it closes silently; an attempt already in
379 /// progress runs to its own end.
380 #[cfg(feature = "pairing-code")]
381 pub pairing_window: Duration,
382 /// Sentence sent in `client/pair-pending`, in the host's language.
383 ///
384 /// A host that wants to tell the operator what to do sets it here; without one the message is
385 /// sent with no text, because the crate does not invent operator-facing prose.
386 #[cfg(feature = "pairing-code")]
387 pub pairing_pending_text: Option<String>,
388 /// Emission formats the client offers for a dynamic pairing code.
389 ///
390 /// An empty list offers no dynamic method at all; a non-empty one advertises
391 /// `dynamic_pairing_code` in `client/hello`, together with [`ClientConfig::code_out_channels`].
392 /// Both lists must be set for the method to be offered, because the protocol treats a
393 /// descriptor left without a known format or channel as unrecognized. The code itself is
394 /// derived per attempt, never configured.
395 #[cfg(feature = "pairing-code")]
396 pub code_formats: Vec<CodeFormat>,
397 /// Channels the host can carry a dynamic pairing code through.
398 ///
399 /// The host sets what it can render or speak; the server picks the method's format, and the
400 /// client emits the code through [`Event::PairingCode`](crate::Event::PairingCode).
401 #[cfg(feature = "pairing-code")]
402 pub code_out_channels: Vec<CodeOutChannel>,
403 /// The server-initiated half of the connection mode, or `None` for client-initiated
404 /// connections.
405 ///
406 /// Setting it makes [`advertise`](crate::advertise) publish `_sendspin._tcp` and accept the
407 /// servers that connect, and makes a manual [`connect`](crate::connect) fail: `connection.md`
408 /// lets a client use one of the two methods at a time, never both. [`Inbound::new`] fills the
409 /// listen address and the path with the values the spec recommends.
410 ///
411 /// [`Inbound::new`]: crate::Inbound::new
412 #[cfg(feature = "discovery")]
413 pub inbound: Option<crate::Inbound>,
414}
415
416impl fmt::Debug for ClientConfig {
417 /// Formats the configuration without the store and without key material.
418 ///
419 /// The store holds the pairing PSK and the records, and its own `Debug` is the host's; the
420 /// identity redacts its secret. Neither is delegated to here, so a `Debug` log of a
421 /// configuration cannot leak a key.
422 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
423 let mut debug = formatter.debug_struct("ClientConfig");
424 debug
425 .field("server", &self.server)
426 .field("player_name", &self.player_name)
427 .field("device_info", &self.device_info)
428 .field("identity", &self.identity)
429 .field("storage", &self.storage.as_ref().map(|_| "<host storage>"))
430 .field("audio_mode", &self.audio_mode)
431 .field("volume", &self.volume)
432 .field("muted", &self.muted)
433 .field("required_lead_time_ms", &self.required_lead_time_ms)
434 .field("min_buffer_ms", &self.min_buffer_ms)
435 .field("volume_policy", &self.volume_policy)
436 .field("max_backoff", &self.max_backoff)
437 .field("strict_group_id", &self.strict_group_id)
438 .field("unpaired_access", &self.unpaired_access)
439 .field("pairing_timeout", &self.pairing_timeout);
440 // The static code is a credential, so it is named but never printed.
441 #[cfg(feature = "pairing-code")]
442 debug
443 .field(
444 "static_pairing_code",
445 &self.static_pairing_code.as_ref().map(|_| "<redacted>"),
446 )
447 .field("pairing_window", &self.pairing_window)
448 .field("pairing_pending_text", &self.pairing_pending_text)
449 .field("code_formats", &self.code_formats)
450 .field("code_out_channels", &self.code_out_channels);
451 // The backend's own `Debug` belongs to the host, so it is named rather than delegated to;
452 // `Inbound`'s format does the same for the backend it holds.
453 #[cfg(feature = "discovery")]
454 debug.field("inbound", &self.inbound);
455 debug.finish()
456 }
457}
458
459impl ClientConfig {
460 /// Builds a configuration for `server` with the crate's defaults.
461 ///
462 /// Everything a host rarely changes starts at a documented value: no device description, no
463 /// pairing store, [`AudioMode::Decode`], volume 100 and unmuted, [`VolumePolicy::default`],
464 /// a 250 ms start-up lead, a buffer the session derives rather than a pinned one,
465 /// [`DEFAULT_MAX_BACKOFF`], the tolerated foreign `group_id`, unpaired access admitted, and
466 /// [`DEFAULT_PAIRING_TIMEOUT`](crate::DEFAULT_PAIRING_TIMEOUT). A
467 /// host that restores a level or a mute state sets [`ClientConfig::volume`] and
468 /// [`ClientConfig::muted`] on the value this returns.
469 ///
470 /// The fields stay public, so a host can also build the struct itself and name every field.
471 pub fn new(
472 server: impl Into<String>,
473 player_name: impl Into<String>,
474 identity: Identity,
475 ) -> ClientConfig {
476 ClientConfig {
477 server: server.into(),
478 player_name: player_name.into(),
479 device_info: None,
480 identity,
481 storage: None,
482 audio_mode: AudioMode::Decode,
483 volume: 100,
484 muted: false,
485 // Every release before this field asked the server for a quarter of a second; a host
486 // whose output starts slower sets its own.
487 required_lead_time_ms: 250,
488 // `None` leaves the buffer to the session, which derives it from arrival delay.
489 min_buffer_ms: None,
490 volume_policy: VolumePolicy::default(),
491 max_backoff: DEFAULT_MAX_BACKOFF,
492 // The documented tolerance is the default: a foreign group id does not close the
493 // connection unless the host asks for the spec's strictness.
494 strict_group_id: false,
495 // Earlier releases admitted every session, so the setting starts where they left off.
496 unpaired_access: true,
497 pairing_timeout: crate::DEFAULT_PAIRING_TIMEOUT,
498 #[cfg(feature = "pairing-code")]
499 static_pairing_code: None,
500 #[cfg(feature = "pairing-code")]
501 pairing_window: DEFAULT_PAIRING_WINDOW,
502 #[cfg(feature = "pairing-code")]
503 pairing_pending_text: None,
504 #[cfg(feature = "pairing-code")]
505 code_formats: Vec::new(),
506 #[cfg(feature = "pairing-code")]
507 code_out_channels: Vec::new(),
508 // The client-initiated mode is the default: nothing is advertised and nothing listens.
509 #[cfg(feature = "discovery")]
510 inbound: None,
511 }
512 }
513
514 /// Rejects a configuration that would put invalid fields on the wire.
515 pub(crate) fn validate(&self) -> Result<()> {
516 self.validate_common()?;
517 if self.server.trim().is_empty() {
518 bail!("ClientConfig::server must not be empty");
519 }
520 Ok(())
521 }
522
523 /// Rejects the fields both connection modes share.
524 ///
525 /// A server that advertises and accepts connections names no server address, so the address
526 /// check belongs to [`validate`](ClientConfig::validate) alone and the inbound listener
527 /// validates without it.
528 pub(crate) fn validate_common(&self) -> Result<()> {
529 if self.player_name.trim().is_empty() {
530 bail!("ClientConfig::player_name must not be empty");
531 }
532 if self.player_name.len() > MAX_PLAYER_NAME_LEN {
533 bail!(
534 "ClientConfig::player_name is {} bytes, more than the {MAX_PLAYER_NAME_LEN} the \
535 protocol allows",
536 self.player_name.len()
537 );
538 }
539 if self.volume > MAX_VOLUME {
540 bail!(
541 "ClientConfig::volume is {}, outside the 0-{MAX_VOLUME} the protocol defines",
542 self.volume
543 );
544 }
545 if self.volume_policy.threshold > MAX_VOLUME {
546 bail!(
547 "ClientConfig::volume_policy.threshold is {}, outside the 0-{MAX_VOLUME} level \
548 range",
549 self.volume_policy.threshold
550 );
551 }
552 if self.volume_policy.max_step > MAX_VOLUME {
553 bail!(
554 "ClientConfig::volume_policy.max_step is {}, outside the 0-{MAX_VOLUME} step \
555 range",
556 self.volume_policy.max_step
557 );
558 }
559 if self.max_backoff.is_zero() {
560 bail!("ClientConfig::max_backoff must not be zero");
561 }
562 // The protocol bounds the reported buffer to 0-5000 ms. `required_lead_time_ms` has no
563 // counterpart: the spec gives it no upper bound, so the field's type is the only one.
564 if let Some(min_buffer_ms) = self.min_buffer_ms {
565 if min_buffer_ms > MAX_MIN_BUFFER_MS {
566 bail!(
567 "ClientConfig::min_buffer_ms is {min_buffer_ms}, outside the \
568 0-{MAX_MIN_BUFFER_MS} ms the protocol defines"
569 );
570 }
571 }
572 if self.pairing_timeout.is_zero() {
573 bail!("ClientConfig::pairing_timeout must not be zero");
574 }
575 #[cfg(feature = "pairing-code")]
576 {
577 if let Some(code) = &self.static_pairing_code {
578 if code.len() != STATIC_PAIRING_CODE_LEN
579 || !code.bytes().all(|byte| byte.is_ascii_digit())
580 {
581 // The code itself is a credential, so the error names the shape, never the
582 // value the host passed.
583 bail!(
584 "ClientConfig::static_pairing_code must be {STATIC_PAIRING_CODE_LEN} \
585 ASCII digits"
586 );
587 }
588 }
589 if self.pairing_window.is_zero() {
590 bail!("ClientConfig::pairing_window must not be zero");
591 }
592 if let Some(text) = &self.pairing_pending_text {
593 if text.len() > MAX_PAIRING_PENDING_TEXT_LEN {
594 bail!(
595 "ClientConfig::pairing_pending_text is {} bytes, more than the \
596 {MAX_PAIRING_PENDING_TEXT_LEN} the protocol allows",
597 text.len()
598 );
599 }
600 }
601 // A descriptor with formats but no channel - or the other way round - is one a server
602 // treats as unrecognized, so the client would advertise a method it cannot complete.
603 if self.code_formats.is_empty() != self.code_out_channels.is_empty() {
604 bail!(
605 "ClientConfig::code_formats and ClientConfig::code_out_channels must both be \
606 set or both be empty"
607 );
608 }
609 }
610 // The path becomes TXT record content and the endpoint the listener serves, so it has to be
611 // a `path-absolute` (RFC 3986) the other side can append to an authority: a leading slash,
612 // and not the `//authority` form.
613 #[cfg(feature = "discovery")]
614 if let Some(inbound) = &self.inbound {
615 if !inbound.path.starts_with('/') || inbound.path.starts_with("//") {
616 bail!(
617 "ClientConfig::inbound.path must be an absolute path such as \
618 \"/sendspin\", not a relative one and not one starting with //"
619 );
620 }
621 }
622 Ok(())
623 }
624}
625
626#[cfg(test)]
627mod tests {
628 use super::*;
629
630 /// A configuration that passes validation, for tests that change one field.
631 fn valid() -> ClientConfig {
632 ClientConfig {
633 server: "127.0.0.1:1".to_owned(),
634 player_name: "Test player".to_owned(),
635 device_info: None,
636 identity: Identity::generate(),
637 storage: None,
638 audio_mode: AudioMode::Passthrough,
639 volume: 100,
640 muted: false,
641 required_lead_time_ms: 250,
642 min_buffer_ms: None,
643 volume_policy: VolumePolicy::default(),
644 max_backoff: Duration::from_secs(1),
645 strict_group_id: false,
646 unpaired_access: true,
647 pairing_timeout: crate::DEFAULT_PAIRING_TIMEOUT,
648 #[cfg(feature = "discovery")]
649 inbound: None,
650 #[cfg(feature = "pairing-code")]
651 static_pairing_code: None,
652 #[cfg(feature = "pairing-code")]
653 pairing_window: DEFAULT_PAIRING_WINDOW,
654 #[cfg(feature = "pairing-code")]
655 pairing_pending_text: None,
656 #[cfg(feature = "pairing-code")]
657 code_formats: Vec::new(),
658 #[cfg(feature = "pairing-code")]
659 code_out_channels: Vec::new(),
660 }
661 }
662
663 #[test]
664 fn the_constructor_fills_a_configuration_that_validates() {
665 let config = ClientConfig::new("127.0.0.1:8927", "Test player", Identity::generate());
666 config.validate().expect("the defaults are valid");
667 assert_eq!(config.server, "127.0.0.1:8927");
668 assert_eq!(config.player_name, "Test player");
669 assert_eq!(config.audio_mode, AudioMode::Decode);
670 assert_eq!(config.volume, 100);
671 assert!(!config.muted);
672 assert_eq!(
673 config.required_lead_time_ms, 250,
674 "the constructor must keep the lead every release before this field reported"
675 );
676 assert!(
677 config.min_buffer_ms.is_none(),
678 "the constructor leaves the buffer to the session instead of pinning one"
679 );
680 assert_eq!(config.max_backoff, DEFAULT_MAX_BACKOFF);
681 assert!(
682 !config.strict_group_id,
683 "the documented tolerance is the default; a host opts into the spec's strictness"
684 );
685 assert!(
686 config.unpaired_access,
687 "unpaired access is admitted by default, as every earlier release did"
688 );
689 assert_eq!(config.pairing_timeout, crate::DEFAULT_PAIRING_TIMEOUT);
690 assert!(config.storage.is_none());
691 assert!(config.device_info.is_none());
692 // The client-initiated mode is what a host gets without asking: nothing advertises and no
693 // socket listens until it sets an `Inbound`.
694 #[cfg(feature = "discovery")]
695 assert!(config.inbound.is_none());
696 }
697
698 #[test]
699 fn the_pairing_timeout_must_be_positive() {
700 let config = ClientConfig {
701 pairing_timeout: Duration::ZERO,
702 #[cfg(feature = "discovery")]
703 inbound: None,
704 ..valid()
705 };
706 let error = config
707 .validate()
708 .expect_err("a zero timeout would abort every attempt at once");
709 assert!(
710 format!("{error:#}").contains("pairing_timeout"),
711 "the error must name the field, got: {error:#}"
712 );
713 config_with_default_timeout()
714 .validate()
715 .expect("120s is valid");
716 }
717
718 /// A configuration with the protocol's recommended attempt timeout.
719 fn config_with_default_timeout() -> ClientConfig {
720 let config = valid();
721 assert_eq!(config.pairing_timeout, crate::DEFAULT_PAIRING_TIMEOUT);
722 config
723 }
724
725 /// The protocol bounds the reported buffer to 0-5000 ms; the lead has no bound beyond its type.
726 #[test]
727 fn a_pinned_buffer_is_bounded_by_the_protocol_range() {
728 for min_buffer_ms in [0, 250, 5_000] {
729 ClientConfig {
730 min_buffer_ms: Some(min_buffer_ms),
731 ..valid()
732 }
733 .validate()
734 .unwrap_or_else(|error| panic!("{min_buffer_ms} is inside 0-5000: {error:#}"));
735 }
736
737 let config = ClientConfig {
738 min_buffer_ms: Some(MAX_MIN_BUFFER_MS + 1),
739 ..valid()
740 };
741 let error = config
742 .validate()
743 .expect_err("a value above the protocol's range cannot be reported");
744 let message = format!("{error:#}");
745 assert!(
746 message.contains("min_buffer_ms") && message.contains(&MAX_MIN_BUFFER_MS.to_string()),
747 "the error must name the field and the range, got: {message}"
748 );
749
750 // The lead is a start-up time, not a buffer: the spec gives it no upper bound.
751 ClientConfig {
752 required_lead_time_ms: 6_000,
753 ..valid()
754 }
755 .validate()
756 .expect("the lead accepts every value its type can hold");
757 }
758
759 #[test]
760 fn a_configuration_debug_names_no_key_material() {
761 let store = std::sync::Arc::new(crate::test_support::MemoryStore::holding([7u8; 32]));
762 let config = ClientConfig {
763 storage: Some(store),
764 ..valid()
765 };
766 let text = format!("{config:?}");
767 assert!(text.contains("ClientConfig"), "unexpected format: {text}");
768 assert!(
769 text.contains("<host storage>"),
770 "the store is named but never delegated to: {text}"
771 );
772 assert!(
773 !text.contains(&config.identity.secret_base64()),
774 "the identity secret must stay out of a debug format: {text}"
775 );
776 }
777
778 #[test]
779 fn a_stored_psk_formats_without_its_key_material() {
780 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
781 use base64::Engine as _;
782
783 let psk = [0xab; 32];
784 let record = StoredPsk {
785 category: PskCategory::Pairing,
786 psk,
787 server_id: "B1y4w7z0c3f6i9l2o5r8u1x4a7d0g3j6m9p2s5v8y1b".to_owned(),
788 };
789 let text = format!("{record:?}");
790 assert!(text.contains("StoredPsk"), "unexpected format: {text}");
791 assert!(text.contains("Pairing"), "the category is not key material");
792 assert!(text.contains("B1y4w7z0c3f6i9l2o5r8u1x4a7d0g3j6m9p2s5v8y1b"));
793 assert!(text.contains("<redacted>"));
794 assert!(
795 !text.contains(&URL_SAFE_NO_PAD.encode(psk)),
796 "the key must never appear in a debug format: {text}"
797 );
798 assert!(
799 !text.contains(&format!("{psk:?}")),
800 "not even the raw bytes may appear: {text}"
801 );
802 }
803
804 /// The dynamic method's descriptor needs a format and a channel; one without the other is
805 /// treated as unrecognized by a server, so the configuration refuses it before a connection.
806 #[cfg(feature = "pairing-code")]
807 #[test]
808 fn the_code_descriptor_lists_are_set_together() {
809 let formats_only = ClientConfig {
810 code_formats: vec![CodeFormat::Digits],
811 ..valid()
812 };
813 let error = formats_only
814 .validate()
815 .expect_err("a format without a channel is not a usable descriptor");
816 assert!(
817 format!("{error:#}").contains("code_out_channels"),
818 "the error names the missing list, got: {error:#}"
819 );
820
821 let channels_only = ClientConfig {
822 code_out_channels: vec![CodeOutChannel::Display],
823 ..valid()
824 };
825 let error = channels_only
826 .validate()
827 .expect_err("a channel without a format is not a usable descriptor");
828 assert!(
829 format!("{error:#}").contains("code_formats"),
830 "the error names the missing list, got: {error:#}"
831 );
832
833 ClientConfig {
834 code_formats: vec![CodeFormat::Digits, CodeFormat::QrCode],
835 code_out_channels: vec![CodeOutChannel::Display],
836 ..valid()
837 }
838 .validate()
839 .expect("both lists make the method offerable");
840 }
841
842 /// The identifiers are the ones `client/hello` and `server/activate` spell.
843 #[cfg(feature = "pairing-code")]
844 #[test]
845 fn the_code_types_round_trip_through_their_wire_names() {
846 assert_eq!(CodeFormat::Digits.as_wire(), "digits");
847 assert_eq!(CodeFormat::QrCode.as_wire(), "qr_code");
848 assert_eq!(CodeFormat::from_wire("digits"), Some(CodeFormat::Digits));
849 assert_eq!(CodeFormat::from_wire("qr_code"), Some(CodeFormat::QrCode));
850 assert_eq!(
851 CodeFormat::from_wire("nfc"),
852 None,
853 "a format this revision does not know selects nothing"
854 );
855 assert_eq!(CodeOutChannel::Display.as_wire(), "display");
856 assert_eq!(CodeOutChannel::Speaker.as_wire(), "speaker");
857 }
858
859 #[test]
860 fn an_empty_server_address_is_rejected() {
861 for server in ["", " "] {
862 let config = ClientConfig {
863 server: server.to_owned(),
864 ..valid()
865 };
866 let error = config.validate().expect_err("an empty address has no host");
867 assert!(
868 format!("{error:#}").contains("server"),
869 "the error must name the address, got: {error:#}"
870 );
871 }
872 }
873
874 #[test]
875 fn a_player_name_is_bounded_by_the_protocol_length() {
876 let longest = ClientConfig {
877 player_name: "a".repeat(MAX_PLAYER_NAME_LEN),
878 ..valid()
879 };
880 longest
881 .validate()
882 .expect("a name at the limit must be accepted");
883
884 let config = ClientConfig {
885 player_name: "a".repeat(MAX_PLAYER_NAME_LEN + 1),
886 ..valid()
887 };
888 let error = config
889 .validate()
890 .expect_err("a name above the limit must be rejected");
891 let message = format!("{error:#}");
892 assert!(
893 message.contains("player_name")
894 && message.contains(&(MAX_PLAYER_NAME_LEN + 1).to_string()),
895 "the error must name the field and the length, got: {message}"
896 );
897
898 let config = ClientConfig {
899 player_name: " \t ".to_owned(),
900 ..valid()
901 };
902 let error = config
903 .validate()
904 .expect_err("a blank name must be rejected");
905 assert!(format!("{error:#}").contains("player_name"));
906 }
907
908 /// The protocol fixes the code at eight decimal digits; anything else cannot be entered.
909 #[cfg(feature = "pairing-code")]
910 #[test]
911 fn a_static_pairing_code_is_exactly_eight_digits() {
912 for code in ["12345678", "00000000", "99999999"] {
913 let config = ClientConfig {
914 static_pairing_code: Some(code.to_owned()),
915 ..valid()
916 };
917 config
918 .validate()
919 .unwrap_or_else(|error| panic!("{code:?} must be accepted: {error:#}"));
920 }
921
922 for code in [
923 "",
924 "1234567",
925 "123456789",
926 "1234 678",
927 "1234567a",
928 "--------",
929 "12345678",
930 ] {
931 let config = ClientConfig {
932 static_pairing_code: Some(code.to_owned()),
933 ..valid()
934 };
935 let error = config
936 .validate()
937 .expect_err("a code that is not eight digits must be rejected");
938 let message = format!("{error:#}");
939 assert!(
940 message.contains("static_pairing_code"),
941 "the error must name the field, got: {message}"
942 );
943 assert!(
944 !message.contains(code) || code.is_empty(),
945 "the code is a credential and must not appear in the error: {message}"
946 );
947 }
948 }
949
950 /// The window has no pause, so a zero lifetime would close it before any attempt could start.
951 #[cfg(feature = "pairing-code")]
952 #[test]
953 fn the_pairing_window_and_pending_text_are_bounded() {
954 let config = ClientConfig {
955 pairing_window: Duration::ZERO,
956 ..valid()
957 };
958 let error = config
959 .validate()
960 .expect_err("a zero window cannot admit an attempt");
961 assert!(
962 format!("{error:#}").contains("pairing_window"),
963 "the error must name the field, got: {error:#}"
964 );
965
966 let longest = ClientConfig {
967 pairing_pending_text: Some("a".repeat(MAX_PAIRING_PENDING_TEXT_LEN)),
968 ..valid()
969 };
970 longest
971 .validate()
972 .expect("a sentence at the limit must be accepted");
973
974 let config = ClientConfig {
975 pairing_pending_text: Some("a".repeat(MAX_PAIRING_PENDING_TEXT_LEN + 1)),
976 ..valid()
977 };
978 let error = config
979 .validate()
980 .expect_err("a sentence above the limit must be rejected");
981 assert!(
982 format!("{error:#}").contains("pairing_pending_text"),
983 "the error must name the field, got: {error:#}"
984 );
985 }
986
987 /// The static code is a credential, so a `Debug` log of the configuration must not print it.
988 #[cfg(feature = "pairing-code")]
989 #[test]
990 fn a_static_pairing_code_is_redacted_in_debug() {
991 let config = ClientConfig {
992 static_pairing_code: Some("12345678".to_owned()),
993 ..valid()
994 };
995 let text = format!("{config:?}");
996 assert!(
997 text.contains("static_pairing_code: Some(\"<redacted>\")"),
998 "the field must be named but redacted: {text}"
999 );
1000 assert!(
1001 !text.contains("12345678"),
1002 "the code must never appear in a debug format: {text}"
1003 );
1004 }
1005}