use std::time::Duration;
use serde_json::Value;
use crate::redact;
#[derive(thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("{message}")]
Authentication {
message: String,
envelope: Option<Value>,
error_code: Option<String>,
},
#[error("{message}")]
RateLimit {
message: String,
retry_after: Option<Duration>,
envelope: Option<Value>,
error_code: Option<String>,
},
#[error("Network error: {0}")]
Network(#[source] reqwest::Error),
#[error("API error {status}: {message}")]
Api {
status: u16,
message: String,
envelope: Option<Value>,
error_code: Option<String>,
url: Option<String>,
},
#[error("Request timed out")]
Timeout,
#[error("API error {status}: {message}")]
AccessDenied {
status: u16,
message: String,
envelope: Option<Value>,
error_code: Option<String>,
},
#[error("API error {status}: {message}")]
ClientBlocked {
status: u16,
message: String,
envelope: Option<Value>,
error_code: Option<String>,
},
#[error("API error {status}: {message}")]
NotFound {
status: u16,
message: String,
envelope: Option<Value>,
error_code: Option<String>,
},
#[error("API error {}: {message}", status.map_or_else(|| "None".to_owned(), |s| s.to_string()))]
PremiumRequired {
status: Option<u16>,
message: String,
envelope: Option<Value>,
error_code: Option<String>,
},
#[error("API error {}: {message}", status.map_or_else(|| "None".to_owned(), |s| s.to_string()))]
FeatureUnavailable {
status: Option<u16>,
message: String,
envelope: Option<Value>,
error_code: Option<String>,
},
#[error("Validation error for '{field}': {message}")]
Validation {
field: String,
message: String,
envelope: Option<Value>,
error_code: Option<String>,
},
#[error("No network ID provided and no preferred network set")]
MissingNetworkId,
#[error(transparent)]
Storage(#[from] StorageError),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
}
fn debug_envelope(envelope: Option<&Value>) -> Option<Value> {
envelope.map(redact::redact_sensitive)
}
fn debug_url_path_only(url: Option<&String>) -> Option<String> {
url.map(|full| {
url::Url::parse(full).map_or_else(
|_| full.split(['?', '#']).next().unwrap_or(full).to_owned(),
|parsed| parsed.path().to_owned(),
)
})
}
impl std::fmt::Debug for Error {
#[allow(clippy::too_many_lines)]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Error::Authentication {
message,
envelope,
error_code,
} => f
.debug_struct("Authentication")
.field("message", message)
.field("envelope", &debug_envelope(envelope.as_ref()))
.field("error_code", error_code)
.finish(),
Error::RateLimit {
message,
retry_after,
envelope,
error_code,
} => f
.debug_struct("RateLimit")
.field("message", message)
.field("retry_after", retry_after)
.field("envelope", &debug_envelope(envelope.as_ref()))
.field("error_code", error_code)
.finish(),
Error::Network(err) => f.debug_tuple("Network").field(err).finish(),
Error::Api {
status,
message,
envelope,
error_code,
url,
} => f
.debug_struct("Api")
.field("status", status)
.field("message", message)
.field("envelope", &debug_envelope(envelope.as_ref()))
.field("error_code", error_code)
.field("url", &debug_url_path_only(url.as_ref()))
.finish(),
Error::Timeout => write!(f, "Timeout"),
Error::AccessDenied {
status,
message,
envelope,
error_code,
} => f
.debug_struct("AccessDenied")
.field("status", status)
.field("message", message)
.field("envelope", &debug_envelope(envelope.as_ref()))
.field("error_code", error_code)
.finish(),
Error::ClientBlocked {
status,
message,
envelope,
error_code,
} => f
.debug_struct("ClientBlocked")
.field("status", status)
.field("message", message)
.field("envelope", &debug_envelope(envelope.as_ref()))
.field("error_code", error_code)
.finish(),
Error::NotFound {
status,
message,
envelope,
error_code,
} => f
.debug_struct("NotFound")
.field("status", status)
.field("message", message)
.field("envelope", &debug_envelope(envelope.as_ref()))
.field("error_code", error_code)
.finish(),
Error::PremiumRequired {
status,
message,
envelope,
error_code,
} => f
.debug_struct("PremiumRequired")
.field("status", status)
.field("message", message)
.field("envelope", &debug_envelope(envelope.as_ref()))
.field("error_code", error_code)
.finish(),
Error::FeatureUnavailable {
status,
message,
envelope,
error_code,
} => f
.debug_struct("FeatureUnavailable")
.field("status", status)
.field("message", message)
.field("envelope", &debug_envelope(envelope.as_ref()))
.field("error_code", error_code)
.finish(),
Error::Validation {
field,
message,
envelope,
error_code,
} => f
.debug_struct("Validation")
.field("field", field)
.field("message", message)
.field("envelope", &debug_envelope(envelope.as_ref()))
.field("error_code", error_code)
.finish(),
Error::MissingNetworkId => write!(f, "MissingNetworkId"),
Error::Storage(err) => f.debug_tuple("Storage").field(err).finish(),
Error::Json(err) => f.debug_tuple("Json").field(err).finish(),
}
}
}
impl Error {
#[must_use]
pub fn authentication(message: impl Into<String>) -> Self {
Error::Authentication {
message: message.into(),
envelope: None,
error_code: None,
}
}
#[must_use]
pub fn validation(field: impl Into<String>, message: impl Into<String>) -> Self {
Error::Validation {
field: field.into(),
message: message.into(),
envelope: None,
error_code: None,
}
}
#[must_use]
pub fn envelope(&self) -> Option<&Value> {
match self {
Error::Authentication { envelope, .. }
| Error::RateLimit { envelope, .. }
| Error::Api { envelope, .. }
| Error::AccessDenied { envelope, .. }
| Error::ClientBlocked { envelope, .. }
| Error::NotFound { envelope, .. }
| Error::PremiumRequired { envelope, .. }
| Error::FeatureUnavailable { envelope, .. }
| Error::Validation { envelope, .. } => envelope.as_ref(),
Error::Network(_)
| Error::Timeout
| Error::MissingNetworkId
| Error::Storage(_)
| Error::Json(_) => None,
}
}
#[must_use]
pub fn error_code(&self) -> Option<&str> {
match self {
Error::Authentication { error_code, .. }
| Error::RateLimit { error_code, .. }
| Error::Api { error_code, .. }
| Error::AccessDenied { error_code, .. }
| Error::ClientBlocked { error_code, .. }
| Error::NotFound { error_code, .. }
| Error::PremiumRequired { error_code, .. }
| Error::FeatureUnavailable { error_code, .. }
| Error::Validation { error_code, .. } => error_code.as_deref(),
Error::Network(_)
| Error::Timeout
| Error::MissingNetworkId
| Error::Storage(_)
| Error::Json(_) => None,
}
}
#[must_use]
pub fn status(&self) -> Option<u16> {
match self {
Error::Api { status, .. }
| Error::AccessDenied { status, .. }
| Error::ClientBlocked { status, .. }
| Error::NotFound { status, .. } => Some(*status),
Error::PremiumRequired { status, .. } | Error::FeatureUnavailable { status, .. } => {
*status
}
Error::Authentication { .. }
| Error::RateLimit { .. }
| Error::Network(_)
| Error::Timeout
| Error::Validation { .. }
| Error::MissingNetworkId
| Error::Storage(_)
| Error::Json(_) => None,
}
}
#[must_use]
pub fn is_auth_error(&self) -> bool {
matches!(self, Error::Authentication { .. }) || self.status() == Some(401)
}
}
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum StorageError {
#[error("storage I/O error: {0}")]
Io(#[from] std::io::Error),
#[error("storage serialization error: {0}")]
Serde(#[from] serde_json::Error),
#[error("{backend} storage error: {message}")]
Backend {
backend: String,
message: String,
},
#[error("no credentials stored")]
NotFound,
#[error("stored credentials are empty")]
Empty,
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use super::{Error, StorageError};
#[test]
fn authentication_display_is_verbatim_message() {
let err = Error::authentication("Not authenticated");
assert_eq!(err.to_string(), "Not authenticated");
}
#[test]
fn rate_limit_display_is_the_message() {
let err = Error::RateLimit {
message: "error.rate.limit".to_owned(),
retry_after: None,
envelope: None,
error_code: Some("error.rate.limit".to_owned()),
};
assert_eq!(err.to_string(), "error.rate.limit");
let err = Error::RateLimit {
message: "error.rate.limit".to_owned(),
retry_after: Some(Duration::from_secs(30)),
envelope: None,
error_code: None,
};
assert_eq!(err.to_string(), "error.rate.limit");
}
#[test]
fn api_display_matches_python_format() {
let err = Error::Api {
status: 500,
message: "boom".to_owned(),
envelope: None,
error_code: None,
url: None,
};
assert_eq!(err.to_string(), "API error 500: boom");
}
#[test]
fn api_display_excludes_url_field_even_when_it_carries_a_token() {
let err = Error::Api {
status: 404,
message: "not found".to_owned(),
envelope: None,
error_code: None,
url: Some("https://api-user.e2ro.com/2.2/foo?s=secret-token".to_owned()),
};
let rendered = err.to_string();
assert_eq!(rendered, "API error 404: not found");
assert!(!rendered.contains("secret-token"));
}
#[test]
fn timeout_display_is_fixed_message() {
assert_eq!(Error::Timeout.to_string(), "Request timed out");
}
#[test]
fn access_denied_display_matches_python_format() {
let err = Error::AccessDenied {
status: 403,
message: "error.access.denied".to_owned(),
envelope: None,
error_code: Some("error.access.denied".to_owned()),
};
assert_eq!(err.to_string(), "API error 403: error.access.denied");
}
#[test]
fn client_blocked_display_matches_python_format() {
let err = Error::ClientBlocked {
status: 200,
message: "error.app.version.blocked".to_owned(),
envelope: None,
error_code: None,
};
assert_eq!(err.to_string(), "API error 200: error.app.version.blocked");
}
#[test]
fn not_found_display_matches_python_format() {
let err = Error::NotFound {
status: 404,
message: "unrecognised error string".to_owned(),
envelope: None,
error_code: None,
};
assert_eq!(err.to_string(), "API error 404: unrecognised error string");
}
#[test]
fn premium_required_display_matches_python_str_of_optional_status() {
let err = Error::PremiumRequired {
status: Some(200),
message: "error.premium.user_not_subscribed".to_owned(),
envelope: None,
error_code: None,
};
assert_eq!(
err.to_string(),
"API error 200: error.premium.user_not_subscribed"
);
let err = Error::PremiumRequired {
status: None,
message: "This feature requires an Eero Plus subscription".to_owned(),
envelope: None,
error_code: None,
};
assert_eq!(
err.to_string(),
"API error None: This feature requires an Eero Plus subscription"
);
}
#[test]
fn feature_unavailable_display_matches_python_format() {
let err = Error::FeatureUnavailable {
status: Some(200),
message: "error.eero.offline".to_owned(),
envelope: None,
error_code: None,
};
assert_eq!(err.to_string(), "API error 200: error.eero.offline");
}
#[test]
fn validation_display_matches_python_format() {
let err = Error::validation("field", "msg");
assert_eq!(err.to_string(), "Validation error for 'field': msg");
}
#[test]
fn missing_network_id_display_is_fixed_message() {
assert_eq!(
Error::MissingNetworkId.to_string(),
"No network ID provided and no preferred network set"
);
}
#[test]
fn storage_display_is_transparent() {
let err = Error::Storage(StorageError::NotFound);
assert_eq!(err.to_string(), "no credentials stored");
}
#[test]
fn json_display_wraps_serde_error() {
let serde_err = serde_json::from_str::<serde_json::Value>("not json").unwrap_err();
let err = Error::Json(serde_err);
assert!(err.to_string().starts_with("JSON error: "));
}
#[test]
fn network_display_wraps_reqwest_error() {
let reqwest_err = reqwest::Client::new()
.get("not a valid url")
.build()
.expect_err("malformed URL must fail to build");
let err = Error::Network(reqwest_err);
assert!(err.to_string().starts_with("Network error: "));
}
#[test]
fn storage_error_display_strings() {
assert_eq!(
StorageError::Backend {
backend: "keyring".to_owned(),
message: "entry not found".to_owned(),
}
.to_string(),
"keyring storage error: entry not found"
);
assert_eq!(StorageError::NotFound.to_string(), "no credentials stored");
assert_eq!(
StorageError::Empty.to_string(),
"stored credentials are empty"
);
}
#[test]
fn envelope_and_error_code_accessors_round_trip() {
let envelope = serde_json::json!({"meta": {"code": 404}});
let err = Error::NotFound {
status: 404,
message: "unrecognised error string".to_owned(),
envelope: Some(envelope.clone()),
error_code: Some("weird".to_owned()),
};
assert_eq!(err.envelope(), Some(&envelope));
assert_eq!(err.error_code(), Some("weird"));
assert_eq!(err.status(), Some(404));
}
#[test]
fn envelope_and_error_code_are_none_for_client_side_errors() {
let err = Error::authentication("Not authenticated");
assert_eq!(err.envelope(), None);
assert_eq!(err.error_code(), None);
assert_eq!(err.status(), None);
assert_eq!(Error::Timeout.envelope(), None);
assert_eq!(Error::MissingNetworkId.error_code(), None);
}
#[test]
fn is_auth_error_matrix() {
assert!(Error::authentication("Not authenticated").is_auth_error());
assert!(
Error::Api {
status: 401,
message: String::new(),
envelope: None,
error_code: None,
url: None,
}
.is_auth_error()
);
assert!(
Error::AccessDenied {
status: 401,
message: String::new(),
envelope: None,
error_code: None,
}
.is_auth_error()
);
assert!(
!Error::Api {
status: 403,
message: String::new(),
envelope: None,
error_code: None,
url: None,
}
.is_auth_error()
);
assert!(
!Error::AccessDenied {
status: 403,
message: String::new(),
envelope: None,
error_code: None,
}
.is_auth_error()
);
assert!(
!Error::NotFound {
status: 404,
message: String::new(),
envelope: None,
error_code: None,
}
.is_auth_error()
);
assert!(
!Error::RateLimit {
message: String::new(),
retry_after: None,
envelope: None,
error_code: None,
}
.is_auth_error()
);
assert!(!Error::Timeout.is_auth_error());
assert!(
!Error::PremiumRequired {
status: None,
message: String::new(),
envelope: None,
error_code: None,
}
.is_auth_error()
);
assert!(
!Error::FeatureUnavailable {
status: None,
message: String::new(),
envelope: None,
error_code: None,
}
.is_auth_error()
);
assert!(!Error::validation("x", "y").is_auth_error());
assert!(!Error::MissingNetworkId.is_auth_error());
assert!(!Error::Storage(StorageError::NotFound).is_auth_error());
assert!(
!Error::Json(serde_json::from_str::<serde_json::Value>("bad").unwrap_err())
.is_auth_error()
);
}
#[test]
fn storage_error_from_io_error() {
let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "no such file");
let storage_err: StorageError = io_err.into();
assert!(matches!(storage_err, StorageError::Io(_)));
}
#[test]
fn storage_error_from_serde_error() {
let serde_err = serde_json::from_str::<serde_json::Value>("not json").unwrap_err();
let storage_err: StorageError = serde_err.into();
assert!(matches!(storage_err, StorageError::Serde(_)));
}
#[test]
fn error_from_storage_error() {
let err: Error = StorageError::NotFound.into();
assert!(matches!(err, Error::Storage(StorageError::NotFound)));
}
#[test]
fn error_from_serde_error() {
let serde_err = serde_json::from_str::<serde_json::Value>("not json").unwrap_err();
let err: Error = serde_err.into();
assert!(matches!(err, Error::Json(_)));
}
#[test]
fn api_debug_never_prints_the_envelope_password_or_the_url_query() {
let err = Error::Api {
status: 200,
message: "boom".to_owned(),
envelope: Some(serde_json::json!({"password": "hunter2"})),
error_code: None,
url: Some("https://api-user.e2ro.com/2.2/account?serial=SECRET".to_owned()),
};
let debug = format!("{err:?}");
assert!(
!debug.contains("hunter2"),
"envelope value must be redacted, got {debug:?}"
);
assert!(
!debug.contains("SECRET"),
"url query string must be stripped, got {debug:?}"
);
assert!(
debug.contains("[REDACTED"),
"the redacted envelope's marker must still be visible, got {debug:?}"
);
assert!(
debug.contains("/2.2/account"),
"the url path itself is not sensitive and should still be visible, got {debug:?}"
);
}
#[test]
fn authentication_debug_never_prints_the_envelope_password() {
let err = Error::Authentication {
message: "failed".to_owned(),
envelope: Some(serde_json::json!({"token": "abc123456"})),
error_code: None,
};
let debug = format!("{err:?}");
assert!(!debug.contains("abc123456"));
assert!(debug.contains("[REDACTED"));
}
#[test]
fn debug_with_no_envelope_or_url_still_renders() {
let err = Error::Timeout;
assert_eq!(format!("{err:?}"), "Timeout");
let err = Error::MissingNetworkId;
assert_eq!(format!("{err:?}"), "MissingNetworkId");
}
}