laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
Documentation
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;

/// How users log in with one provider: where to send them, where to exchange the callback's
/// code, and how to read their profile. Register a driver under a provider name with
/// [`Drivers::extend`].
///
/// Social login runs the rest of the login for every driver. It sends the user to
/// [`authorize_url`](Self::authorize_url) with a random state and a PKCE challenge, checks the
/// callback against the session, and exchanges the code at [`token_url`](Self::token_url),
/// sending the client ID and secret in the form. Then it calls [`user`](Self::user) with the
/// tokens, and adds the provider's name and the token to the profile it returns.
///
/// ```
/// use laravel::auth::social::{self, Driver, Profile, Tokens};
///
/// struct GitLab;
///
/// impl Driver for GitLab {
///     fn authorize_url(&self) -> String {
///         "https://gitlab.com/oauth/authorize".to_owned()
///     }
///
///     fn token_url(&self) -> String {
///         "https://gitlab.com/oauth/token".to_owned()
///     }
///
///     fn scopes(&self) -> &[&str] {
///         &["openid", "profile", "email"]
///     }
///
///     async fn user(&self, tokens: &Tokens<'_>) -> Result<Profile, social::Error> {
///         tokens.user_info("https://gitlab.com/oauth/userinfo").await
///     }
/// }
/// ```
pub trait Driver: Send + Sync + 'static {
    /// The URL where the provider asks the user to approve the application. It may have query
    /// parameters of its own.
    fn authorize_url(&self) -> String;

    /// The URL where social login exchanges the callback's code for tokens.
    fn token_url(&self) -> String;

    /// The scopes that every login asks for. [`PendingRedirect::scopes`](super::PendingRedirect::scopes)
    /// adds to these.
    fn scopes(&self) -> &[&str];

    /// Reads the user's profile, from the ID token in `tokens` or from the provider's API.
    ///
    /// # Errors
    ///
    /// Fails with [`Error::Provider`] when the provider can't be reached or its response can't be
    /// trusted. A profile without an ID fails the login the same way.
    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>;

/// The providers that users can log in with, by name. `google`, `github`, and `microsoft` are
/// registered already, and you may add your own:
///
/// ```
/// use laravel::Application;
/// # use laravel::auth::social::{self, Driver, Profile, Tokens};
/// # struct GitLab { url: String }
/// # impl Driver for GitLab {
/// #     fn authorize_url(&self) -> String { format!("{}/oauth/authorize", self.url) }
/// #     fn token_url(&self) -> String { format!("{}/oauth/token", self.url) }
/// #     fn scopes(&self) -> &[&str] { &["openid", "profile", "email"] }
/// #     async fn user(&self, tokens: &Tokens<'_>) -> Result<Profile, social::Error> {
/// #         tokens.user_info(format!("{}/oauth/userinfo", self.url)).await
/// #     }
/// # }
///
/// Application::configure().with_services(|app| {
///     app.social().extend("gitlab", |_config| GitLab { url: "https://gitlab.com".into() });
/// });
/// ```
///
/// Each factory runs once, while the application starts, with the final configuration. A later
/// registration under the same name replaces an earlier one, including a built-in provider.
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 {
    /// Registers a provider under a name, such as `gitlab`. The name is the `{provider}` in the
    /// routes, and the prefix of the variables that hold its OAuth client, such as
    /// `GITLAB_CLIENT_ID`.
    ///
    /// The factory receives the final configuration, so it may read the provider's own
    /// [configuration section](struct@crate::config::Section), such as the address of a self-hosted
    /// server.
    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>),
            ),
        );
    }

    /// Builds every registered provider's driver.
    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(),
        )
    }
}

/// The application's providers, built while it starts.
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 {
    /// The provider's name in messages, such as `GitHub`.
    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
    }
}

/// The tokens that the provider issued for a login, which [`Driver::user`] reads the profile
/// with.
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<'_> {
    /// The access token, for calling the provider's API as the user.
    #[must_use]
    pub fn access_token(&self) -> &str {
        &self.response.access_token
    }

    /// The claims of the OpenID Connect ID token that came with the access token, after checking
    /// that the token is for this application's client ID.
    ///
    /// The token came straight from the token endpoint over TLS, so OpenID Connect Core 3.1.3.7
    /// waives its signature check. Check the issuer (`iss`) yourself.
    ///
    /// # Errors
    ///
    /// Fails with [`Error::Provider`] when the response has no ID token, the token can't be read,
    /// or its audience (`aud`) is another client.
    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)
    }

    /// Reads the profile from an OpenID Connect user info endpoint, such as GitLab's, Okta's, or
    /// Keycloak's. `sub` becomes the profile's `id`, `preferred_username` its `nickname`, and
    /// `picture` its `avatar`, and `name`, `email`, and `email_verified` fill the fields of the
    /// same names. `raw` holds every claim. These endpoints return the standard claims only when
    /// the login asks for the `openid` scope.
    ///
    /// # Errors
    ///
    /// Fails with [`Error::Provider`] when the endpoint can't be reached, refuses the access
    /// token, or doesn't return a JSON object.
    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")
        ))
    }
}

/// The profile that a [`Driver`] reads. Social login adds the provider and the token to make the
/// [`User`](super::User) that [`user`](super::user) returns.
#[derive(Debug, Clone, Default)]
pub struct Profile {
    /// The user's ID at the provider, which never changes. It's required.
    pub id: String,
    /// The user's full name.
    pub name: Option<String>,
    /// The user's handle, such as a GitHub login.
    pub nickname: Option<String>,
    /// The user's email address. Mark it verified only when the provider says it verified the
    /// address, since [`User::verified_email`](super::User::verified_email) links accounts by it.
    pub email: Option<Email>,
    /// The URL of the user's avatar.
    pub avatar: Option<String>,
    /// The profile exactly as the provider sent it.
    pub raw: Value,
}

pub(super) fn string(value: &Value, name: &str) -> Option<String> {
    value.get(name)?.as_str().map(str::to_owned)
}

/// The OpenID Connect `email` claim, verified when `email_verified` is `true`.
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),
    })
}