use std::future::Future;
use std::time::Duration;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use crate::client::{Client, with_retry};
use crate::error::{Error, ErrorKind, kind_for_status};
use crate::transport::Answer;
const METADATA_PATH: &str = "/.well-known/oauth-authorization-server";
const DEVICE_AUTHORIZATION_PATH: &str = "/oauth/device_authorization";
const TOKEN_PATH: &str = "/oauth/token";
const REVOKE_PATH: &str = "/oauth/revoke";
const DEVICE_CODE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";
const DEFAULT_POLL_INTERVAL: i64 = 5;
const SLOW_DOWN_STEP: i64 = 5;
#[derive(Debug, Clone, Copy)]
pub struct OauthApi<'a> {
client: &'a Client,
}
impl<'a> OauthApi<'a> {
pub(crate) fn new(client: &'a Client) -> Self {
Self { client }
}
pub async fn metadata(&self) -> Result<OauthMetadata, OauthError> {
self.metadata_with(OauthOptions::new()).await
}
pub async fn metadata_with(&self, opts: OauthOptions) -> Result<OauthMetadata, OauthError> {
let timeout = self.timeout(opts.timeout)?;
with_retry(self.client.retries(), || async move {
decode(self.client.transport().get_keyless(METADATA_PATH, timeout).await?)
})
.await
}
pub async fn device_authorization(
&self,
client_id: &str,
) -> Result<DeviceAuthorization, OauthError> {
self.device_authorization_with(client_id, DeviceAuthorizationOptions::new()).await
}
pub async fn device_authorization_with(
&self,
client_id: &str,
opts: DeviceAuthorizationOptions,
) -> Result<DeviceAuthorization, OauthError> {
let mut form = vec![("client_id", client_id)];
if let Some(scope) = opts.scope.as_deref().filter(|s| !s.is_empty()) {
form.push(("scope", scope));
}
if let Some(resource) = opts.resource.as_deref().filter(|r| !r.is_empty()) {
form.push(("resource", resource));
}
let timeout = self.timeout(opts.timeout)?;
let form = &form;
with_retry(self.client.retries(), || async move {
let answer =
self.client.transport().post_form(DEVICE_AUTHORIZATION_PATH, form, timeout).await?;
decode(answer)
})
.await
}
pub async fn exchange_device_code(
&self,
client_id: &str,
device_code: &str,
) -> Result<TokenResponse, OauthError> {
self.exchange_device_code_with(client_id, device_code, OauthOptions::new()).await
}
pub async fn exchange_device_code_with(
&self,
client_id: &str,
device_code: &str,
opts: OauthOptions,
) -> Result<TokenResponse, OauthError> {
let form = [
("grant_type", DEVICE_CODE_GRANT),
("device_code", device_code),
("client_id", client_id),
];
self.exchange(&form, opts).await
}
pub async fn exchange_refresh_token(
&self,
client_id: &str,
refresh_token: &str,
) -> Result<TokenResponse, OauthError> {
self.exchange_refresh_token_with(client_id, refresh_token, OauthOptions::new()).await
}
pub async fn exchange_refresh_token_with(
&self,
client_id: &str,
refresh_token: &str,
opts: OauthOptions,
) -> Result<TokenResponse, OauthError> {
let form = [
("grant_type", "refresh_token"),
("refresh_token", refresh_token),
("client_id", client_id),
];
self.exchange(&form, opts).await
}
pub async fn revoke(&self, client_id: &str, token: &str) -> Result<(), OauthError> {
self.revoke_with(client_id, token, OauthOptions::new()).await
}
pub async fn revoke_with(
&self,
client_id: &str,
token: &str,
opts: OauthOptions,
) -> Result<(), OauthError> {
let form = [("token", token), ("client_id", client_id)];
let timeout = self.timeout(opts.timeout)?;
let form = &form;
with_retry(self.client.retries(), || async move {
let answer = self.client.transport().post_form(REVOKE_PATH, form, timeout).await?;
match answer.status {
200..=299 => Ok(()),
_ => Err(refusal(answer)),
}
})
.await
}
pub async fn poll_device_token(
&self,
client_id: &str,
device: &DeviceAuthorization,
) -> Result<TokenResponse, OauthError> {
self.poll_device_token_with(client_id, device, OauthOptions::new()).await
}
pub async fn poll_device_token_with(
&self,
client_id: &str,
device: &DeviceAuthorization,
opts: OauthOptions,
) -> Result<TokenResponse, OauthError> {
self.poll(client_id, device, opts, &TokioClock::start()).await
}
pub(crate) async fn poll<C: PollClock + Sync>(
&self,
client_id: &str,
device: &DeviceAuthorization,
opts: OauthOptions,
clock: &C,
) -> Result<TokenResponse, OauthError> {
self.timeout(opts.timeout)?;
let mut interval =
if device.interval >= 1 { device.interval } else { DEFAULT_POLL_INTERVAL };
let deadline = clock.now().saturating_add(seconds(device.expires_in));
loop {
let left = deadline.saturating_sub(clock.now());
clock.sleep(seconds(interval).min(left)).await;
if clock.now() >= deadline {
return Err(OauthError::ExpiredToken(OauthErrorResponse {
error_code: "expired_token".to_owned(),
error_description: None,
status: None,
}));
}
match self.exchange_device_code_with(client_id, &device.device_code, opts.clone()).await
{
Err(OauthError::Rejected(refused)) if refused.error_code == "slow_down" => {
interval = interval.saturating_add(SLOW_DOWN_STEP);
}
Err(OauthError::Rejected(refused))
if refused.error_code == "authorization_pending" => {}
outcome => return outcome,
}
}
}
async fn exchange(
&self,
form: &[(&str, &str)],
opts: OauthOptions,
) -> Result<TokenResponse, OauthError> {
let timeout = self.timeout(opts.timeout)?;
decode(self.client.transport().post_form(TOKEN_PATH, form, timeout).await?)
}
fn timeout(&self, per_call: Option<Duration>) -> Result<Duration, Error> {
self.client.call_timeout(per_call)
}
}
#[derive(Debug, Clone, Default)]
pub struct OauthOptions {
timeout: Option<Duration>,
}
impl OauthOptions {
pub fn new() -> Self {
Self::default()
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
}
#[derive(Debug, Clone, Default)]
pub struct DeviceAuthorizationOptions {
scope: Option<String>,
resource: Option<String>,
timeout: Option<Duration>,
}
impl DeviceAuthorizationOptions {
pub fn new() -> Self {
Self::default()
}
pub fn scope(mut self, scope: impl Into<String>) -> Self {
self.scope = Some(scope.into());
self
}
pub fn resource(mut self, resource: impl Into<String>) -> Self {
self.resource = Some(resource.into());
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct OauthMetadata {
pub issuer: String,
pub authorization_endpoint: String,
pub token_endpoint: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub device_authorization_endpoint: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub revocation_endpoint: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scopes_supported: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub response_types_supported: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub grant_types_supported: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code_challenge_methods_supported: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub token_endpoint_auth_methods_supported: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub authorization_response_iss_parameter_supported: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub service_documentation: Option<String>,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct DeviceAuthorization {
pub device_code: String,
pub user_code: String,
pub verification_uri: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub verification_uri_complete: Option<String>,
pub expires_in: i64,
pub interval: i64,
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct TokenResponse {
pub access_token: String,
pub token_type: String,
pub expires_in: i64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub refresh_token: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: Option<String>,
#[serde(rename = "mslm:apikey_id", default, skip_serializing_if = "Option::is_none")]
pub apikey_id: Option<String>,
#[serde(rename = "mslm:apikey", default, skip_serializing_if = "Option::is_none")]
pub apikey: Option<String>,
}
#[derive(Debug)]
#[non_exhaustive]
pub enum OauthError {
AccessDenied(OauthErrorResponse),
ExpiredToken(OauthErrorResponse),
Rejected(OauthErrorResponse),
Client(Error),
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct OauthErrorResponse {
pub error_code: String,
pub error_description: Option<String>,
pub status: Option<u16>,
}
impl OauthError {
pub fn kind(&self) -> ErrorKind {
match self {
Self::Client(err) => err.kind(),
Self::AccessDenied(r) | Self::ExpiredToken(r) | Self::Rejected(r) => {
kind_for_status(r.status.unwrap_or(400), None)
}
}
}
pub fn retryable(&self) -> bool {
match self {
Self::Client(err) => err.retryable(),
Self::AccessDenied(_) | Self::ExpiredToken(_) | Self::Rejected(_) => false,
}
}
pub fn status(&self) -> Option<u16> {
match self {
Self::Client(err) => err.status(),
Self::AccessDenied(r) | Self::ExpiredToken(r) | Self::Rejected(r) => r.status,
}
}
pub fn error_code(&self) -> Option<&str> {
self.response().map(|r| r.error_code.as_str())
}
pub fn error_description(&self) -> Option<&str> {
self.response().and_then(|r| r.error_description.as_deref())
}
pub fn message(&self) -> String {
match self {
Self::Client(err) => err.message(),
Self::AccessDenied(r) | Self::ExpiredToken(r) | Self::Rejected(r) => {
match &r.error_description {
Some(description) => format!("{}: {description}", r.error_code),
None => r.error_code.clone(),
}
}
}
}
pub(crate) fn retry_after(&self) -> Option<Duration> {
match self {
Self::Client(err) => err.retry_after(),
Self::AccessDenied(_) | Self::ExpiredToken(_) | Self::Rejected(_) => None,
}
}
fn response(&self) -> Option<&OauthErrorResponse> {
match self {
Self::AccessDenied(r) | Self::ExpiredToken(r) | Self::Rejected(r) => Some(r),
Self::Client(_) => None,
}
}
}
impl std::fmt::Display for OauthError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match (self, self.status()) {
(Self::Client(err), _) => std::fmt::Display::fmt(err, f),
(_, Some(status)) => {
write!(f, "internetdata: oauth (HTTP {status}): {}", self.message())
}
(_, None) => write!(f, "internetdata: oauth: {}", self.message()),
}
}
}
impl std::error::Error for OauthError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
Self::Client(err) => Some(err),
Self::AccessDenied(_) | Self::ExpiredToken(_) | Self::Rejected(_) => None,
}
}
}
impl From<Error> for OauthError {
fn from(err: Error) -> Self {
Self::Client(err)
}
}
pub(crate) trait PollClock {
fn now(&self) -> Duration;
fn sleep(&self, duration: Duration) -> impl Future<Output = ()> + Send;
}
struct TokioClock {
origin: tokio::time::Instant,
}
impl TokioClock {
fn start() -> Self {
Self { origin: tokio::time::Instant::now() }
}
}
impl PollClock for TokioClock {
fn now(&self) -> Duration {
self.origin.elapsed()
}
fn sleep(&self, duration: Duration) -> impl Future<Output = ()> + Send {
tokio::time::sleep(duration)
}
}
fn seconds(n: i64) -> Duration {
Duration::from_secs(u64::try_from(n).unwrap_or(0))
}
fn decode<T: DeserializeOwned>(answer: Answer) -> Result<T, OauthError> {
if !(200..300).contains(&answer.status) {
return Err(refusal(answer));
}
serde_json::from_str(&answer.body).map_err(|e| {
OauthError::Client(Error::Api {
kind: ErrorKind::ServerError,
message: format!("could not decode the response: {e}"),
status: answer.status,
retry_after: None,
})
})
}
fn refusal(answer: Answer) -> OauthError {
if (400..500).contains(&answer.status) {
if let Some(refused) = oauth_error_response(answer.status, &answer.body) {
return match refused.error_code.as_str() {
"access_denied" => OauthError::AccessDenied(refused),
"expired_token" => OauthError::ExpiredToken(refused),
_ => OauthError::Rejected(refused),
};
}
}
OauthError::Client(Error::from_response(answer.status, answer.retry_after, &answer.body))
}
fn oauth_error_response(status: u16, body: &str) -> Option<OauthErrorResponse> {
let value: serde_json::Value = serde_json::from_str(body).ok()?;
let error_code = value.get("error")?.as_str()?.to_owned();
let error_description =
value.get("error_description").and_then(serde_json::Value::as_str).map(str::to_owned);
Some(OauthErrorResponse { error_code, error_description, status: Some(status) })
}
#[cfg(test)]
mod tests;