meteroid-rs 0.31.4

Official Rust SDK for Meteroid, the open-source billing platform: subscriptions, invoicing, usage-based billing and webhooks.
Documentation
// this file is @generated by Perseid; edit the shared runtime template.
//! Security schemes of the API and the credentials configured for them.
#![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>>;

/// Returns a fresh bearer token before each request, e.g. a short-lived access token.
#[derive(Clone)]
pub struct TokenProvider(Arc<dyn Fn() -> TokenFuture + Send + Sync>);

impl TokenProvider {
    /// Calls `provider` for the token of each request.
    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())))
    }
}

/// Keeps request futures `Sync` while they await a provider or token request future that is only
/// `Send`.
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")
    }
}

/// HTTP basic credentials.
#[derive(Clone)]
pub struct BasicAuth {
    /// The user name.
    pub username: String,
    /// The password.
    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,
    /// A bearer token the client can fetch with the OAuth2 client credentials flow: the token URL
    /// (absolute, or relative to the base URL) and the scopes asked for.
    OAuth(&'static str, &'static str),
    Basic,
    /// Location (`header`, `query` or `cookie`) and name of the key.
    ApiKey(&'static str, &'static str),
}

/// Alternatives of scheme names: the first one whose credentials are all configured is sent.
pub(crate) type Security = &'static [&'static [&'static str]];

/// Tokens are renewed this long before they expire, or at half their life when it is shorter.
const EXPIRY_MARGIN: Duration = Duration::from_secs(60);

struct CachedToken {
    value: String,
    /// `None` for a token without a lifetime.
    expires: Option<Instant>,
}

/// The client credentials of the OAuth2 flow, and the access tokens fetched with them by token URL.
#[derive(Clone)]
pub(crate) struct OAuthClient {
    pub(crate) client_id: String,
    pub(crate) client_secret: String,
    /// Sends the client credentials as form fields instead of an HTTP basic header.
    pub(crate) in_body: bool,
    // The lock is held while a token is fetched, so concurrent requests share one fetch.
    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(),
        }
    }

    /// The token cached for `url`, else the one `fetch` gets, with its lifetime.
    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)
    }

    /// Forgets `token` of `url` after the API rejected it, unless a newer one replaced it.
    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);
        }
    }
}

/// The OAuth2 access token a request carries, which a 401 response replaces.
pub(crate) struct OAuthUse {
    pub(crate) url: &'static str,
    pub(crate) scope: &'static str,
    /// The cache key of the token: the absolute token URL.
    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>,
}

/// Headers and query parameters carrying the credentials of one request.
#[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,
        }
    }

    /// The names of the first alternative whose credentials are all configured.
    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()
    }

    /// The token URL and scopes of the OAuth2 scheme whose access token the client fetches, when
    /// neither a token provider nor a token is set.
    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,
            })
    }

    /// The headers, query parameters and cookies of the credentials of the first satisfiable
    /// alternative. `oauth_token` is the access token fetched by [`Self::oauth_scheme`].
    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
}