mod drivers;
mod fake;
mod providers;
use crate::session::SessionInternals as _;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::sync::LazyLock;
use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
use url::Url;
pub(crate) use self::drivers::Registered;
use self::drivers::Registration;
pub use self::drivers::{Driver, Drivers, Profile, Tokens};
pub(crate) use self::fake::Fakes;
pub use self::fake::{FakeUser, SocialFake, fake};
use crate::config::social::{Credentials, Social};
use crate::context::{Context, Internals};
use crate::http::Redirect;
use crate::http::client::Client;
use crate::session::Session;
use crate::time::Timestamp;
static CLIENT: LazyLock<Client> = LazyLock::new(Client::for_provider);
const RESERVED: [&str; 7] = [
"client_id",
"redirect_uri",
"response_type",
"scope",
"state",
"code_challenge",
"code_challenge_method",
];
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Provider(Cow<'static, str>);
impl Provider {
pub const GOOGLE: Self = Self(Cow::Borrowed("google"));
pub const GITHUB: Self = Self(Cow::Borrowed("github"));
pub const MICROSOFT: Self = Self(Cow::Borrowed("microsoft"));
pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
Self(name.into())
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
}
impl From<&'static str> for Provider {
fn from(name: &'static str) -> Self {
Self::new(name)
}
}
impl From<String> for Provider {
fn from(name: String) -> Self {
Self::new(name)
}
}
impl From<&Provider> for Provider {
fn from(provider: &Provider) -> Self {
provider.clone()
}
}
impl PartialEq<str> for Provider {
fn eq(&self, other: &str) -> bool {
self.as_str() == other
}
}
impl PartialEq<&str> for Provider {
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl fmt::Display for Provider {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[cfg(feature = "database")]
mod database {
use super::Provider;
use crate::db::{AnyRow, Decode, JsonElement, Nullable, Value};
impl JsonElement for Provider {}
impl Nullable for Provider {
fn null() -> Value<'static> {
Value::Text(None)
}
}
impl From<Provider> for Value<'_> {
fn from(provider: Provider) -> Self {
Self::Text(Some(provider.0))
}
}
impl<'a> From<&'a Provider> for Value<'a> {
fn from(provider: &'a Provider) -> Self {
Self::Text(Some(std::borrow::Cow::Borrowed(provider.as_str())))
}
}
impl<'a> From<&&'a Provider> for Value<'a> {
fn from(provider: &&'a Provider) -> Self {
Self::Text(Some(std::borrow::Cow::Borrowed(provider.as_str())))
}
}
impl Decode for Provider {
fn decode(row: &AnyRow, index: usize) -> crate::Result<Self> {
String::decode(row, index).map(Self::from)
}
}
}
#[derive(Debug, Clone)]
pub struct User {
pub provider: Provider,
pub id: String,
pub name: Option<String>,
pub nickname: Option<String>,
pub email: Option<Email>,
pub avatar: Option<String>,
pub token: Token,
pub raw: serde_json::Value,
}
impl User {
pub fn verified_email(&self) -> Option<&str> {
self.email
.as_ref()
.filter(|email| email.verified)
.map(|email| email.address.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Email {
pub address: String,
pub verified: bool,
}
#[derive(Clone, Serialize, Deserialize)]
pub struct Token {
pub access: String,
pub refresh: Option<String>,
pub expires_at: Option<Timestamp>,
pub scopes: Vec<String>,
}
#[cfg(feature = "database")]
impl crate::crypt::Encryptable for Token {
fn __encrypt(&self, encrypter: &crate::crypt::Encrypter) -> crate::Result<String> {
crate::crypt::__encrypt_json(self, encrypter)
}
fn __decrypt(payload: &str, encrypter: &crate::crypt::Encrypter) -> crate::Result<(Self, bool)> {
crate::crypt::__decrypt_json(payload, encrypter)
}
fn __same(&self, other: &Self) -> bool {
crate::crypt::__same_json(self, other)
}
}
impl fmt::Debug for Token {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Token")
.field("access", &"[redacted]")
.field("refresh", &self.refresh.as_ref().map(|_| "[redacted]"))
.field("expires_at", &self.expires_at)
.field("scopes", &self.scopes)
.finish()
}
}
#[derive(Debug, thiserror::Error, crate::errors::Status)]
pub enum Error {
#[error("Not Found")]
#[status(404)]
NotConfigured(Provider),
#[error("Not Found")]
#[status(404)]
UnknownProvider(Provider),
#[error("The login was cancelled.")]
#[status(403)]
Denied,
#[error("The login has expired. Please try again.")]
#[status(403)]
InvalidState,
#[error("{0}")]
#[status(502)]
Provider(String),
}
#[track_caller]
pub fn redirect(provider: impl Into<Provider>) -> crate::Result<Redirect> {
self::provider(provider).redirect()
}
pub fn provider(provider: impl Into<Provider>) -> PendingRedirect {
PendingRedirect {
provider: provider.into(),
scopes: Vec::new(),
parameters: Vec::new(),
}
}
#[derive(Debug, Clone)]
#[must_use = "a pending redirect does nothing until `redirect()` builds it"]
pub struct PendingRedirect {
provider: Provider,
scopes: Vec<String>,
parameters: Vec<(String, String)>,
}
impl PendingRedirect {
pub fn scopes<S: Into<String>>(mut self, scopes: impl IntoIterator<Item = S>) -> Self {
self.scopes.extend(scopes.into_iter().map(Into::into));
self
}
#[track_caller]
pub fn with<K: Into<String>, V: Into<String>>(mut self, parameters: impl IntoIterator<Item = (K, V)>) -> Self {
for (name, value) in parameters {
let name = name.into();
assert!(
!RESERVED.contains(&name.as_str()),
"social login sets the `{name}` parameter itself"
);
self.parameters.push((name, value.into()));
}
self
}
#[track_caller]
pub fn redirect(self) -> crate::Result<Redirect> {
let context = Context::expect("laravel::auth::social::redirect()");
let driver = registration(&context, &self.provider)?;
if let Some(fake) = Fakes::of(&context).active() {
let url = format!("https://social.fake/{}/authorize", self.provider);
fake.record_redirect(self.provider);
return Ok(leave_for(&context, url));
}
let social = &context.config().social;
let credentials = credentials(social, &self.provider, &driver.label)?;
let session = Session::of(&context).ok_or_else(|| {
crate::error::fail("social login needs a session: use it in routes of the `web` group, which start one")
})?;
let login = PendingLogin {
state: crate::str::random(40),
verifier: crate::str::random(64),
callback_url: callback_url(&self.provider, credentials),
};
let url = self.authorize_url(driver, credentials, &login)?;
session.put(&session_key(&self.provider), &login);
Ok(leave_for(&context, url))
}
fn authorize_url(
&self,
driver: &Registration,
credentials: &Credentials,
login: &PendingLogin,
) -> Result<String, Error> {
let mut scopes: Vec<&str> = driver.scopes().to_vec();
for scope in &self.scopes {
if !scopes.contains(&scope.as_str()) {
scopes.push(scope);
}
}
let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(login.verifier.as_bytes()));
let mut url = Url::parse(&driver.authorize_url())
.map_err(|error| Error::Provider(format!("{}'s authorization URL is invalid: {error}", driver.label)))?;
url.query_pairs_mut()
.append_pair("client_id", &credentials.client_id)
.append_pair("redirect_uri", &login.callback_url)
.append_pair("response_type", "code")
.append_pair("scope", &scopes.join(" "))
.append_pair("state", &login.state)
.append_pair("code_challenge", &challenge)
.append_pair("code_challenge_method", "S256")
.extend_pairs(&self.parameters);
Ok(url.into())
}
}
fn leave_for(context: &Context, url: String) -> Redirect {
if context.request().is_some_and(|request| request.is_inertia_visit()) {
return Redirect::to(url.clone())
.status(409)
.with_header("x-inertia-location", url);
}
Redirect::to(url)
}
pub async fn user(provider: impl Into<Provider>) -> Result<User, Error> {
let provider = provider.into();
let context = Context::expect("laravel::auth::social::user()");
let driver = registration(&context, &provider)?;
if let Some(fake) = Fakes::of(&context).active() {
return fake.user(&provider);
}
let config = context.config();
let credentials = credentials(&config.social, &provider, &driver.label)?;
let (login, code) = callback(&context, &provider, &driver.label)?;
let response = exchange(driver, credentials, &login, &code).await?;
let tokens = Tokens {
label: &driver.label,
client_id: &credentials.client_id,
response: &response,
};
let profile = driver.user(&tokens).await?;
if profile.id.is_empty() {
return Err(Error::Provider(format!("{}'s profile has no ID", driver.label)));
}
Ok(User {
provider,
id: profile.id,
name: profile.name,
nickname: profile.nickname,
email: profile.email,
avatar: profile.avatar,
token: response.token(),
raw: profile.raw,
})
}
fn registration<'a>(context: &'a Context, provider: &Provider) -> Result<&'a Registration, Error> {
context
.part::<Registered>()
.get(provider)
.ok_or_else(|| Error::UnknownProvider(provider.clone()))
}
fn callback(context: &Context, provider: &Provider, label: &str) -> Result<(PendingLogin, String), Error> {
let Some(session) = Session::of(context) else {
panic!("social login needs a session: use it in routes of the `web` group, which start one");
};
let login: Option<PendingLogin> = session.pull(&session_key(provider));
let query: HashMap<String, String> = context.request().map_or_else(HashMap::new, |request| {
url::form_urlencoded::parse(request.query().as_bytes())
.into_owned()
.collect()
});
if let Some(error) = query.get("error") {
if error == "access_denied" {
return Err(Error::Denied);
}
let description = query
.get("error_description")
.map(|description| format!(": {description}"))
.unwrap_or_default();
return Err(Error::Provider(format!(
"{label} returned `{error}` to the callback{description}"
)));
}
let login = login
.filter(|login| {
query
.get("state")
.is_some_and(|state| bool::from(state.as_bytes().ct_eq(login.state.as_bytes())))
})
.ok_or(Error::InvalidState)?;
let code = query.get("code").cloned().ok_or(Error::InvalidState)?;
Ok((login, code))
}
async fn exchange(
driver: &Registration,
credentials: &Credentials,
login: &PendingLogin,
code: &str,
) -> Result<TokenResponse, Error> {
let label = &driver.label;
let response = CLIENT
.post(driver.token_url())
.accept_json()
.form([
("grant_type", "authorization_code"),
("code", code),
("redirect_uri", &login.callback_url),
("client_id", &credentials.client_id),
("client_secret", &credentials.client_secret),
("code_verifier", &login.verifier),
])
.send()
.await
.map_err(|error| Error::Provider(format!("couldn't reach {label}'s token endpoint: {error}")))?;
let body: serde_json::Value = response.json().unwrap_or_default();
if let Some(error) = body.get("error").and_then(serde_json::Value::as_str) {
let description = body
.get("error_description")
.and_then(serde_json::Value::as_str)
.map(|description| format!(": {description}"))
.unwrap_or_default();
return Err(Error::Provider(format!(
"{label} refused the token exchange with HTTP {} and `{error}`{description}",
response.status().as_u16(),
)));
}
if !response.successful() {
return Err(Error::Provider(format!(
"{label} refused the token exchange with HTTP {}: {}",
response.status().as_u16(),
response.text()
)));
}
serde_json::from_value(body)
.map_err(|error| Error::Provider(format!("{label}'s token response is invalid: {error}")))
}
#[derive(Deserialize)]
struct TokenResponse {
access_token: String,
refresh_token: Option<String>,
expires_in: Option<i64>,
scope: Option<String>,
id_token: Option<String>,
}
impl TokenResponse {
fn token(&self) -> Token {
let expires_at = self.expires_in.and_then(|seconds| {
crate::now()
.timestamp()
.checked_add(jiff::SignedDuration::from_secs(seconds))
.ok()
});
Token {
access: self.access_token.clone(),
refresh: self.refresh_token.clone(),
expires_at,
scopes: self
.scope
.as_deref()
.unwrap_or_default()
.split([' ', ','])
.filter(|scope| !scope.is_empty())
.map(str::to_owned)
.collect(),
}
}
}
#[derive(Serialize, Deserialize)]
struct PendingLogin {
state: String,
verifier: String,
callback_url: String,
}
fn credentials<'a>(social: &'a Social, provider: &Provider, label: &str) -> Result<&'a Credentials, Error> {
social.client(provider.as_str()).ok_or_else(|| {
let prefix = Social::env_prefix(provider.as_str());
tracing::warn!("set {prefix}_CLIENT_ID and {prefix}_CLIENT_SECRET to log in with {label}");
Error::NotConfigured(provider.clone())
})
}
fn session_key(provider: &Provider) -> String {
format!("social.{provider}")
}
#[track_caller]
fn callback_url(provider: &Provider, credentials: &Credentials) -> String {
match &credentials.redirect {
Some(redirect) => crate::url::to(redirect),
None => crate::url::to(&format!("/auth/{provider}/callback")),
}
}