#![allow(dead_code)]
use std::{
collections::HashMap,
fmt,
future::Future,
pin::Pin,
sync::{Arc, Mutex, PoisonError},
task::{Context, Poll},
time::{Duration, Instant},
};
use crate::error::Error;
type TokenFuture = Pin<Box<dyn Future<Output = Result<String, Error>> + Send>>;
#[derive(Clone)]
pub struct TokenProvider(Arc<dyn Fn() -> TokenFuture + Send + Sync>);
impl TokenProvider {
pub fn new<F, Fut>(provider: F) -> Self
where
F: Fn() -> Fut + Send + Sync + 'static,
Fut: Future<Output = Result<String, Error>> + Send + 'static,
{
Self(Arc::new(move || Box::pin(provider())))
}
}
pub(crate) struct SyncFuture<'a, T>(Mutex<Pin<Box<dyn Future<Output = T> + Send + 'a>>>);
impl<'a, T> SyncFuture<'a, T> {
pub(crate) fn new(future: impl Future<Output = T> + Send + 'a) -> Self {
Self(Mutex::new(Box::pin(future)))
}
}
impl<T> Future for SyncFuture<'_, T> {
type Output = T;
fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Self::Output> {
let future = self
.get_mut()
.0
.get_mut()
.unwrap_or_else(PoisonError::into_inner);
future.as_mut().poll(cx)
}
}
impl fmt::Debug for TokenProvider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("TokenProvider")
}
}
#[derive(Clone)]
pub struct BasicAuth {
pub username: String,
pub password: String,
}
impl fmt::Debug for BasicAuth {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("BasicAuth")
.field("username", &self.username)
.finish_non_exhaustive()
}
}
pub(crate) enum Scheme {
Bearer,
OAuth(&'static str, &'static str),
Basic,
ApiKey(&'static str, &'static str),
}
pub(crate) type Security = &'static [&'static [&'static str]];
const EXPIRY_MARGIN: Duration = Duration::from_secs(60);
struct CachedToken {
value: String,
expires: Option<Instant>,
}
#[derive(Clone)]
pub(crate) struct OAuthClient {
pub(crate) client_id: String,
pub(crate) client_secret: String,
pub(crate) in_body: bool,
tokens: Arc<tokio::sync::Mutex<HashMap<String, CachedToken>>>,
}
impl OAuthClient {
pub(crate) fn new(client_id: String, client_secret: String, in_body: bool) -> Self {
Self {
client_id,
client_secret,
in_body,
tokens: Arc::default(),
}
}
pub(crate) async fn token(
&self,
url: &str,
fetch: SyncFuture<'_, Result<(String, Option<Duration>), Error>>,
) -> Result<String, Error> {
let mut tokens = self.tokens.lock().await;
if let Some(cached) = tokens.get(url) {
if cached
.expires
.is_none_or(|expires| expires > Instant::now())
{
return Ok(cached.value.clone());
}
}
let (value, lifetime) = fetch.await?;
let expires = lifetime.map(|life| Instant::now() + life - EXPIRY_MARGIN.min(life / 2));
tokens.insert(
url.to_owned(),
CachedToken {
value: value.clone(),
expires,
},
);
Ok(value)
}
pub(crate) async fn invalidate(&self, url: &str, token: &str) {
let mut tokens = self.tokens.lock().await;
if tokens.get(url).is_some_and(|cached| cached.value == token) {
tokens.remove(url);
}
}
}
pub(crate) struct OAuthUse {
pub(crate) url: &'static str,
pub(crate) scope: &'static str,
pub(crate) key: String,
pub(crate) token: String,
}
#[derive(Clone)]
pub(crate) struct Credentials {
pub(crate) schemes: &'static [(&'static str, Scheme)],
pub(crate) security: Security,
pub(crate) token_provider: Option<TokenProvider>,
pub(crate) oauth: Option<OAuthClient>,
pub(crate) basic_auth: Option<BasicAuth>,
pub(crate) api_keys: HashMap<String, String>,
}
#[derive(Default)]
pub(crate) struct Applied {
pub(crate) headers: Vec<(&'static str, String)>,
pub(crate) query: Vec<(&'static str, String)>,
pub(crate) cookies: Vec<(&'static str, String)>,
}
impl Credentials {
fn scheme(&self, name: &str) -> Option<&Scheme> {
self.schemes
.iter()
.find(|(n, _)| *n == name)
.map(|(_, s)| s)
}
fn api_key<'a>(&'a self, name: &str, token: Option<&'a str>) -> Option<&'a str> {
self.api_keys.get(name).map(String::as_str).or(token)
}
fn configured(&self, name: &str, token: Option<&str>) -> bool {
match self.scheme(name) {
Some(Scheme::Bearer) => self.token_provider.is_some() || token.is_some(),
Some(Scheme::OAuth(..)) => {
self.token_provider.is_some() || token.is_some() || self.oauth.is_some()
}
Some(Scheme::Basic) => self.basic_auth.is_some(),
Some(Scheme::ApiKey(..)) => self.api_key(name, token).is_some(),
None => false,
}
}
fn chosen(&self, security: Option<Security>, token: Option<&str>) -> &'static [&'static str] {
security
.unwrap_or(self.security)
.iter()
.find(|names| {
!names.is_empty() && names.iter().all(|name| self.configured(name, token))
})
.copied()
.unwrap_or_default()
}
pub(crate) fn oauth_scheme(
&self,
security: Option<Security>,
token: Option<&str>,
) -> Option<(&'static str, &'static str)> {
if self.oauth.is_none() || self.token_provider.is_some() || token.is_some() {
return None;
}
self.chosen(security, token)
.iter()
.find_map(|name| match self.scheme(name) {
Some(Scheme::OAuth(url, scope)) => Some((*url, *scope)),
_ => None,
})
}
pub(crate) async fn apply(
&self,
security: Option<Security>,
token: Option<&str>,
oauth_token: Option<&str>,
) -> Result<Applied, Error> {
let mut applied = Applied::default();
for name in self.chosen(security, token) {
match self.scheme(name) {
Some(Scheme::Bearer | Scheme::OAuth(..)) => {
let token = match &self.token_provider {
Some(provider) => SyncFuture::new((provider.0)()).await?,
None => token.or(oauth_token).unwrap_or_default().to_owned(),
};
applied
.headers
.push(("authorization", format!("Bearer {token}")));
}
Some(Scheme::Basic) => {
let BasicAuth { username, password } = self.basic_auth.as_ref().unwrap();
let encoded = base64(format!("{username}:{password}").as_bytes());
applied
.headers
.push(("authorization", format!("Basic {encoded}")));
}
Some(Scheme::ApiKey(location, param)) => {
let key = self.api_key(name, token).unwrap_or_default().to_owned();
match *location {
"query" => applied.query.push((param, key)),
"cookie" => applied.cookies.push((param, key)),
_ => applied.headers.push((param, key)),
}
}
None => {}
}
}
Ok(applied)
}
}
pub(crate) fn base64(input: &[u8]) -> String {
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
let mut out = String::with_capacity(input.len().div_ceil(3) * 4);
for chunk in input.chunks(3) {
let bytes = [
chunk[0],
*chunk.get(1).unwrap_or(&0),
*chunk.get(2).unwrap_or(&0),
];
let n = u32::from_be_bytes([0, bytes[0], bytes[1], bytes[2]]);
for i in 0..4 {
if i <= chunk.len() {
out.push(ALPHABET[(n >> (18 - 6 * i) & 63) as usize] as char);
} else {
out.push('=');
}
}
}
out
}