pub mod api_key;
pub mod authorization_code;
pub mod device_code;
use std::time::Duration;
use std::time::SystemTime;
use std::time::UNIX_EPOCH;
use serde::Deserialize;
use crate::credentials::Credential;
use crate::error::Error;
use crate::error::Result;
pub const DEFAULT_USER_AGENT: &str = concat!("oauthkit/", env!("CARGO_PKG_VERSION"));
const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
#[derive(Deserialize)]
pub(crate) struct TokenResponse {
pub access_token: String,
#[serde(default)]
pub refresh_token: Option<String>,
#[serde(default)]
pub expires_in: Option<i64>,
pub token_type: String,
}
impl std::fmt::Debug for TokenResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TokenResponse")
.field("access_token", &"<redacted>")
.field(
"refresh_token",
&self.refresh_token.as_ref().map(|_| "<redacted>"),
)
.field("expires_in", &self.expires_in)
.field("token_type", &self.token_type)
.finish()
}
}
#[derive(Debug, Deserialize)]
pub(crate) struct TokenErrorResponse {
pub error: String,
#[serde(default)]
pub error_description: Option<String>,
}
pub fn http_client() -> Result<reqwest::Client> {
http_client_with_user_agent(DEFAULT_USER_AGENT)
}
pub fn http_client_with_user_agent(user_agent: &str) -> Result<reqwest::Client> {
reqwest::Client::builder()
.user_agent(user_agent)
.timeout(DEFAULT_TIMEOUT)
.connect_timeout(DEFAULT_CONNECT_TIMEOUT)
.build()
.map_err(Error::from)
}
pub(crate) fn expiry_from_expires_in(expires_in: Option<i64>) -> Option<i64> {
let expires_in = expires_in?;
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
Some(now.saturating_add(expires_in))
}
pub(crate) fn oauth_error_detail(body: &str) -> Option<String> {
serde_json::from_str::<TokenErrorResponse>(body)
.ok()
.map(|err| match err.error_description {
Some(desc) => format!("{}: {desc}", err.error),
None => err.error,
})
}
#[tracing::instrument(level = "debug", skip_all, fields(provider = %provider, token_url = %token_url))]
pub(crate) async fn post_token_form(
client: &reqwest::Client,
provider: &str,
token_url: &str,
form: &[(&str, &str)],
) -> Result<Credential> {
tracing::debug!("posting token form to endpoint");
let response = client
.post(token_url)
.header(reqwest::header::ACCEPT, "application/json")
.form(form)
.send()
.await?;
let status = response.status();
let body = response.text().await?;
if !status.is_success() {
if let Some(detail) = oauth_error_detail(&body) {
tracing::warn!(status = %status, error = %detail, "token endpoint returned an OAuth error");
return Err(Error::Authorization(detail));
}
tracing::warn!(status = %status, "token endpoint returned a non-success status");
return Err(Error::Authorization(format!("HTTP {status}")));
}
let token: TokenResponse = match serde_json::from_str(&body) {
Ok(t) => t,
Err(e) => {
if let Some(detail) = oauth_error_detail(&body) {
tracing::warn!(status = %status, error = %detail, "token endpoint returned an OAuth error with 200 status");
return Err(Error::Authorization(detail));
}
tracing::warn!("token response was not valid JSON");
return Err(Error::Malformed(format!("token response was not valid JSON: {e}")));
}
};
if token.access_token.trim().is_empty() {
return Err(Error::Malformed(
"token response contained an empty access_token".to_string(),
));
}
if token.token_type.trim().is_empty() {
return Err(Error::Malformed(
"token response contained an empty token_type".to_string(),
));
}
let refresh_token = token
.refresh_token
.filter(|t| !t.trim().is_empty());
tracing::debug!(
has_refresh = refresh_token.is_some(),
has_expiry = token.expires_in.is_some(),
"token exchange succeeded"
);
Ok(Credential::oauth(
provider.to_string(),
token.access_token,
refresh_token,
expiry_from_expires_in(token.expires_in),
Some(token.token_type),
))
}
#[tracing::instrument(level = "debug", skip_all, fields(provider = %provider, client_id = %client_id))]
pub async fn refresh(
provider: &str,
token_url: &str,
client_id: &str,
refresh_token: &str,
) -> Result<Credential> {
tracing::debug!("refreshing access token");
let client = http_client()?;
let form = [
("grant_type", "refresh_token"),
("refresh_token", refresh_token),
("client_id", client_id),
];
post_token_form(&client, provider, token_url, &form).await
}