use std::collections::HashMap;
use std::fmt;
use std::future::Future;
use std::sync::Arc;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use futures_util::future::BoxFuture;
use serde_json::Value;
use super::{CLIENT, Email, Error, Provider, TokenResponse, providers};
use crate::config::Config;
pub trait Driver: Send + Sync + 'static {
fn authorize_url(&self) -> String;
fn token_url(&self) -> String;
fn scopes(&self) -> &[&str];
fn user(&self, tokens: &Tokens<'_>) -> impl Future<Output = Result<Profile, Error>> + Send;
}
trait ErasedDriver: Send + Sync + 'static {
fn authorize_url(&self) -> String;
fn token_url(&self) -> String;
fn scopes(&self) -> &[&str];
fn user<'a>(&'a self, tokens: &'a Tokens<'a>) -> BoxFuture<'a, Result<Profile, Error>>;
}
impl<D: Driver> ErasedDriver for D {
fn authorize_url(&self) -> String {
Driver::authorize_url(self)
}
fn token_url(&self) -> String {
Driver::token_url(self)
}
fn scopes(&self) -> &[&str] {
Driver::scopes(self)
}
fn user<'a>(&'a self, tokens: &'a Tokens<'a>) -> BoxFuture<'a, Result<Profile, Error>> {
Box::pin(Driver::user(self, tokens))
}
}
type Factory = Box<dyn FnOnce(&Config) -> Arc<dyn ErasedDriver> + Send + Sync>;
pub struct Drivers {
factories: HashMap<Provider, (String, Factory)>,
}
impl Default for Drivers {
fn default() -> Self {
let mut drivers = Self {
factories: HashMap::new(),
};
drivers.insert(Provider::GOOGLE, "Google", |_| providers::Google);
drivers.insert(Provider::GITHUB, "GitHub", providers::GitHub::new);
drivers.insert(Provider::MICROSOFT, "Microsoft", providers::Microsoft::new);
drivers
}
}
impl fmt::Debug for Drivers {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut names: Vec<_> = self.factories.keys().map(Provider::as_str).collect();
names.sort_unstable();
f.debug_struct("Drivers").field("providers", &names).finish()
}
}
impl Drivers {
pub fn extend<D, F>(&mut self, name: impl Into<Provider>, factory: F) -> &mut Self
where
D: Driver,
F: FnOnce(&Config) -> D + Send + Sync + 'static,
{
let name = name.into();
let label = name.as_str().to_owned();
self.insert(name, label, factory);
self
}
fn insert<D, F>(&mut self, name: Provider, label: impl Into<String>, factory: F)
where
D: Driver,
F: FnOnce(&Config) -> D + Send + Sync + 'static,
{
self.factories.insert(
name,
(
label.into(),
Box::new(move |config| Arc::new(factory(config)) as Arc<dyn ErasedDriver>),
),
);
}
pub(crate) fn build(self, config: &Config) -> Registered {
Registered(
self.factories
.into_iter()
.map(|(name, (label, factory))| {
let driver = factory(config);
(name, Registration { label, driver })
})
.collect(),
)
}
}
pub(crate) struct Registered(HashMap<Provider, Registration>);
impl fmt::Debug for Registered {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_set().entries(self.0.keys()).finish()
}
}
impl Registered {
pub(super) fn get(&self, provider: &Provider) -> Option<&Registration> {
self.0.get(provider)
}
}
pub(super) struct Registration {
pub(super) label: String,
driver: Arc<dyn ErasedDriver>,
}
impl Registration {
pub(super) fn authorize_url(&self) -> String {
self.driver.authorize_url()
}
pub(super) fn token_url(&self) -> String {
self.driver.token_url()
}
pub(super) fn scopes(&self) -> &[&str] {
self.driver.scopes()
}
pub(super) async fn user(&self, tokens: &Tokens<'_>) -> Result<Profile, Error> {
self.driver.user(tokens).await
}
}
pub struct Tokens<'a> {
pub(super) label: &'a str,
pub(super) client_id: &'a str,
pub(super) response: &'a TokenResponse,
}
impl fmt::Debug for Tokens<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Tokens")
.field("provider", &self.label)
.finish_non_exhaustive()
}
}
impl Tokens<'_> {
#[must_use]
pub fn access_token(&self) -> &str {
&self.response.access_token
}
pub fn id_token(&self) -> Result<Value, Error> {
let invalid = || Error::Provider(format!("{}'s token response has no valid ID token", self.label));
let payload = self
.response
.id_token
.as_deref()
.and_then(|token| token.split('.').nth(1))
.ok_or_else(invalid)?;
let claims: Value = URL_SAFE_NO_PAD
.decode(payload)
.ok()
.and_then(|json| serde_json::from_slice(&json).ok())
.filter(Value::is_object)
.ok_or_else(invalid)?;
let audience = claims.get("aud");
let matches = match audience {
Some(Value::String(audience)) => audience == self.client_id,
Some(Value::Array(audiences)) => audiences.iter().any(|audience| audience == self.client_id),
_ => false,
};
if !matches {
return Err(self.untrusted("aud", audience.map(Value::to_string).as_deref()));
}
Ok(claims)
}
pub async fn user_info(&self, url: impl Into<String>) -> Result<Profile, Error> {
let claims: Value = CLIENT
.get(url)
.token(self.access_token())
.accept_json()
.ensure_successful()
.send()
.await
.and_then(|response| response.json())
.map_err(|error| Error::Provider(format!("couldn't fetch {}'s user info: {error}", self.label)))?;
if !claims.is_object() {
return Err(Error::Provider(format!(
"{}'s user info isn't a JSON object",
self.label
)));
}
Ok(Profile {
id: match claims.get("sub") {
Some(Value::String(id)) => id.clone(),
Some(Value::Number(id)) => id.to_string(),
_ => String::new(),
},
name: string(&claims, "name"),
nickname: string(&claims, "preferred_username"),
email: email(&claims),
avatar: string(&claims, "picture"),
raw: claims,
})
}
pub(super) fn untrusted(&self, claim: &str, value: Option<&str>) -> Error {
Error::Provider(format!(
"{}'s ID token has an unexpected `{claim}`: {}",
self.label,
value.unwrap_or("none")
))
}
}
#[derive(Debug, Clone, Default)]
pub struct Profile {
pub id: String,
pub name: Option<String>,
pub nickname: Option<String>,
pub email: Option<Email>,
pub avatar: Option<String>,
pub raw: Value,
}
pub(super) fn string(value: &Value, name: &str) -> Option<String> {
value.get(name)?.as_str().map(str::to_owned)
}
pub(super) fn email(claims: &Value) -> Option<Email> {
Some(Email {
address: string(claims, "email")?,
verified: claims.get("email_verified").and_then(Value::as_bool) == Some(true),
})
}