use std::panic::AssertUnwindSafe;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, PoisonError, RwLock, Weak};
use std::time::Duration;
use reqwest::header::{
ACCEPT, CONTENT_TYPE, COOKIE, HeaderMap, HeaderName, LOCATION, RETRY_AFTER, USER_AGENT,
};
use reqwest::redirect::Policy;
use reqwest::{Client, Method, StatusCode};
use secrecy::SecretString;
use serde_json::Value;
use tokio::sync::watch;
use url::Url;
use crate::auth::Session;
use crate::consts;
use crate::envelope::Envelope;
use crate::error::{Error, StorageError};
use crate::errors;
use crate::links::{self, OriginMismatch};
use crate::redact;
use crate::routes::{self, ApiVersion, Nested, Resource};
use crate::storage::{self, CredentialStore};
#[derive(Debug, Clone)]
pub enum RequestBody {
None,
Json(Value),
Form(Vec<(String, String)>),
EmptyJsonString,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct RequestTimeout {
pub total: Option<Duration>,
pub read: Option<Duration>,
}
impl RequestTimeout {
#[must_use]
pub const fn new(total: Option<Duration>, read: Option<Duration>) -> Self {
Self { total, read }
}
#[must_use]
pub const fn total(total: Duration) -> Self {
Self {
total: Some(total),
read: None,
}
}
}
#[derive(Debug, Clone, Copy)]
struct Bounds {
total: Option<Duration>,
read: Option<Duration>,
per_call: bool,
}
#[derive(Debug)]
pub struct Transport {
http: Client,
api_host: Url,
session: RwLock<Option<Session>>,
store: Option<Arc<dyn CredentialStore>>,
persistence: Arc<Persistence>,
storage_failures: StorageFailures,
user_agent: String,
accept_language: String,
send_legacy_cookie: bool,
get_retries: u32,
timeout: RequestTimeout,
refresh_slot: tokio::sync::Mutex<Weak<watch::Sender<Option<bool>>>>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum StorageFailures {
#[default]
Warn,
Fatal,
}
#[derive(Debug)]
struct Persistence {
generation: AtomicU64,
io: Mutex<()>,
last_ok: AtomicBool,
}
impl Persistence {
fn new() -> Self {
Self {
generation: AtomicU64::new(0),
io: Mutex::new(()),
last_ok: AtomicBool::new(true),
}
}
fn persist(
&self,
store: &dyn CredentialStore,
ticket: u64,
session: Option<&Session>,
) -> Result<(), StorageError> {
let _gate = self.io.lock().unwrap_or_else(PoisonError::into_inner);
if self.generation.load(Ordering::SeqCst) != ticket {
tracing::debug!("session persist skipped: a newer session change supersedes it");
return Ok(());
}
let Some(session) = session else {
self.last_ok.store(true, Ordering::SeqCst);
return store.clear();
};
match std::panic::catch_unwind(AssertUnwindSafe(|| store.save(session))) {
Ok(result) => {
self.last_ok.store(result.is_ok(), Ordering::SeqCst);
result
}
Err(payload) => {
self.last_ok.store(false, Ordering::SeqCst);
std::panic::resume_unwind(payload)
}
}
}
}
#[derive(Debug)]
struct TicketedStore {
store: Arc<dyn CredentialStore>,
persistence: Arc<Persistence>,
ticket: u64,
}
impl CredentialStore for TicketedStore {
fn load(&self) -> Result<Session, StorageError> {
self.store.load()
}
fn save(&self, session: &Session) -> Result<(), StorageError> {
self.persistence
.persist(self.store.as_ref(), self.ticket, Some(session))
}
fn clear(&self) -> Result<(), StorageError> {
self.persistence
.persist(self.store.as_ref(), self.ticket, None)
}
}
impl Transport {
#[must_use]
pub fn builder() -> TransportBuilder {
TransportBuilder::default()
}
#[must_use]
pub fn api_host(&self) -> &Url {
&self.api_host
}
#[must_use]
pub fn user_agent(&self) -> &str {
&self.user_agent
}
#[must_use]
pub fn session(&self) -> Option<Session> {
self.session_snapshot()
}
pub fn set_session(&self, session: Option<Session>) -> Result<(), Error> {
if let Some(ref s) = session {
crate::auth::session::validate_token_shape("token", s.expose_token())?;
}
let Some(store) = &self.store else {
self.replace_session(session);
return Ok(());
};
let for_store = session.clone();
let saving = for_store.is_some();
let ticket = self.replace_session(session);
let outcome = self
.persistence
.persist(store.as_ref(), ticket, for_store.as_ref());
self.apply_storage_policy(outcome, saving)
}
pub async fn set_session_async(&self, session: Option<Session>) -> Result<(), Error> {
self.set_session_async_then(session, || {}).await
}
pub(crate) async fn set_session_async_then(
&self,
session: Option<Session>,
on_replaced: impl FnOnce(),
) -> Result<(), Error> {
if let Some(ref s) = session {
crate::auth::session::validate_token_shape("token", s.expose_token())?;
}
let Some(store) = &self.store else {
self.replace_session(session);
on_replaced();
return Ok(());
};
let for_store = session.clone();
let saving = for_store.is_some();
let ticket = self.replace_session(session);
on_replaced();
let ticketed: Arc<dyn CredentialStore> = Arc::new(TicketedStore {
store: Arc::clone(store),
persistence: Arc::clone(&self.persistence),
ticket,
});
let outcome = match for_store {
Some(s) => storage::save_async(ticketed, s).await,
None => storage::clear_async(ticketed).await,
};
if saving
&& outcome.is_err()
&& self.persistence.generation.load(Ordering::SeqCst) == ticket
{
self.persistence.last_ok.store(false, Ordering::SeqCst);
}
self.apply_storage_policy(outcome, saving)
}
#[must_use]
pub fn credentials_persisted(&self) -> bool {
self.persistence.last_ok.load(Ordering::SeqCst)
}
fn apply_storage_policy(
&self,
outcome: Result<(), StorageError>,
saving: bool,
) -> Result<(), Error> {
match outcome {
Ok(()) => Ok(()),
Err(err) => match self.storage_failures {
StorageFailures::Warn => {
let reported = !storage::is_task_failure(&err)
&& self
.store
.as_deref()
.is_some_and(CredentialStore::reports_failures);
match (reported, saving) {
(true, true) => tracing::debug!(
error = %err,
"credential store failed to persist the session (already reported)"
),
(true, false) => tracing::debug!(
error = %err,
"credential store failed to clear the session (already reported)"
),
(false, true) => tracing::warn!(
error = %err,
"failed to persist session to credential store"
),
(false, false) => tracing::warn!(
error = %err,
"failed to clear session from credential store"
),
}
Ok(())
}
StorageFailures::Fatal => Err(err.into()),
},
}
}
#[must_use]
pub fn is_authenticated(&self) -> bool {
self.session_snapshot()
.is_some_and(|session| session.is_valid())
}
pub async fn request(
&self,
method: Method,
url: Url,
query: &[(&str, String)],
body: RequestBody,
) -> Result<Envelope, Error> {
self.request_with_timeout(method, url, query, body, None)
.await
}
pub async fn request_with_timeout(
&self,
method: Method,
url: Url,
query: &[(&str, String)],
body: RequestBody,
timeout: Option<RequestTimeout>,
) -> Result<Envelope, Error> {
reject_userinfo(&url)?;
let token = self.current_token().ok_or_else(not_authenticated)?;
let first = self
.execute_with_get_retry(&method, &url, query, &body, Some(&token), timeout)
.await;
if first.as_ref().err().is_some_and(refresh_requested) && self.refresh_session().await? {
let retry_token = self.current_token().ok_or_else(not_authenticated)?;
return self
.execute_with_get_retry(&method, &url, query, &body, Some(&retry_token), timeout)
.await;
}
first
}
pub async fn resource(
&self,
route: &Resource,
id_or_url: &str,
parent: Option<&Value>,
query: &[(&str, String)],
body: RequestBody,
) -> Result<Envelope, Error> {
self.resource_with_timeout(route, id_or_url, parent, query, body, None)
.await
}
pub async fn resource_with_timeout(
&self,
route: &Resource,
id_or_url: &str,
parent: Option<&Value>,
query: &[(&str, String)],
body: RequestBody,
timeout: Option<RequestTimeout>,
) -> Result<Envelope, Error> {
let url = route.resolve(self.api_host(), id_or_url, parent)?;
self.request_with_timeout(route.method.clone(), url, query, body, timeout)
.await
}
pub async fn nested(
&self,
route: &Nested,
network: &str,
child: &str,
parent: Option<&Value>,
query: &[(&str, String)],
body: RequestBody,
) -> Result<Envelope, Error> {
self.nested_with_timeout(route, network, child, parent, query, body, None)
.await
}
#[allow(clippy::too_many_arguments)]
pub async fn nested_with_timeout(
&self,
route: &Nested,
network: &str,
child: &str,
parent: Option<&Value>,
query: &[(&str, String)],
body: RequestBody,
timeout: Option<RequestTimeout>,
) -> Result<Envelope, Error> {
let url = route.resolve(self.api_host(), network, child, parent)?;
self.request_with_timeout(route.method.clone(), url, query, body, timeout)
.await
}
pub(crate) async fn request_with_token(
&self,
method: Method,
url: Url,
query: &[(&str, String)],
body: RequestBody,
token: Option<&SecretString>,
) -> Result<Envelope, Error> {
reject_userinfo(&url)?;
self.execute_with_get_retry(&method, &url, query, &body, token, None)
.await
}
pub async fn refresh_session(&self) -> Result<bool, Error> {
enum Role {
Leader(Arc<watch::Sender<Option<bool>>>),
Waiter(watch::Receiver<Option<bool>>),
}
let role = {
let mut guard = self.refresh_slot.lock().await;
if let Some(sender) = guard.upgrade() {
let rx = sender.subscribe();
Role::Waiter(rx)
} else {
let (tx, _rx) = watch::channel(None);
let tx = Arc::new(tx);
*guard = Arc::downgrade(&tx);
Role::Leader(tx)
}
};
match role {
Role::Leader(tx) => {
let result = self.do_refresh().await;
let broadcast = match &result {
Ok(refreshed) => Some(*refreshed),
Err(_) => Some(false),
};
let _ = tx.send(broadcast);
result
}
Role::Waiter(mut rx) => {
let wait = async {
loop {
if let Some(value) = *rx.borrow_and_update() {
return value;
}
if rx.changed().await.is_err() {
return false;
}
}
};
match tokio::time::timeout(consts::SESSION_REFRESH_GUARD_TIMEOUT, wait).await {
Ok(value) => Ok(value),
Err(_elapsed) => Ok(false),
}
}
}
}
async fn do_refresh(&self) -> Result<bool, Error> {
let session = self.session_snapshot();
let Some(token) = session.filter(Session::is_valid).map(|s| s.token().clone()) else {
return Err(Error::authentication(
"No session token available. Login first.",
));
};
let url = routes::LOGIN_REFRESH.resolve(self.api_host(), "", None)?;
match self
.request_with_token(
Method::POST,
url,
&[],
RequestBody::EmptyJsonString,
Some(&token),
)
.await
{
Ok(_envelope) => {
tracing::debug!("Session refreshed; server-issued token ignored per SDK policy");
Ok(true)
}
Err(Error::Authentication { error_code, .. }) => {
let group = errors::classify_error_code(error_code.as_deref());
let retain = matches!(
group,
Some(errors::ErrorGroup::Verification | errors::ErrorGroup::SessionRefresh)
);
if !retain {
self.set_session_async(None).await?;
}
Ok(false)
}
Err(err @ (Error::Network(_) | Error::Timeout)) => Err(err),
Err(_other) => Ok(false),
}
}
fn session_snapshot(&self) -> Option<Session> {
self.session
.read()
.unwrap_or_else(PoisonError::into_inner)
.clone()
}
fn current_token(&self) -> Option<SecretString> {
self.session_snapshot()
.filter(Session::is_valid)
.map(|session| session.token().clone())
}
fn replace_session(&self, session: Option<Session>) -> u64 {
let mut guard = self.session.write().unwrap_or_else(PoisonError::into_inner);
*guard = session;
self.persistence.generation.fetch_add(1, Ordering::SeqCst) + 1
}
fn origin_mismatch(&self, url: &Url) -> Option<OriginMismatch> {
links::origin_mismatch(url, &self.api_host)
}
fn apply_credentials(
&self,
mut request: reqwest::RequestBuilder,
url: &Url,
token: Option<&SecretString>,
) -> reqwest::RequestBuilder {
let Some(token) = token else {
return request;
};
if let Some(mismatch) = self.origin_mismatch(url) {
tracing::warn!(reason = mismatch.reason, "{}", withheld_message(&mismatch));
return request;
}
let token_str = Session::expose_secret_token(token);
request = request.header(user_token_header(), token_str);
if self.send_legacy_cookie {
request = request.header(
COOKIE,
format!("{}={}", consts::SESSION_COOKIE_NAME, token_str),
);
}
request
}
fn apply_body(request: reqwest::RequestBuilder, body: &RequestBody) -> reqwest::RequestBuilder {
match body {
RequestBody::None => request,
RequestBody::Json(value) => request.json(value),
RequestBody::Form(pairs) => {
let mut serializer = url::form_urlencoded::Serializer::new(String::new());
for (key, value) in pairs {
serializer.append_pair(key, value);
}
request
.header(CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(serializer.finish())
}
RequestBody::EmptyJsonString => request
.header(CONTENT_TYPE, "application/json")
.body("\"\""),
}
}
async fn execute_with_get_retry(
&self,
method: &Method,
url: &Url,
query: &[(&str, String)],
body: &RequestBody,
token: Option<&SecretString>,
timeout: Option<RequestTimeout>,
) -> Result<Envelope, Error> {
let mut attempt: u32 = 0;
loop {
let outcome = match self
.execute_once(method, url, query, body, token, timeout)
.await
{
Ok(exchange) => {
log_api_error(method, exchange.status);
status_to_envelope(
exchange.status,
&exchange.body,
&exchange.url,
exchange.retry_after,
)
}
Err(err) => Err(err),
};
let retryable = *method == Method::GET
&& attempt < self.get_retries
&& outcome.as_ref().err().is_some_and(is_transient_failure);
if !retryable {
return outcome;
}
attempt += 1;
let shown = u64::from(attempt) + 1;
let max_attempts = u64::from(self.get_retries) + 1;
tracing::warn!(
attempt = shown,
max_attempts,
"Retrying GET request after transient failure (attempt {shown}/{max_attempts})"
);
tracing::debug!(path = url.path(), "Retrying GET {}", url.path());
tokio::time::sleep(consts::GET_RETRY_DELAY).await;
}
}
async fn execute_once(
&self,
method: &Method,
url: &Url,
query: &[(&str, String)],
body: &RequestBody,
token: Option<&SecretString>,
timeout: Option<RequestTimeout>,
) -> Result<RawExchange, Error> {
let bounds = self.bounds_for(timeout);
let attempt = self.send_and_read(method, url, query, body, token, bounds);
let outcome = match bounds.total {
Some(total) => tokio::time::timeout(total, attempt)
.await
.unwrap_or_else(|_elapsed| Err(Error::Timeout)),
None => attempt.await,
};
if let Err(err) = &outcome {
log_transport_failure(method, url, err);
}
outcome
}
fn bounds_for(&self, per_call: Option<RequestTimeout>) -> Bounds {
let effective = per_call.unwrap_or(self.timeout);
Bounds {
total: effective.total.filter(|d| !d.is_zero()),
read: effective.read.filter(|d| !d.is_zero()),
per_call: per_call.is_some(),
}
}
async fn send_and_read(
&self,
method: &Method,
url: &Url,
query: &[(&str, String)],
body: &RequestBody,
token: Option<&SecretString>,
bounds: Bounds,
) -> Result<RawExchange, Error> {
let mut url = url.clone();
if !query.is_empty() {
url.query_pairs_mut().extend_pairs(query);
}
let mut request = self.http.request(method.clone(), url.clone());
request = request.header(ACCEPT, "application/json");
request = request.header(USER_AGENT, &self.user_agent);
request = request.header(x_accept_language_header(), &self.accept_language);
request = self.apply_credentials(request, &url, token);
request = Self::apply_body(request, body);
if bounds.per_call {
request = request.timeout(Duration::MAX);
}
let response = match bounds.read {
Some(read) => tokio::time::timeout(read, request.send())
.await
.map_err(|_elapsed| Error::Timeout)?,
None => request.send().await,
}
.map_err(map_reqwest_error)?;
let status = response.status();
tracing::debug!(
method = %method,
path = url.path(),
status = status.as_u16(),
"eero transport request"
);
if response.url() != &url {
return Err(Error::Api {
status: status.as_u16(),
message: format!("Redirect followed unexpectedly: {status} at {}", url.path()),
envelope: None,
error_code: None,
url: Some(url.to_string()),
});
}
if status.is_redirection() {
let location_url = response
.headers()
.get(LOCATION)
.and_then(|value| value.to_str().ok())
.filter(|value| !value.is_empty())
.and_then(|value| Url::parse(value).ok().or_else(|| url.join(value).ok()));
tracing::warn!(
status = status.as_u16(),
"Redirect response {} blocked",
status.as_u16()
);
tracing::debug!(
"Blocked redirect Location: {}",
location_url.as_ref().map_or_else(
|| "<none>".to_owned(),
|loc| format!("{}{}", loc.host_str().unwrap_or(""), loc.path())
)
);
let message = location_url.map_or_else(
|| {
format!(
"Redirect not followed: {} at {} (no Location header)",
status.as_u16(),
url.path()
)
},
|loc| {
format!(
"Redirect not followed: {} at {} -> {}",
status.as_u16(),
url.path(),
loc.host_str().unwrap_or("unknown host")
)
},
);
return Err(Error::Api {
status: status.as_u16(),
message,
envelope: None,
error_code: None,
url: Some(url.to_string()),
});
}
let retry_after = parse_retry_after(response.headers());
let bytes = read_capped_body(response, bounds.read).await?;
let body = decode_body(status, bytes, &url)?;
Ok(RawExchange {
status,
body,
retry_after,
url,
})
}
}
fn withheld_message(mismatch: &OriginMismatch) -> String {
match &mismatch.target {
Some(target) => format!(
"Session header withheld from a request to a {}: {target}",
mismatch.reason
),
None => format!(
"Session header withheld from a request with {}",
mismatch.reason
),
}
}
fn reject_userinfo(url: &Url) -> Result<(), Error> {
if url.username().is_empty() && url.password().is_none() {
Ok(())
} else {
Err(Error::validation("url", "must not carry userinfo"))
}
}
fn user_token_header() -> HeaderName {
HeaderName::from_static("x-user-token")
}
fn x_accept_language_header() -> HeaderName {
HeaderName::from_static("x-accept-language")
}
struct RawExchange {
status: StatusCode,
body: String,
retry_after: Option<Duration>,
url: Url,
}
fn not_authenticated() -> Error {
Error::authentication("Not authenticated")
}
fn status_to_envelope(
status: StatusCode,
body: &str,
url: &Url,
retry_after: Option<Duration>,
) -> Result<Envelope, Error> {
let code = status.as_u16();
if (200..300).contains(&code) {
if status == StatusCode::NO_CONTENT || body.chars().all(is_python_whitespace) {
return Ok(Envelope::empty());
}
let payload = serde_json::from_str::<Value>(body).map_err(|err| {
tracing::error!(
bytes = body.len(),
"Error parsing JSON response ({} bytes): {err}",
body.len()
);
Error::Api {
status: code,
message: format!("Invalid JSON response ({} bytes)", body.len()),
envelope: None,
error_code: None,
url: Some(url.to_string()),
}
})?;
if !payload.is_object() {
let kind = python_type_name(&payload, body);
tracing::error!(
bytes = body.len(),
"Unexpected {kind} in JSON response ({} bytes)",
body.len()
);
return Err(Error::Api {
status: code,
message: "Unexpected JSON response: expected an object".to_owned(),
envelope: None,
error_code: None,
url: Some(url.to_string()),
});
}
return Ok(Envelope::from_value(payload));
}
let envelope = errors::parse_envelope(body);
let error_code = envelope.as_ref().and_then(errors::error_code_from_envelope);
tracing::debug!(
status = code,
envelope = ?envelope.as_ref().map(redacted_for_log),
"eero transport error response"
);
let mut err = errors::error_for_response(code, envelope, error_code, retry_after);
if let Error::Api { url: err_url, .. } = &mut err {
*err_url = Some(url.to_string());
}
Err(err)
}
fn is_python_whitespace(c: char) -> bool {
c.is_whitespace() || ('\u{1c}'..='\u{1f}').contains(&c)
}
fn python_type_name(payload: &Value, body: &str) -> &'static str {
match payload {
Value::Array(_) => "list",
Value::String(_) => "str",
Value::Bool(_) => "bool",
Value::Null => "NoneType",
Value::Number(_) => {
if body.bytes().any(|b| matches!(b, b'.' | b'e' | b'E')) {
"float"
} else {
"int"
}
}
Value::Object(_) => "dict",
}
}
async fn read_capped_body(
mut response: reqwest::Response,
read: Option<Duration>,
) -> Result<Vec<u8>, Error> {
let status = response.status();
let mut buffer: Vec<u8> = Vec::new();
while let Some(chunk) = next_chunk(&mut response, read).await? {
if buffer.len() + chunk.len() > consts::MAX_RESPONSE_BYTES {
return Err(Error::Api {
status: status.as_u16(),
message: format!(
"Response body exceeded max size of {} bytes",
consts::MAX_RESPONSE_BYTES
),
envelope: None,
error_code: None,
url: Some(response.url().to_string()),
});
}
buffer.extend_from_slice(&chunk);
}
Ok(buffer)
}
fn decode_body(status: StatusCode, bytes: Vec<u8>, url: &Url) -> Result<String, Error> {
match String::from_utf8(bytes) {
Ok(text) => Ok(text),
Err(err) if status.is_success() => {
let len = err.as_bytes().len();
tracing::error!(bytes = len, "Undecodable response body ({len} bytes)");
Err(Error::Api {
status: status.as_u16(),
message: "Response body is not valid UTF-8".to_owned(),
envelope: None,
error_code: None,
url: Some(url.to_string()),
})
}
Err(err) => Ok(String::from_utf8_lossy(err.as_bytes()).into_owned()),
}
}
async fn next_chunk(
response: &mut reqwest::Response,
read: Option<Duration>,
) -> Result<Option<bytes::Bytes>, Error> {
let chunk = match read {
Some(read) => tokio::time::timeout(read, response.chunk())
.await
.map_err(|_elapsed| Error::Timeout)?,
None => response.chunk().await,
};
chunk.map_err(map_reqwest_error)
}
fn parse_retry_after(headers: &HeaderMap) -> Option<Duration> {
let raw = headers.get(RETRY_AFTER)?.to_str().ok()?;
let now = jiff::tz::TimeZone::UTC.to_datetime(jiff::Timestamp::now());
parse_retry_after_at(raw, now)
}
fn parse_retry_after_at(raw: &str, now: jiff::civil::DateTime) -> Option<Duration> {
let raw = raw.trim();
if !raw.is_empty() && raw.bytes().all(|b| b.is_ascii_digit()) {
let cap = consts::RETRY_AFTER_MAX.as_secs();
return Some(Duration::from_secs(
raw.parse::<u64>().map_or(cap, |s| s.min(cap)),
));
}
let when = parse_http_date(raw)?;
let delay = Duration::try_from(when.duration_since(now)).unwrap_or(Duration::ZERO);
Some(delay.min(consts::RETRY_AFTER_MAX))
}
fn parse_http_date(raw: &str) -> Option<jiff::civil::DateTime> {
let tokens: Vec<&str> = raw.split_ascii_whitespace().collect();
let mut rest = tokens.as_slice();
if let Some((first, tail)) = rest.split_first()
&& (first.ends_with(',') || is_day_name(first))
{
rest = tail;
}
let (day, month, year, time) = match *rest {
[day, month, year, time, zone] if zone.eq_ignore_ascii_case("GMT") => {
(day, month, year, time)
}
[date, time, zone] if zone.eq_ignore_ascii_case("GMT") => {
let mut parts = date.split('-');
let (day, month, year) = (parts.next()?, parts.next()?, parts.next()?);
if parts.next().is_some() {
return None;
}
(day, month, year, time)
}
[month, day, time, year] => (day, month, year, time),
_ => return None,
};
let mut clock = time.split(':');
let (hour, minute, second) = (clock.next()?, clock.next()?, clock.next()?);
if clock.next().is_some() {
return None;
}
let year = i16::try_from(parse_year(year)?).ok()?;
if year < 1 {
return None;
}
jiff::civil::DateTime::new(
year,
parse_month(month)?,
parse_digits(day, 2)?,
parse_digits(hour, 2)?,
parse_digits(minute, 2)?,
parse_digits(second, 2)?,
0,
)
.ok()
}
fn is_day_name(token: &str) -> bool {
const DAYS: [&str; 7] = ["mon", "tue", "wed", "thu", "fri", "sat", "sun"];
token.len() >= 3
&& token.is_char_boundary(3)
&& DAYS.iter().any(|day| token[..3].eq_ignore_ascii_case(day))
&& token.bytes().all(|b| b.is_ascii_alphabetic())
}
fn parse_month(token: &str) -> Option<i8> {
const MONTHS: [&str; 12] = [
"jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "oct", "nov", "dec",
];
let position = MONTHS
.iter()
.position(|month| token.eq_ignore_ascii_case(month))?;
i8::try_from(position + 1).ok()
}
fn parse_digits(token: &str, max_len: usize) -> Option<i8> {
if token.is_empty() || token.len() > max_len || !token.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
token.parse().ok()
}
fn parse_year(token: &str) -> Option<i32> {
if !token.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
let value: i32 = token.parse().ok()?;
match token.len() {
2 => Some(value + if value > 68 { 1900 } else { 2000 }),
4 => Some(value),
_ => None,
}
}
fn refresh_requested(err: &Error) -> bool {
matches!(
err,
Error::Authentication { status: Some(401), error_code, .. }
if errors::classify_error_code(error_code.as_deref())
== Some(errors::ErrorGroup::SessionRefresh)
)
}
fn is_transient_failure(err: &Error) -> bool {
match err {
Error::Network(_) | Error::Timeout => true,
Error::RateLimit { .. } => false,
other => other.status().is_some_and(|status| status >= 500),
}
}
thread_local! {
#[cfg(test)]
static REDACTIONS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}
fn redacted_for_log(envelope: &Value) -> String {
#[cfg(test)]
REDACTIONS.with(|count| count.set(count.get() + 1));
redact::redact_sensitive(envelope).to_string()
}
fn map_reqwest_error(err: reqwest::Error) -> Error {
if err.is_timeout() {
Error::Timeout
} else {
Error::Network(err)
}
}
fn network_error_kind(err: &reqwest::Error) -> &'static str {
if err.is_timeout() {
"timeout"
} else if err.is_connect() {
"connect"
} else if err.is_redirect() {
"redirect"
} else if err.is_body() {
"body"
} else if err.is_decode() {
"decode"
} else if err.is_request() {
"request"
} else {
"other"
}
}
fn network_error_cause(err: &reqwest::Error) -> String {
let mut causes = Vec::new();
let mut source = std::error::Error::source(err);
while let Some(cause) = source {
causes.push(cause.to_string());
source = cause.source();
}
if causes.is_empty() {
format!("{} error", network_error_kind(err))
} else {
causes.join(": ")
}
}
fn log_transport_failure(method: &Method, url: &Url, error: &Error) {
match error {
Error::Timeout => {
tracing::error!(method = %method, "Request timed out on {method} request");
tracing::debug!(
method = %method,
path = url.path(),
"Request to {} timed out",
url.path()
);
}
Error::Network(err) => {
let kind = network_error_kind(err);
tracing::error!(method = %method, kind, "Network error ({kind}) on {method} request");
tracing::debug!(
method = %method,
path = url.path(),
"Network error: {} for URL: {}",
network_error_cause(err),
url.path()
);
}
_ => {}
}
}
fn log_api_error(method: &Method, status: StatusCode) {
let code = status.as_u16();
if status.is_success() || matches!(code, 401 | 404 | 429) {
return;
}
tracing::error!(status = code, method = %method, "API error {code} on {method} request");
}
const BASE_URL_UNPARSEABLE: &str = "has an authority that cannot be parsed";
const BASE_URL_USERINFO: &str = "must not carry userinfo";
const BASE_URL_NOT_ABSOLUTE: &str = "must be an absolute URL with a scheme and a host";
fn validate_base_url(raw: &str) -> Result<(), Error> {
let problem = |text: &'static str| Err(Error::validation("base_url", text));
let cleaned: String = raw
.trim_start_matches(|c: char| c <= ' ')
.chars()
.filter(|c| !matches!(c, '\t' | '\r' | '\n'))
.collect();
let netloc = python_netloc(&cleaned);
if netloc.is_some_and(|netloc| netloc.contains('\\')) {
return problem(BASE_URL_UNPARSEABLE);
}
let parsed = Url::parse(&cleaned);
if let Err(err) = &parsed
&& !matches!(
err,
url::ParseError::EmptyHost
| url::ParseError::RelativeUrlWithoutBase
| url::ParseError::RelativeUrlWithCannotBeABaseBase
| url::ParseError::SetHostOnCannotBeABaseUrl
)
{
return problem(BASE_URL_UNPARSEABLE);
}
let parsed_userinfo = parsed
.as_ref()
.is_ok_and(|url| !url.username().is_empty() || url.password().is_some());
if parsed_userinfo || netloc.is_some_and(|netloc| netloc.contains('@')) {
return problem(BASE_URL_USERINFO);
}
match parsed {
Ok(url)
if netloc.is_some_and(|netloc| !netloc.is_empty())
&& url.host_str().is_some()
&& !url.cannot_be_a_base()
&& url.origin().is_tuple() =>
{
Ok(())
}
_ => problem(BASE_URL_NOT_ABSOLUTE),
}
}
fn python_netloc(url: &str) -> Option<&str> {
let rest = match url.find(':') {
Some(i)
if i > 0
&& url.as_bytes()[0].is_ascii_alphabetic()
&& url.as_bytes()[..i]
.iter()
.all(|b| b.is_ascii_alphanumeric() || matches!(b, b'+' | b'-' | b'.')) =>
{
&url[i + 1..]
}
_ => url,
};
let authority = rest.strip_prefix("//")?;
let end = authority.find(['/', '?', '#']).unwrap_or(authority.len());
Some(&authority[..end])
}
fn parse_base(raw: &str) -> Result<Url, Error> {
let mut url =
Url::parse(raw).map_err(|_| Error::validation("base_url", BASE_URL_NOT_ABSOLUTE))?;
if url.path_segments_mut().is_err() {
return Err(Error::validation("base_url", BASE_URL_NOT_ABSOLUTE));
}
Ok(url)
}
fn validate_header_value(field: &str, value: &str) -> Result<(), Error> {
if value.bytes().all(|b| (0x20..=0x7E).contains(&b)) {
Ok(())
} else {
Err(Error::validation(
field,
"header value must be printable ASCII with no CR/LF",
))
}
}
#[derive(Debug)]
pub struct TransportBuilder {
http_builder: Option<reqwest::ClientBuilder>,
base_root: Option<String>,
user_agent: Option<String>,
accept_language: Option<String>,
send_legacy_cookie: bool,
get_retries: u32,
session: Option<Session>,
store: Option<Arc<dyn CredentialStore>>,
storage_failures: StorageFailures,
timeout: Duration,
read_timeout: Duration,
}
impl Default for TransportBuilder {
fn default() -> Self {
Self {
http_builder: None,
base_root: None,
user_agent: None,
accept_language: None,
send_legacy_cookie: true,
get_retries: 0,
session: None,
store: None,
storage_failures: StorageFailures::default(),
timeout: consts::REQUEST_TIMEOUT,
read_timeout: consts::READ_TIMEOUT,
}
}
}
impl TransportBuilder {
#[must_use]
pub fn http_builder(mut self, builder: reqwest::ClientBuilder) -> Self {
self.http_builder = Some(builder);
self
}
#[must_use]
pub fn base_url(mut self, base_url: impl Into<String>) -> Self {
self.base_root = Some(base_url.into());
self
}
#[must_use]
pub fn user_agent(mut self, user_agent: Option<String>) -> Self {
self.user_agent = user_agent;
self
}
#[must_use]
pub fn accept_language(mut self, accept_language: impl Into<String>) -> Self {
self.accept_language = Some(accept_language.into());
self
}
#[must_use]
pub fn send_legacy_cookie(mut self, send_legacy_cookie: bool) -> Self {
self.send_legacy_cookie = send_legacy_cookie;
self
}
#[must_use]
pub fn get_retries(mut self, get_retries: u32) -> Self {
self.get_retries = get_retries;
self
}
#[must_use]
pub fn session(mut self, session: Option<Session>) -> Self {
self.session = session;
self
}
#[must_use]
pub fn store(mut self, store: Option<Arc<dyn CredentialStore>>) -> Self {
self.store = store;
self
}
#[must_use]
pub fn storage_failures(mut self, storage_failures: StorageFailures) -> Self {
self.storage_failures = storage_failures;
self
}
#[must_use]
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
#[must_use]
pub fn read_timeout(mut self, read_timeout: Duration) -> Self {
self.read_timeout = read_timeout;
self
}
pub fn build(self) -> Result<Transport, Error> {
if let Some(root) = &self.base_root {
validate_base_url(root)?;
}
let (base_22, _base_23) = self.build_bases()?;
let api_host = {
let origin = base_22.origin().ascii_serialization();
Url::parse(&origin).map_err(|_| Error::validation("base_url", BASE_URL_NOT_ABSOLUTE))?
};
let accept_language = self
.accept_language
.unwrap_or_else(|| consts::DEFAULT_ACCEPT_LANGUAGE.to_owned());
validate_header_value("X-Accept-Language", &accept_language)?;
let user_agent = self
.user_agent
.unwrap_or_else(|| consts::DEFAULT_USER_AGENT.to_owned());
validate_header_value("User-Agent", &user_agent)?;
let (http, timeout) = if let Some(builder) = self.http_builder {
let http = builder
.redirect(Policy::none())
.build()
.map_err(Error::Network)?;
(http, RequestTimeout::default())
} else {
let http = Client::builder()
.redirect(Policy::none())
.build()
.map_err(Error::Network)?;
(
http,
RequestTimeout::new(Some(self.timeout), Some(self.read_timeout)),
)
};
Ok(Transport {
http,
api_host,
session: RwLock::new(self.session),
store: self.store,
persistence: Arc::new(Persistence::new()),
storage_failures: self.storage_failures,
user_agent,
accept_language,
send_legacy_cookie: self.send_legacy_cookie,
get_retries: self.get_retries,
timeout,
refresh_slot: tokio::sync::Mutex::new(Weak::new()),
})
}
fn build_bases(&self) -> Result<(Url, Url), Error> {
let (raw_22, raw_23) = match &self.base_root {
Some(root) => {
let trimmed = root.trim_end_matches('/');
(
format!("{trimmed}/{}", ApiVersion::V2_2.segment()),
format!("{trimmed}/{}", ApiVersion::V2_3.segment()),
)
}
None => (
consts::API_BASE_22.to_owned(),
consts::API_BASE_23.to_owned(),
),
};
Ok((parse_base(&raw_22)?, parse_base(&raw_23)?))
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use reqwest::header::{HeaderMap, HeaderValue, RETRY_AFTER};
use url::Url;
use super::{
REDACTIONS, RequestTimeout, Transport, is_transient_failure, parse_retry_after,
parse_retry_after_at, refresh_requested, reject_userinfo, status_to_envelope,
validate_header_value, withheld_message,
};
use crate::error::Error;
use crate::routes::{ACCOUNT, ApiVersion, Resource};
#[test]
fn retry_after_parses_delta_seconds_form() {
let mut headers = HeaderMap::new();
headers.insert(RETRY_AFTER, HeaderValue::from_static("120"));
assert_eq!(parse_retry_after(&headers), Some(Duration::from_secs(120)));
}
#[test]
fn retry_after_parses_delta_seconds_form_with_surrounding_whitespace() {
let mut headers = HeaderMap::new();
headers.insert(RETRY_AFTER, HeaderValue::from_static(" 30 "));
assert_eq!(parse_retry_after(&headers), Some(Duration::from_secs(30)));
}
#[test]
fn retry_after_parses_http_date_form_in_the_future() {
let mut headers = HeaderMap::new();
headers.insert(
RETRY_AFTER,
HeaderValue::from_static("Thu, 01 Jan 2099 00:00:00 GMT"),
);
let parsed = parse_retry_after(&headers).expect("valid HTTP-date form parses");
assert!(parsed > Duration::from_secs(0));
}
#[test]
fn retry_after_http_date_in_the_past_is_zero_not_none() {
let mut headers = HeaderMap::new();
headers.insert(
RETRY_AFTER,
HeaderValue::from_static("Wed, 01 Jan 2003 00:00:00 GMT"),
);
assert_eq!(parse_retry_after(&headers), Some(Duration::ZERO));
}
#[test]
fn retry_after_absent_header_is_none() {
let headers = HeaderMap::new();
assert_eq!(parse_retry_after(&headers), None);
}
#[test]
fn retry_after_garbage_value_is_none_not_an_error() {
let mut headers = HeaderMap::new();
headers.insert(
RETRY_AFTER,
HeaderValue::from_static("not a retry-after value"),
);
assert_eq!(parse_retry_after(&headers), None);
}
#[test]
fn retry_after_negative_number_is_none() {
let mut headers = HeaderMap::new();
headers.insert(RETRY_AFTER, HeaderValue::from_static("-5"));
assert_eq!(parse_retry_after(&headers), None);
}
fn now() -> jiff::civil::DateTime {
jiff::civil::datetime(2026, 10, 22, 12, 0, 0, 0)
}
fn at(raw: &str) -> Option<Duration> {
parse_retry_after_at(raw, now())
}
#[test]
fn retry_after_delta_seconds_are_ascii_digits_only() {
assert_eq!(at("0"), Some(Duration::ZERO));
assert_eq!(at("120"), Some(Duration::from_secs(120)));
assert_eq!(at(" 45 "), Some(Duration::from_secs(45)));
assert_eq!(at("\t45\t"), Some(Duration::from_secs(45)));
assert_eq!(at("007"), Some(Duration::from_secs(7)));
for bad in [
"+5",
"-5",
"1.5",
"1e3",
"12 seconds",
"",
" ",
"soon",
"\u{663}",
] {
assert_eq!(at(bad), None, "{bad:?}");
}
}
#[test]
fn retry_after_is_capped_at_one_day() {
let cap = Some(crate::consts::RETRY_AFTER_MAX);
assert_eq!(cap, Some(Duration::from_hours(24)));
assert_eq!(at("86400"), cap);
assert_eq!(at("86399"), Some(Duration::from_secs(86_399)));
assert_eq!(at("86401"), cap);
assert_eq!(at("9999999999"), cap);
assert_eq!(at(&"9".repeat(400)), cap);
assert_eq!(at("Mon, 10 Jan 2059 01:46:40 GMT"), cap);
assert_eq!(at("Fri, 31 Dec 9999 23:59:59 GMT"), cap);
}
#[test]
fn retry_after_reads_all_three_http_date_forms_as_utc() {
let minute = Some(Duration::from_secs(60));
assert_eq!(at("Thu, 22 Oct 2026 12:01:00 GMT"), minute);
assert_eq!(at("Thursday, 22-Oct-26 12:01:00 GMT"), minute);
assert_eq!(at("Thu Oct 22 12:01:00 2026"), minute);
assert_eq!(at("Mon, 22 Oct 2026 12:01:00 GMT"), minute);
assert_eq!(at("22 OCT 2026 12:01:00 GMT"), minute);
assert_eq!(at("Fri, 22 oct 2026 12:01:00 gmt"), minute);
assert_eq!(
parse_retry_after_at(
"Sun Nov 1 12:00:30 2026",
jiff::civil::datetime(2026, 11, 1, 6, 0, 0, 0)
),
Some(Duration::from_secs(6 * 3600 + 30)),
);
assert_eq!(at("Sunday, 06-Nov-94 08:49:37 GMT"), Some(Duration::ZERO));
assert_eq!(
at("Tuesday, 22-Oct-30 12:00:01 GMT"),
Some(crate::consts::RETRY_AFTER_MAX),
"22-Oct-30 is 2030, years away, so the cap"
);
}
#[test]
fn retry_after_http_date_in_the_past_is_zero() {
assert_eq!(at("Wed, 01 Jan 2003 00:00:00 GMT"), Some(Duration::ZERO));
assert_eq!(at("Thu, 22 Oct 2026 11:59:59 GMT"), Some(Duration::ZERO));
assert_eq!(at("Thu, 22 Oct 2026 12:00:00 GMT"), Some(Duration::ZERO));
}
#[test]
fn retry_after_impossible_or_malformed_dates_are_none() {
for bad in [
"Mon, 99 Foo 2999 99:99:99 GMT",
"Wed, 01 Jan 99999 00:00:00 GMT",
"Thu, 30 Feb 2026 12:00:00 GMT",
"Thu, 22 Oct 2026 24:00:00 GMT",
"Thu, 22 Oct 2026 12:00:60 GMT",
"Thu, 22 Oct 0000 12:00:00 GMT",
"Thu, 22 Oct 2026 12:00 GMT",
"Thu, 22 Oct 2026 12:00:00 PST",
"Thu, 22 Oct 2026 12:00:00",
"Thursday, 22-Oct-2026-1 12:00:00 GMT",
"Thu, 22 Oct 202 12:00:00 GMT",
"Thu 22 Oct 2026",
] {
assert_eq!(at(bad), None, "{bad:?}");
}
}
#[test]
fn retry_after_ignores_non_visible_ascii_header_values() {
let mut headers = HeaderMap::new();
headers.insert(
RETRY_AFTER,
HeaderValue::from_bytes("\u{663}".as_bytes()).unwrap(),
);
assert_eq!(parse_retry_after(&headers), None);
}
fn refresh_requested_for(body: &str) -> bool {
let url = Url::parse("http://mock.test:1234/2.2/account").unwrap();
status_to_envelope(reqwest::StatusCode::UNAUTHORIZED, body, &url, None)
.err()
.as_ref()
.is_some_and(refresh_requested)
}
#[test]
fn refresh_signal_detected_on_exact_match() {
assert!(refresh_requested_for(
r#"{"meta":{"code":401,"error":"error.session.refresh"}}"#
));
}
#[test]
fn refresh_signal_not_detected_on_a_different_error_value() {
assert!(!refresh_requested_for(
r#"{"meta":{"code":401,"error":"invalid_credentials"}}"#
));
}
#[test]
fn refresh_signal_not_detected_when_meta_is_absent() {
assert!(!refresh_requested_for(r#"{"data":{}}"#));
}
#[test]
fn refresh_signal_not_detected_on_invalid_json() {
assert!(!refresh_requested_for("not json at all"));
}
#[test]
fn refresh_signal_needs_a_401() {
let url = Url::parse("http://mock.test:1234/2.2/account").unwrap();
let body = r#"{"meta":{"code":403,"error":"error.session.refresh"}}"#;
let err = status_to_envelope(reqwest::StatusCode::FORBIDDEN, body, &url, None)
.expect_err("a 403");
assert!(!refresh_requested(&err));
}
#[test]
fn only_server_side_failures_are_transient() {
let url = Url::parse("http://mock.test:1234/2.2/account").unwrap();
let classify = |status: u16, body: &str| {
status_to_envelope(
reqwest::StatusCode::from_u16(status).unwrap(),
body,
&url,
None,
)
.expect_err("an error status")
};
let rate_limited = r#"{"meta":{"code":503,"error":"error.rate.limit"}}"#;
let premium = r#"{"meta":{"code":503,"error":"error.premium.user_not_subscribed"}}"#;
for (status, body, transient) in [
(500, "", true),
(502, "garbage", true),
(503, r#"{"meta":{"code":503}}"#, true),
(599, "", true),
(503, premium, true),
(429, "", false),
(503, rate_limited, false),
(500, rate_limited, false),
(400, "", false),
(401, "", false),
(403, "", false),
(404, "", false),
(409, "", false),
] {
let err = classify(status, body);
assert_eq!(
is_transient_failure(&err),
transient,
"{status} {body}: {err:?}"
);
}
assert!(is_transient_failure(&Error::Timeout));
assert!(!is_transient_failure(&Error::validation(
"field", "message"
)));
assert!(!is_transient_failure(&Error::authentication(
"Not authenticated"
)));
}
fn redactions_at(level: tracing::Level) -> usize {
const BODY: &str =
r#"{"meta":{"code":400,"error":"error.request.invalid"},"data":{"token":"x"}}"#;
let url = Url::parse("http://mock.test:1234/2.2/account").unwrap();
let subscriber = tracing_subscriber::fmt()
.with_max_level(level)
.with_writer(std::io::sink)
.finish();
crate::storage::test_support::register_anchor_dispatcher();
REDACTIONS.with(|count| count.set(0));
tracing::subscriber::with_default(subscriber, || {
let _ = status_to_envelope(reqwest::StatusCode::BAD_REQUEST, BODY, &url, None);
});
REDACTIONS.with(std::cell::Cell::get)
}
#[test]
fn a_disabled_debug_level_never_invokes_the_redactor() {
assert_eq!(redactions_at(tracing::Level::WARN), 0);
assert_eq!(redactions_at(tracing::Level::DEBUG), 1);
}
#[test]
fn validate_header_value_accepts_empty() {
validate_header_value("x", "").expect("empty header value matches the `*` rule");
}
#[test]
fn validate_header_value_rejects_crlf() {
let err = validate_header_value("x", "a\r\nb").unwrap_err();
assert!(matches!(err, Error::Validation { field, .. } if field == "x"));
}
#[test]
fn validate_header_value_accepts_printable_ascii() {
validate_header_value("x", "eero/3.0 (iPhone; iOS 17.0)").expect("printable ascii ok");
}
#[test]
fn request_timeout_default_is_unbounded_on_both_axes() {
let timeout = RequestTimeout::default();
assert_eq!(timeout.total, None);
assert_eq!(timeout.read, None);
}
#[test]
fn request_timeout_constructors_set_the_documented_fields() {
let both = RequestTimeout::new(Some(Duration::from_secs(5)), Some(Duration::from_secs(2)));
assert_eq!(both.total, Some(Duration::from_secs(5)));
assert_eq!(both.read, Some(Duration::from_secs(2)));
let total_only = RequestTimeout::total(Duration::from_secs(120));
assert_eq!(total_only.total, Some(Duration::from_secs(120)));
assert_eq!(total_only.read, None, "total() leaves the read bound unset");
}
#[test]
fn bounds_default_to_the_builder_timeouts_when_no_per_call_value_is_supplied() {
let transport = Transport::builder().build().expect("builds with defaults");
let bounds = transport.bounds_for(None);
assert_eq!(bounds.total, Some(crate::consts::REQUEST_TIMEOUT));
assert_eq!(bounds.read, Some(crate::consts::READ_TIMEOUT));
assert!(!bounds.per_call);
}
#[test]
fn a_per_call_value_replaces_the_default_wholesale() {
let transport = Transport::builder().build().expect("builds with defaults");
let bounds = transport.bounds_for(Some(RequestTimeout::total(Duration::from_secs(120))));
assert_eq!(bounds.total, Some(Duration::from_secs(120)));
assert_eq!(
bounds.read, None,
"the default read bound must not leak back in"
);
assert!(bounds.per_call);
let bounds = transport.bounds_for(Some(RequestTimeout::default()));
assert_eq!((bounds.total, bounds.read), (None, None));
}
#[test]
fn zero_durations_mean_unbounded_for_defaults_and_per_call_values() {
let transport = Transport::builder()
.timeout(Duration::ZERO)
.read_timeout(Duration::ZERO)
.build()
.expect("builds with zero defaults");
let bounds = transport.bounds_for(None);
assert_eq!((bounds.total, bounds.read), (None, None));
let bounds = transport.bounds_for(Some(RequestTimeout::new(
Some(Duration::ZERO),
Some(Duration::from_secs(1)),
)));
assert_eq!(bounds.total, None);
assert_eq!(bounds.read, Some(Duration::from_secs(1)));
}
#[test]
fn a_caller_supplied_http_builder_leaves_the_default_unbounded() {
let transport = Transport::builder()
.http_builder(reqwest::Client::builder())
.timeout(Duration::from_secs(1))
.read_timeout(Duration::from_secs(1))
.build()
.expect("builds with a caller-supplied builder");
let bounds = transport.bounds_for(None);
assert_eq!((bounds.total, bounds.read), (None, None));
}
fn v2_3_resource() -> Resource {
Resource {
method: reqwest::Method::PUT,
version: ApiVersion::V2_3,
template: "networks/{id}/devices",
link: None,
}
}
#[test]
fn default_bases_resolve_against_the_real_eero_host() {
let transport = Transport::builder().build().expect("builds with defaults");
let url = ACCOUNT
.resolve(transport.api_host(), "", None)
.expect("a fixed path always resolves");
assert_eq!(url.as_str(), "https://api-user.e2ro.com/2.2/account");
}
#[test]
fn overridden_base_url_is_used_for_both_api_versions() {
let transport = Transport::builder()
.base_url("http://127.0.0.1:9999")
.build()
.expect("builds with an overridden base");
let v22 = ACCOUNT
.resolve(transport.api_host(), "", None)
.expect("v2.2 resource resolves");
assert_eq!(v22.as_str(), "http://127.0.0.1:9999/2.2/account");
let resource = v2_3_resource();
let v23 = resource
.resolve(transport.api_host(), "123", None)
.expect("v2.3 resource resolves");
assert_eq!(
v23.as_str(),
"http://127.0.0.1:9999/2.3/networks/123/devices"
);
}
#[test]
fn api_host_has_no_path_and_reflects_the_override() {
let transport = Transport::builder()
.base_url("http://127.0.0.1:9999")
.build()
.expect("builds with an overridden base");
assert_eq!(transport.api_host().as_str(), "http://127.0.0.1:9999/");
assert_eq!(transport.api_host().path(), "/");
}
#[test]
fn api_host_defaults_to_the_real_eero_host() {
let transport = Transport::builder().build().expect("builds with defaults");
assert_eq!(transport.api_host().host_str(), Some("api-user.e2ro.com"));
assert_eq!(transport.api_host().scheme(), "https");
}
#[test]
fn overridden_base_url_trailing_slash_is_not_doubled() {
let transport = Transport::builder()
.base_url("http://127.0.0.1:9999/")
.build()
.expect("builds with a trailing-slash base");
let url = ACCOUNT
.resolve(transport.api_host(), "", None)
.expect("resource resolves");
assert_eq!(url.as_str(), "http://127.0.0.1:9999/2.2/account");
}
#[test]
fn invalid_base_url_is_rejected_at_build_time() {
let err = Transport::builder()
.base_url("not a url")
.build()
.expect_err("malformed base URL must fail fast");
assert!(matches!(err, Error::Validation { field, .. } if field == "base_url"));
}
#[test]
fn no_session_means_not_authenticated_and_no_snapshot() {
let transport = Transport::builder().build().expect("builds with defaults");
assert!(!transport.is_authenticated());
assert!(transport.session().is_none());
}
#[test]
fn set_session_updates_the_snapshot_and_authentication_state() {
let transport = Transport::builder().build().expect("builds with defaults");
transport
.set_session(Some(crate::auth::Session::from_token("tok-123")))
.expect("no store configured, cannot fail");
assert!(transport.is_authenticated());
assert!(transport.session().is_some());
transport
.set_session(None)
.expect("clearing with no store cannot fail");
assert!(!transport.is_authenticated());
assert!(transport.session().is_none());
}
#[test]
fn set_session_rejects_an_empty_token() {
let transport = Transport::builder().build().expect("builds with defaults");
let err = transport
.set_session(Some(crate::auth::Session::from_token("")))
.expect_err("an empty token must be rejected");
assert!(matches!(err, Error::Validation { field, .. } if field == "token"));
assert!(!transport.is_authenticated());
}
#[test]
fn set_session_rejects_a_token_with_a_control_character() {
let transport = Transport::builder().build().expect("builds with defaults");
let err = transport
.set_session(Some(crate::auth::Session::from_token("tok\r\nX-Evil: 1")))
.expect_err("a control character in the token must be rejected");
assert!(matches!(err, Error::Validation { field, .. } if field == "token"));
}
#[derive(Debug)]
struct AcceptingStore;
impl crate::storage::CredentialStore for AcceptingStore {
fn load(&self) -> Result<crate::auth::Session, crate::error::StorageError> {
Ok(crate::auth::Session::empty())
}
fn save(&self, _: &crate::auth::Session) -> Result<(), crate::error::StorageError> {
Ok(())
}
fn clear(&self) -> Result<(), crate::error::StorageError> {
Ok(())
}
}
#[test]
fn a_save_cancelled_before_it_reaches_the_store_is_not_persisted() {
let pool = tokio::runtime::Builder::new_current_thread()
.build()
.expect("builds the blocking pool's runtime");
let driver = tokio::runtime::Builder::new_current_thread()
.build()
.expect("builds the runtime that polls the caller");
let transport = Transport::builder()
.store(Some(std::sync::Arc::new(AcceptingStore)))
.build()
.expect("builds");
assert!(transport.credentials_persisted());
let handle = pool.handle().clone();
pool.shutdown_background();
driver.block_on(async {
let _enter = handle.enter();
transport
.set_session_async(Some(crate::auth::Session::from_token("tok-123")))
.await
.expect("the Warn policy swallows the failure");
});
assert!(
!transport.credentials_persisted(),
"a save that never reached the store did not persist"
);
assert!(
transport.is_authenticated(),
"the in-memory session is unaffected"
);
}
fn transport_for_base(base: &str) -> Transport {
Transport::builder()
.base_url(base)
.build()
.expect("builds with an overridden base")
}
fn mismatch_reason(transport: &Transport, raw: &str) -> Option<&'static str> {
transport
.origin_mismatch(&Url::parse(raw).unwrap())
.map(|mismatch| mismatch.reason)
}
#[test]
fn the_gate_accepts_the_configured_scheme_host_and_port() {
let transport = transport_for_base("http://mock.test:9999");
assert_eq!(
mismatch_reason(&transport, "http://mock.test:9999/2.2/account"),
None
);
assert_eq!(
mismatch_reason(&transport, "HTTP://MOCK.TEST:9999/2.2/account"),
None
);
}
#[test]
fn the_gate_names_the_first_failing_check() {
let transport = transport_for_base("http://mock.test:9999");
for (raw, reason) in [
("http://evil.example:9999/x", "foreign host"),
("http://mock.test.evil.example:9999/x", "foreign host"),
("https://mock.test:9999/x", "non-matching scheme"),
("http://mock.test:8888/x", "non-matching port"),
("http://mock.test/x", "non-matching port"),
("http://user:pass@mock.test:9999/x", "URL with userinfo"),
("http://mock.test@evil.example:9999/x", "URL with userinfo"),
] {
assert_eq!(mismatch_reason(&transport, raw), Some(reason), "{raw}");
}
}
#[test]
fn the_gate_treats_an_explicit_default_port_as_none() {
let https = transport_for_base("https://mock.test");
for raw in [
"https://mock.test:443/2.2/account",
"https://mock.test:/x",
"https://mock.test/x",
] {
assert_eq!(mismatch_reason(&https, raw), None, "{raw}");
}
assert_eq!(
mismatch_reason(&https, "https://mock.test:0/x"),
Some("non-matching port")
);
assert_eq!(
mismatch_reason(&https, "https://mock.test:80/x"),
Some("non-matching port")
);
let explicit = transport_for_base("https://mock.test:443");
assert_eq!(mismatch_reason(&explicit, "https://mock.test/x"), None);
let http = transport_for_base("http://mock.test");
assert_eq!(mismatch_reason(&http, "http://mock.test:80/x"), None);
assert_eq!(
mismatch_reason(&http, "http://mock.test:443/x"),
Some("non-matching port")
);
let other_port = transport_for_base("https://mock.test:8443");
assert_eq!(
mismatch_reason(&other_port, "https://mock.test/x"),
Some("non-matching port")
);
assert_eq!(
mismatch_reason(&other_port, "https://mock.test:8443/x"),
None
);
}
#[test]
fn withheld_message_follows_python_without_the_url() {
let transport = transport_for_base("https://mock.test");
let message = |raw: &str| {
withheld_message(
&transport
.origin_mismatch(&Url::parse(raw).unwrap())
.unwrap(),
)
};
assert_eq!(
message("https://mock.test:8443/endpoint?token=secret"),
"Session header withheld from a request to a non-matching port: https://mock.test"
);
assert_eq!(
message("http://mock.test/endpoint"),
"Session header withheld from a request to a non-matching scheme: http://mock.test"
);
assert_eq!(
message("https://other.test/endpoint"),
"Session header withheld from a request to a foreign host: https://other.test"
);
let userinfo = message("https://user:pass@mock.test:8443/endpoint");
assert_eq!(
userinfo,
"Session header withheld from a request with URL with userinfo"
);
assert!(!userinfo.contains("pass") && !userinfo.contains("user:"));
}
#[test]
fn urls_the_parser_rejects_never_reach_the_gate() {
for raw in [
"http://127.0.0.1:abc/x",
"http://127.0.0.1:99999/x",
"http://[::1/x",
"https://mock.test\u{ff1a}99/x",
] {
assert!(Url::parse(raw).is_err(), "{raw}");
}
}
#[test]
fn userinfo_is_rejected_before_a_request() {
for raw in [
"http://user:pass@mock.test/x",
"http://user@mock.test/x",
"http://:pass@mock.test/x",
] {
let err = reject_userinfo(&Url::parse(raw).unwrap()).expect_err(raw);
assert!(
matches!(&err, Error::Validation { field, message, .. }
if field == "url" && message == "must not carry userinfo"),
"{raw}: {err:?}"
);
assert!(!err.to_string().contains("pass"));
}
reject_userinfo(&Url::parse("http://@mock.test/x").unwrap()).expect("no userinfo remains");
}
fn base_url_problem(raw: &str) -> String {
match Transport::builder().base_url(raw).build() {
Err(Error::Validation { field, message, .. }) => {
assert_eq!(field, "base_url", "{raw}");
assert!(!message.contains(raw) || raw.is_empty(), "{raw}: {message}");
message
}
Err(other) => panic!("{raw}: unexpected {other:?}"),
Ok(_) => panic!("{raw}: unexpectedly built"),
}
}
#[test]
fn base_url_with_userinfo_is_rejected_at_build_time() {
for raw in [
"https://user:pass@api.example.com",
"https://api.example.com@evil.example",
"https://@api.example.com",
"https://user@",
"https://user:pass@api.example.com:8443/2.2",
] {
let message = base_url_problem(raw);
assert_eq!(message, "must not carry userinfo", "{raw}");
assert!(!message.contains("pass"));
}
}
#[test]
fn base_url_with_unparseable_authority_is_rejected_at_build_time() {
for raw in [
"https://api.example.com:abc",
"https://api.example.com:99999",
"https://api.example.com\\@evil.example",
"https://api.example.com\u{ff1a}99",
"https://[::1",
"https://user:pass@api.example.com:abc",
] {
assert_eq!(
base_url_problem(raw),
"has an authority that cannot be parsed",
"{raw}"
);
}
}
#[test]
fn base_url_without_scheme_or_host_is_rejected_at_build_time() {
for raw in [
"",
"not a url",
"api.example.com",
"api.example.com:8080",
"//api.example.com",
"/2.2",
"https://",
"https:///2.2",
"https:api.example.com",
"https:/api.example.com",
"https:\\\\api.example.com",
"mailto:someone",
"foo://api.example.com",
] {
assert_eq!(
base_url_problem(raw),
"must be an absolute URL with a scheme and a host",
"{raw:?}"
);
}
}
#[test]
fn usable_base_urls_still_build() {
for (raw, api_host) in [
("https://api.example.com", "https://api.example.com/"),
(
"https://api.example.com:8443",
"https://api.example.com:8443/",
),
(
"HTTPS://API.Example.COM:443/2.2",
"https://api.example.com/",
),
("http://127.0.0.1:8080", "http://127.0.0.1:8080/"),
("http://127.0.0.1:8080/", "http://127.0.0.1:8080/"),
("http://[::1]:8080", "http://[::1]:8080/"),
] {
let transport = Transport::builder().base_url(raw).build().expect(raw);
assert_eq!(transport.api_host().as_str(), api_host, "{raw}");
}
let transport = transport_for_base("https://api.example.com:8443");
assert_eq!(
mismatch_reason(&transport, "https://api.example.com/x"),
Some("non-matching port")
);
}
#[test]
fn the_default_base_still_builds_without_an_override() {
let transport = Transport::builder().build().expect("the real hosts");
assert_eq!(transport.api_host().as_str(), "https://api-user.e2ro.com/");
}
#[test]
fn python_netloc_follows_urlsplit() {
for (raw, netloc) in [
("https://host/path", Some("host")),
("https://host?x#y", Some("host")),
("https://user@host:1/", Some("user@host:1")),
("//host/x", Some("host")),
("https://", Some("")),
("https:host", None),
("https:/host", None),
("host", None),
("host:8080", None),
("", None),
] {
assert_eq!(super::python_netloc(raw), netloc, "{raw:?}");
}
}
}