use std::fmt::Write as _;
use std::future::Future;
use std::time::Duration;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
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 AUTHORIZE_PATH: &str = "/oauth/authorize";
const TOKEN_PATH: &str = "/oauth/token";
const REVOKE_PATH: &str = "/oauth/revoke";
const REGISTER_PATH: &str = "/oauth/register";
const DEVICE_CODE_GRANT: &str = "urn:ietf:params:oauth:grant-type:device_code";
const PKCE_METHOD: &str = "S256";
const DEFAULT_POLL_INTERVAL: i64 = 5;
const SLOW_DOWN_STEP: i64 = 5;
#[derive(Debug, Clone, Copy)]
pub struct OauthApi<'a> {
client: &'a Client,
}
pub(crate) fn authorization_server(base_url: &str) -> String {
let Ok(mut url) = reqwest::Url::parse(base_url) else {
return base_url.to_owned();
};
let apex = match url.host_str().and_then(|host| host.split_once('.')) {
Some(("api", rest)) => rest.to_owned(),
Some((label, rest)) => match label.strip_prefix("api-") {
Some(env) if !env.is_empty() => format!("{env}.{rest}"),
_ => return base_url.to_owned(),
},
None => return base_url.to_owned(),
};
if url.set_host(Some(&apex)).is_err() {
return base_url.to_owned();
}
url.as_str().trim_end_matches('/').to_owned()
}
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 fn authorization_url(
&self,
client_id: &str,
redirect_uri: &str,
code_challenge: &str,
) -> Result<String, OauthError> {
self.authorization_url_with(
client_id,
redirect_uri,
code_challenge,
AuthorizationUrlOptions::new(),
)
}
pub fn authorization_url_with(
&self,
client_id: &str,
redirect_uri: &str,
code_challenge: &str,
opts: AuthorizationUrlOptions,
) -> Result<String, OauthError> {
let required = [
("client_id", client_id),
("redirect_uri", redirect_uri),
("code_challenge", code_challenge),
];
if let Some((name, _)) = required.iter().find(|(_, value)| value.is_empty()) {
return Err(Error::Config(format!("{name} must not be empty")).into());
}
let mut params = vec![("response_type", "code")];
params.extend(required);
params.push(("code_challenge_method", PKCE_METHOD));
for (name, value) in
[("scope", &opts.scope), ("state", &opts.state), ("resource", &opts.resource)]
{
if let Some(value) = value.as_deref().filter(|v| !v.is_empty()) {
params.push((name, value));
}
}
let mut url = format!("{}{AUTHORIZE_PATH}", self.client.transport().oauth_base_url());
for (i, (name, value)) in params.iter().enumerate() {
url.push(if i == 0 { '?' } else { '&' });
url.push_str(name);
url.push('=');
percent_encode(&mut url, value);
}
Ok(url)
}
pub async fn exchange_authorization_code(
&self,
client_id: &str,
code: &str,
code_verifier: &str,
redirect_uri: &str,
) -> Result<TokenResponse, OauthError> {
let opts = OauthOptions::new();
self.exchange_authorization_code_with(client_id, code, code_verifier, redirect_uri, opts)
.await
}
pub async fn exchange_authorization_code_with(
&self,
client_id: &str,
code: &str,
code_verifier: &str,
redirect_uri: &str,
opts: OauthOptions,
) -> Result<TokenResponse, OauthError> {
let form = [
("grant_type", "authorization_code"),
("code", code),
("redirect_uri", redirect_uri),
("client_id", client_id),
("code_verifier", code_verifier),
];
self.exchange(&form, opts).await
}
pub fn create_pkce(&self) -> Result<Pkce, OauthError> {
let mut bytes = [0u8; 32];
getrandom::fill(&mut bytes).map_err(|e| {
Error::Io(std::io::Error::other(format!("the secure random source failed: {e}")))
})?;
let verifier = base64url(&bytes);
let challenge = challenge_for(&verifier);
Ok(Pkce { verifier, challenge, method: PKCE_METHOD.to_owned() })
}
pub fn pkce_challenge(&self, verifier: &str) -> String {
challenge_for(verifier)
}
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?)
}
pub async fn register(
&self,
redirect_uris: &[impl AsRef<str>],
) -> Result<ClientRegistration, OauthError> {
self.register_with(redirect_uris, RegisterOptions::new()).await
}
pub async fn register_with(
&self,
redirect_uris: &[impl AsRef<str>],
opts: RegisterOptions,
) -> Result<ClientRegistration, OauthError> {
let redirect_uris: Vec<&str> = redirect_uris.iter().map(AsRef::as_ref).collect();
if redirect_uris.is_empty() {
return Err(Error::Config("redirect_uris must list at least one URI".to_owned()).into());
}
if let Some(i) = redirect_uris.iter().position(|uri| uri.is_empty()) {
return Err(Error::Config(format!("redirect_uris[{i}] must not be empty")).into());
}
let request = RegistrationRequest {
redirect_uris: &redirect_uris,
client_name: opts.client_name.as_deref().filter(|name| !name.is_empty()),
};
let body = serde_json::to_string(&request).expect("a list of strings always serializes");
let timeout = self.timeout(opts.timeout)?;
let body = &body;
with_retry(self.client.retries(), || async move {
let transport = self.client.transport();
decode(transport.post_json_keyless(REGISTER_PATH, body.clone(), timeout).await?)
})
.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 RegisterOptions {
client_name: Option<String>,
timeout: Option<Duration>,
}
impl RegisterOptions {
pub fn new() -> Self {
Self::default()
}
pub fn client_name(mut self, client_name: impl Into<String>) -> Self {
self.client_name = Some(client_name.into());
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = Some(timeout);
self
}
}
#[derive(Serialize)]
struct RegistrationRequest<'a> {
redirect_uris: &'a [&'a str],
#[serde(skip_serializing_if = "Option::is_none")]
client_name: Option<&'a str>,
}
#[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(Debug, Clone, Default)]
pub struct AuthorizationUrlOptions {
scope: Option<String>,
state: Option<String>,
resource: Option<String>,
}
impl AuthorizationUrlOptions {
pub fn new() -> Self {
Self::default()
}
pub fn scope(mut self, scope: impl Into<String>) -> Self {
self.scope = Some(scope.into());
self
}
pub fn state(mut self, state: impl Into<String>) -> Self {
self.state = Some(state.into());
self
}
pub fn resource(mut self, resource: impl Into<String>) -> Self {
self.resource = Some(resource.into());
self
}
}
#[derive(Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Pkce {
pub verifier: String,
pub challenge: String,
pub method: String,
}
impl std::fmt::Debug for Pkce {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Pkce")
.field("challenge", &self.challenge)
.field("method", &self.method)
.finish_non_exhaustive()
}
}
#[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 client_id_metadata_document_supported: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub registration_endpoint: Option<String>,
#[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(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[non_exhaustive]
pub struct ClientRegistration {
pub client_id: String,
pub client_id_issued_at: i64,
pub client_name: String,
pub redirect_uris: Vec<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub grant_types: Option<Vec<String>>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub response_types: Option<Vec<String>>,
pub token_endpoint_auth_method: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub scope: 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 challenge_for(verifier: &str) -> String {
base64url(Sha256::digest(verifier.as_bytes()).as_slice())
}
fn base64url(bytes: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
for chunk in bytes.chunks(3) {
let n =
chunk.iter().enumerate().fold(0u32, |n, (i, &b)| n | (u32::from(b) << (16 - 8 * i)));
for i in 0..=chunk.len() {
out.push(char::from(ALPHABET[((n >> (18 - 6 * i)) & 63) as usize]));
}
}
out
}
fn percent_encode(out: &mut String, value: &str) {
for &byte in value.as_bytes() {
if byte.is_ascii_alphanumeric() || matches!(byte, b'-' | b'.' | b'_' | b'~') {
out.push(char::from(byte));
} else {
let _ = write!(out, "%{byte:02X}");
}
}
}
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;