use std::time::{Duration, Instant};
use crate::auth::{Refreshed, TokenRefresher};
use crate::error::Error;
use crate::net::{ReadError, read_capped, redact_ureq_error};
use crate::redaction::body_preview;
pub const REFRESH_TIMEOUT: Duration = Duration::from_secs(8);
const TOKEN_URL: &str = "https://fleet-auth.prd.vn.cloud.tesla.com/oauth2/v3/token";
use super::MSG_MAX;
#[derive(serde::Deserialize)]
struct TokenResponse {
access_token: String,
refresh_token: String,
#[serde(default)]
expires_in: u64,
}
pub struct HttpRefresher {
agent: ureq::Agent,
client_id: String,
token_url: crate::Url,
timeout: Duration,
}
impl HttpRefresher {
pub fn new(client_id: String) -> Self {
Self {
agent: crate::net::agent(REFRESH_TIMEOUT),
client_id,
token_url: TOKEN_URL.parse().expect("const URL parses"),
timeout: REFRESH_TIMEOUT,
}
}
pub fn with_token_url(mut self, url: crate::Url) -> Self {
self.token_url = url;
self
}
pub fn with_timeout(mut self, d: Duration) -> Self {
self.timeout = d;
self.agent = crate::net::agent(d);
self
}
}
impl core::fmt::Debug for HttpRefresher {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("HttpRefresher")
.field("token_url", &self.token_url.as_str())
.field("timeout", &self.timeout)
.finish_non_exhaustive()
}
}
impl TokenRefresher for HttpRefresher {
fn refresh(&self, refresh_token: &str) -> Result<Refreshed, Error> {
let form = [
("grant_type", "refresh_token"),
("client_id", self.client_id.as_str()),
("refresh_token", refresh_token),
];
let deadline = Instant::now()
.checked_add(self.timeout)
.unwrap_or_else(Instant::now);
#[allow(clippy::disallowed_methods)]
let sent = self.agent.post(self.token_url.as_str()).send_form(form);
let timed_out = || Error::Auth {
message: body_preview("token refresh timed out", MSG_MAX),
pricing: None,
};
let mut resp = match sent {
Ok(r) => r,
Err(ureq::Error::Timeout(_)) => return Err(timed_out()),
Err(e) => {
return Err(Error::Auth {
message: body_preview(&redact_ureq_error(&e), MSG_MAX),
pricing: None,
});
}
};
let status = resp.status();
let body = match read_capped(
&mut resp.body_mut().as_reader(),
crate::transport::MAX_RESPONSE_BYTES,
deadline,
) {
Ok(body) => body,
Err(ReadError::Deadline) => return Err(timed_out()),
Err(ReadError::CapExceeded) => {
return Err(Error::Auth {
message: body_preview(
&format!(
"token refresh response too large (cap {} bytes)",
crate::transport::MAX_RESPONSE_BYTES
),
MSG_MAX,
),
pricing: None,
});
}
Err(ReadError::Io(e)) => {
return Err(Error::Auth {
message: body_preview(&crate::redaction::redact_transport_error(&e), MSG_MAX),
pricing: None,
});
}
};
if !status.is_success() {
return Err(Error::Auth {
message: body_preview(
&format!(
"token refresh failed: HTTP {status}: {}",
String::from_utf8_lossy(&body)
),
MSG_MAX,
),
pricing: None,
});
}
let parsed: TokenResponse = serde_json::from_slice(&body).map_err(|e| Error::Auth {
message: body_preview(&format!("token refresh response: {e}"), MSG_MAX),
pricing: None,
})?;
Ok(Refreshed::new(
parsed.access_token,
parsed.refresh_token,
parsed.expires_in,
))
}
}
#[cfg(test)]
mod tests;