use std::fmt;
use std::sync::Arc;
use std::time::Duration;
use anyhow::{bail, Result};
use syncspin_core::noise::Identity;
use crate::client::MAX_VOLUME;
use crate::storage::Storage;
pub const MAX_PLAYER_NAME_LEN: usize = 64;
pub const DEFAULT_MAX_BACKOFF: Duration = Duration::from_secs(30);
#[cfg(feature = "pairing-code")]
pub const STATIC_PAIRING_CODE_LEN: usize = 8;
#[cfg(feature = "pairing-code")]
pub const MAX_PAIRING_PENDING_TEXT_LEN: usize = 200;
#[cfg(feature = "pairing-code")]
pub const DEFAULT_PAIRING_WINDOW: Duration = Duration::from_secs(300);
#[cfg(feature = "pairing-code")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodeFormat {
Digits,
QrCode,
}
#[cfg(feature = "pairing-code")]
impl CodeFormat {
pub(crate) fn as_wire(self) -> &'static str {
match self {
CodeFormat::Digits => "digits",
CodeFormat::QrCode => "qr_code",
}
}
pub(crate) fn from_wire(value: &str) -> Option<CodeFormat> {
match value {
"digits" => Some(CodeFormat::Digits),
"qr_code" => Some(CodeFormat::QrCode),
_ => None,
}
}
}
#[cfg(feature = "pairing-code")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CodeOutChannel {
Display,
Speaker,
}
#[cfg(feature = "pairing-code")]
impl CodeOutChannel {
pub(crate) fn as_wire(self) -> &'static str {
match self {
CodeOutChannel::Display => "display",
CodeOutChannel::Speaker => "speaker",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AudioMode {
Decode,
Passthrough,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PskCategory {
LongTerm,
Pairing,
Sentinel,
}
impl PskCategory {
pub(crate) fn from_wire(value: &str) -> Option<PskCategory> {
match value {
"lt" => Some(PskCategory::LongTerm),
"pr" => Some(PskCategory::Pairing),
"sn" => Some(PskCategory::Sentinel),
_ => None,
}
}
#[cfg(feature = "storage-file")]
pub(crate) fn as_wire(self) -> &'static str {
match self {
PskCategory::LongTerm => "lt",
PskCategory::Pairing => "pr",
PskCategory::Sentinel => "sn",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VolumePolicy {
pub threshold: u8,
pub max_step: u8,
pub threshold_floor: bool,
}
impl Default for VolumePolicy {
fn default() -> Self {
Self {
threshold: 40,
max_step: 20,
threshold_floor: false,
}
}
}
#[derive(Clone, PartialEq, Eq)]
pub struct StoredPsk {
pub category: PskCategory,
pub psk: [u8; 32],
pub server_id: String,
}
impl fmt::Debug for StoredPsk {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter
.debug_struct("StoredPsk")
.field("category", &self.category)
.field("psk", &"<redacted>")
.field("server_id", &self.server_id)
.finish()
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct DeviceInfo {
pub product_name: String,
pub manufacturer: String,
pub software_version: Option<String>,
pub mac_address: Option<String>,
}
#[derive(Clone)]
pub struct ClientConfig {
pub server: String,
pub player_name: String,
pub device_info: Option<DeviceInfo>,
pub identity: Identity,
pub storage: Option<Arc<dyn Storage>>,
pub audio_mode: AudioMode,
pub volume: u8,
pub muted: bool,
pub volume_policy: VolumePolicy,
pub max_backoff: Duration,
pub pairing_timeout: Duration,
#[cfg(feature = "pairing-code")]
pub static_pairing_code: Option<String>,
#[cfg(feature = "pairing-code")]
pub pairing_window: Duration,
#[cfg(feature = "pairing-code")]
pub pairing_pending_text: Option<String>,
#[cfg(feature = "pairing-code")]
pub code_formats: Vec<CodeFormat>,
#[cfg(feature = "pairing-code")]
pub code_out_channels: Vec<CodeOutChannel>,
#[cfg(feature = "discovery")]
pub inbound: Option<crate::Inbound>,
}
impl fmt::Debug for ClientConfig {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut debug = formatter.debug_struct("ClientConfig");
debug
.field("server", &self.server)
.field("player_name", &self.player_name)
.field("device_info", &self.device_info)
.field("identity", &self.identity)
.field("storage", &self.storage.as_ref().map(|_| "<host storage>"))
.field("audio_mode", &self.audio_mode)
.field("volume", &self.volume)
.field("muted", &self.muted)
.field("volume_policy", &self.volume_policy)
.field("max_backoff", &self.max_backoff)
.field("pairing_timeout", &self.pairing_timeout);
#[cfg(feature = "pairing-code")]
debug
.field(
"static_pairing_code",
&self.static_pairing_code.as_ref().map(|_| "<redacted>"),
)
.field("pairing_window", &self.pairing_window)
.field("pairing_pending_text", &self.pairing_pending_text)
.field("code_formats", &self.code_formats)
.field("code_out_channels", &self.code_out_channels);
#[cfg(feature = "discovery")]
debug.field("inbound", &self.inbound);
debug.finish()
}
}
impl ClientConfig {
pub fn new(
server: impl Into<String>,
player_name: impl Into<String>,
identity: Identity,
) -> ClientConfig {
ClientConfig {
server: server.into(),
player_name: player_name.into(),
device_info: None,
identity,
storage: None,
audio_mode: AudioMode::Decode,
volume: 100,
muted: false,
volume_policy: VolumePolicy::default(),
max_backoff: DEFAULT_MAX_BACKOFF,
pairing_timeout: crate::DEFAULT_PAIRING_TIMEOUT,
#[cfg(feature = "pairing-code")]
static_pairing_code: None,
#[cfg(feature = "pairing-code")]
pairing_window: DEFAULT_PAIRING_WINDOW,
#[cfg(feature = "pairing-code")]
pairing_pending_text: None,
#[cfg(feature = "pairing-code")]
code_formats: Vec::new(),
#[cfg(feature = "pairing-code")]
code_out_channels: Vec::new(),
#[cfg(feature = "discovery")]
inbound: None,
}
}
pub(crate) fn validate(&self) -> Result<()> {
self.validate_common()?;
if self.server.trim().is_empty() {
bail!("ClientConfig::server must not be empty");
}
Ok(())
}
pub(crate) fn validate_common(&self) -> Result<()> {
if self.player_name.trim().is_empty() {
bail!("ClientConfig::player_name must not be empty");
}
if self.player_name.len() > MAX_PLAYER_NAME_LEN {
bail!(
"ClientConfig::player_name is {} bytes, more than the {MAX_PLAYER_NAME_LEN} the \
protocol allows",
self.player_name.len()
);
}
if self.volume > MAX_VOLUME {
bail!(
"ClientConfig::volume is {}, outside the 0-{MAX_VOLUME} the protocol defines",
self.volume
);
}
if self.volume_policy.threshold > MAX_VOLUME {
bail!(
"ClientConfig::volume_policy.threshold is {}, outside the 0-{MAX_VOLUME} level \
range",
self.volume_policy.threshold
);
}
if self.volume_policy.max_step > MAX_VOLUME {
bail!(
"ClientConfig::volume_policy.max_step is {}, outside the 0-{MAX_VOLUME} step \
range",
self.volume_policy.max_step
);
}
if self.max_backoff.is_zero() {
bail!("ClientConfig::max_backoff must not be zero");
}
if self.pairing_timeout.is_zero() {
bail!("ClientConfig::pairing_timeout must not be zero");
}
#[cfg(feature = "pairing-code")]
{
if let Some(code) = &self.static_pairing_code {
if code.len() != STATIC_PAIRING_CODE_LEN
|| !code.bytes().all(|byte| byte.is_ascii_digit())
{
bail!(
"ClientConfig::static_pairing_code must be {STATIC_PAIRING_CODE_LEN} \
ASCII digits"
);
}
}
if self.pairing_window.is_zero() {
bail!("ClientConfig::pairing_window must not be zero");
}
if let Some(text) = &self.pairing_pending_text {
if text.len() > MAX_PAIRING_PENDING_TEXT_LEN {
bail!(
"ClientConfig::pairing_pending_text is {} bytes, more than the \
{MAX_PAIRING_PENDING_TEXT_LEN} the protocol allows",
text.len()
);
}
}
if self.code_formats.is_empty() != self.code_out_channels.is_empty() {
bail!(
"ClientConfig::code_formats and ClientConfig::code_out_channels must both be \
set or both be empty"
);
}
}
#[cfg(feature = "discovery")]
if let Some(inbound) = &self.inbound {
if !inbound.path.starts_with('/') || inbound.path.starts_with("//") {
bail!(
"ClientConfig::inbound.path must be an absolute path such as \
\"/sendspin\", not a relative one and not one starting with //"
);
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn valid() -> ClientConfig {
ClientConfig {
server: "127.0.0.1:1".to_owned(),
player_name: "Test player".to_owned(),
device_info: None,
identity: Identity::generate(),
storage: None,
audio_mode: AudioMode::Passthrough,
volume: 100,
muted: false,
volume_policy: VolumePolicy::default(),
max_backoff: Duration::from_secs(1),
pairing_timeout: crate::DEFAULT_PAIRING_TIMEOUT,
#[cfg(feature = "discovery")]
inbound: None,
#[cfg(feature = "pairing-code")]
static_pairing_code: None,
#[cfg(feature = "pairing-code")]
pairing_window: DEFAULT_PAIRING_WINDOW,
#[cfg(feature = "pairing-code")]
pairing_pending_text: None,
#[cfg(feature = "pairing-code")]
code_formats: Vec::new(),
#[cfg(feature = "pairing-code")]
code_out_channels: Vec::new(),
}
}
#[test]
fn the_constructor_fills_a_configuration_that_validates() {
let config = ClientConfig::new("127.0.0.1:8927", "Test player", Identity::generate());
config.validate().expect("the defaults are valid");
assert_eq!(config.server, "127.0.0.1:8927");
assert_eq!(config.player_name, "Test player");
assert_eq!(config.audio_mode, AudioMode::Decode);
assert_eq!(config.volume, 100);
assert!(!config.muted);
assert_eq!(config.max_backoff, DEFAULT_MAX_BACKOFF);
assert_eq!(config.pairing_timeout, crate::DEFAULT_PAIRING_TIMEOUT);
assert!(config.storage.is_none());
assert!(config.device_info.is_none());
#[cfg(feature = "discovery")]
assert!(config.inbound.is_none());
}
#[test]
fn the_pairing_timeout_must_be_positive() {
let config = ClientConfig {
pairing_timeout: Duration::ZERO,
#[cfg(feature = "discovery")]
inbound: None,
..valid()
};
let error = config
.validate()
.expect_err("a zero timeout would abort every attempt at once");
assert!(
format!("{error:#}").contains("pairing_timeout"),
"the error must name the field, got: {error:#}"
);
config_with_default_timeout()
.validate()
.expect("120s is valid");
}
fn config_with_default_timeout() -> ClientConfig {
let config = valid();
assert_eq!(config.pairing_timeout, crate::DEFAULT_PAIRING_TIMEOUT);
config
}
#[test]
fn a_configuration_debug_names_no_key_material() {
let store = std::sync::Arc::new(crate::test_support::MemoryStore::holding([7u8; 32]));
let config = ClientConfig {
storage: Some(store),
..valid()
};
let text = format!("{config:?}");
assert!(text.contains("ClientConfig"), "unexpected format: {text}");
assert!(
text.contains("<host storage>"),
"the store is named but never delegated to: {text}"
);
assert!(
!text.contains(&config.identity.secret_base64()),
"the identity secret must stay out of a debug format: {text}"
);
}
#[test]
fn a_stored_psk_formats_without_its_key_material() {
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use base64::Engine as _;
let psk = [0xab; 32];
let record = StoredPsk {
category: PskCategory::Pairing,
psk,
server_id: "B1y4w7z0c3f6i9l2o5r8u1x4a7d0g3j6m9p2s5v8y1b".to_owned(),
};
let text = format!("{record:?}");
assert!(text.contains("StoredPsk"), "unexpected format: {text}");
assert!(text.contains("Pairing"), "the category is not key material");
assert!(text.contains("B1y4w7z0c3f6i9l2o5r8u1x4a7d0g3j6m9p2s5v8y1b"));
assert!(text.contains("<redacted>"));
assert!(
!text.contains(&URL_SAFE_NO_PAD.encode(psk)),
"the key must never appear in a debug format: {text}"
);
assert!(
!text.contains(&format!("{psk:?}")),
"not even the raw bytes may appear: {text}"
);
}
#[cfg(feature = "pairing-code")]
#[test]
fn the_code_descriptor_lists_are_set_together() {
let formats_only = ClientConfig {
code_formats: vec![CodeFormat::Digits],
..valid()
};
let error = formats_only
.validate()
.expect_err("a format without a channel is not a usable descriptor");
assert!(
format!("{error:#}").contains("code_out_channels"),
"the error names the missing list, got: {error:#}"
);
let channels_only = ClientConfig {
code_out_channels: vec![CodeOutChannel::Display],
..valid()
};
let error = channels_only
.validate()
.expect_err("a channel without a format is not a usable descriptor");
assert!(
format!("{error:#}").contains("code_formats"),
"the error names the missing list, got: {error:#}"
);
ClientConfig {
code_formats: vec![CodeFormat::Digits, CodeFormat::QrCode],
code_out_channels: vec![CodeOutChannel::Display],
..valid()
}
.validate()
.expect("both lists make the method offerable");
}
#[cfg(feature = "pairing-code")]
#[test]
fn the_code_types_round_trip_through_their_wire_names() {
assert_eq!(CodeFormat::Digits.as_wire(), "digits");
assert_eq!(CodeFormat::QrCode.as_wire(), "qr_code");
assert_eq!(CodeFormat::from_wire("digits"), Some(CodeFormat::Digits));
assert_eq!(CodeFormat::from_wire("qr_code"), Some(CodeFormat::QrCode));
assert_eq!(
CodeFormat::from_wire("nfc"),
None,
"a format this revision does not know selects nothing"
);
assert_eq!(CodeOutChannel::Display.as_wire(), "display");
assert_eq!(CodeOutChannel::Speaker.as_wire(), "speaker");
}
#[test]
fn an_empty_server_address_is_rejected() {
for server in ["", " "] {
let config = ClientConfig {
server: server.to_owned(),
..valid()
};
let error = config.validate().expect_err("an empty address has no host");
assert!(
format!("{error:#}").contains("server"),
"the error must name the address, got: {error:#}"
);
}
}
#[test]
fn a_player_name_is_bounded_by_the_protocol_length() {
let longest = ClientConfig {
player_name: "a".repeat(MAX_PLAYER_NAME_LEN),
..valid()
};
longest
.validate()
.expect("a name at the limit must be accepted");
let config = ClientConfig {
player_name: "a".repeat(MAX_PLAYER_NAME_LEN + 1),
..valid()
};
let error = config
.validate()
.expect_err("a name above the limit must be rejected");
let message = format!("{error:#}");
assert!(
message.contains("player_name")
&& message.contains(&(MAX_PLAYER_NAME_LEN + 1).to_string()),
"the error must name the field and the length, got: {message}"
);
let config = ClientConfig {
player_name: " \t ".to_owned(),
..valid()
};
let error = config
.validate()
.expect_err("a blank name must be rejected");
assert!(format!("{error:#}").contains("player_name"));
}
#[cfg(feature = "pairing-code")]
#[test]
fn a_static_pairing_code_is_exactly_eight_digits() {
for code in ["12345678", "00000000", "99999999"] {
let config = ClientConfig {
static_pairing_code: Some(code.to_owned()),
..valid()
};
config
.validate()
.unwrap_or_else(|error| panic!("{code:?} must be accepted: {error:#}"));
}
for code in [
"",
"1234567",
"123456789",
"1234 678",
"1234567a",
"--------",
"12345678",
] {
let config = ClientConfig {
static_pairing_code: Some(code.to_owned()),
..valid()
};
let error = config
.validate()
.expect_err("a code that is not eight digits must be rejected");
let message = format!("{error:#}");
assert!(
message.contains("static_pairing_code"),
"the error must name the field, got: {message}"
);
assert!(
!message.contains(code) || code.is_empty(),
"the code is a credential and must not appear in the error: {message}"
);
}
}
#[cfg(feature = "pairing-code")]
#[test]
fn the_pairing_window_and_pending_text_are_bounded() {
let config = ClientConfig {
pairing_window: Duration::ZERO,
..valid()
};
let error = config
.validate()
.expect_err("a zero window cannot admit an attempt");
assert!(
format!("{error:#}").contains("pairing_window"),
"the error must name the field, got: {error:#}"
);
let longest = ClientConfig {
pairing_pending_text: Some("a".repeat(MAX_PAIRING_PENDING_TEXT_LEN)),
..valid()
};
longest
.validate()
.expect("a sentence at the limit must be accepted");
let config = ClientConfig {
pairing_pending_text: Some("a".repeat(MAX_PAIRING_PENDING_TEXT_LEN + 1)),
..valid()
};
let error = config
.validate()
.expect_err("a sentence above the limit must be rejected");
assert!(
format!("{error:#}").contains("pairing_pending_text"),
"the error must name the field, got: {error:#}"
);
}
#[cfg(feature = "pairing-code")]
#[test]
fn a_static_pairing_code_is_redacted_in_debug() {
let config = ClientConfig {
static_pairing_code: Some("12345678".to_owned()),
..valid()
};
let text = format!("{config:?}");
assert!(
text.contains("static_pairing_code: Some(\"<redacted>\")"),
"the field must be named but redacted: {text}"
);
assert!(
!text.contains("12345678"),
"the code must never appear in a debug format: {text}"
);
}
}