use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use std::time::Duration;
use renox::Config;
use renox::http::Http;
use renox::prelude::*;
use serde::{Deserialize, Serialize};
pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
pub(crate) const TIMEOUT: Duration = Duration::from_secs(10);
pub trait Provider: Send + Sync + 'static {
fn name(&self) -> &str;
fn label(&self) -> &str;
fn credentials(&self) -> &Credentials;
fn authorize_endpoint(&self) -> &str;
fn token_endpoint(&self) -> &str;
fn scopes(&self) -> &[&str];
fn authorize_params(&self) -> Vec<(&str, &str)> {
Vec::new()
}
fn exchange<'a>(
&'a self,
http: &'a Http,
request: TokenRequest,
) -> BoxFuture<'a, Result<Token>> {
Box::pin(exchange_code(http, self.token_endpoint(), request))
}
fn with_config(&self, _config: &Config) -> Option<Arc<dyn Provider>> {
None
}
fn profile<'a>(&'a self, http: &'a Http, token: &'a Token) -> BoxFuture<'a, Result<Profile>>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Refused {
reason: String,
message: String,
}
impl Refused {
pub fn new(reason: impl Into<String>, message: impl Into<String>) -> Self {
Self {
reason: reason.into(),
message: message.into(),
}
}
pub fn reason(&self) -> &str {
&self.reason
}
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for Refused {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "sign-in refused ({}): {}", self.reason, self.message)
}
}
impl std::error::Error for Refused {}
#[derive(Clone)]
pub struct Credentials(Source);
#[derive(Clone)]
enum Source {
Given { id: String, secret: String },
Config(String),
}
impl Credentials {
pub fn new(client_id: impl Into<String>, client_secret: impl Into<String>) -> Self {
Self(Source::Given {
id: client_id.into(),
secret: client_secret.into(),
})
}
pub fn from_config(prefix: impl Into<String>) -> Self {
Self(Source::Config(prefix.into()))
}
pub fn resolve(&self, config: &Config) -> Option<(String, String)> {
match &self.0 {
Source::Given { id, secret } if !id.is_empty() && !secret.is_empty() => {
Some((id.clone(), secret.clone()))
}
Source::Given { .. } => None,
Source::Config(prefix) => Some((
config.var(&format!("{prefix}_CLIENT_ID"))?,
config.var(&format!("{prefix}_CLIENT_SECRET"))?,
)),
}
}
}
impl fmt::Debug for Credentials {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.0 {
Source::Given { id, .. } => write!(f, "Credentials({id}, secret hidden)"),
Source::Config(prefix) => write!(f, "Credentials::from_config({prefix:?})"),
}
}
}
#[non_exhaustive]
pub struct TokenRequest {
pub code: String,
pub redirect_uri: String,
pub code_verifier: String,
pub client_id: String,
pub client_secret: String,
}
impl fmt::Debug for TokenRequest {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("TokenRequest")
.field("redirect_uri", &self.redirect_uri)
.field("client_id", &self.client_id)
.finish_non_exhaustive()
}
}
#[derive(Clone, Deserialize)]
#[non_exhaustive]
pub struct Token {
pub access_token: String,
#[serde(default)]
pub token_type: Option<String>,
#[serde(default)]
pub refresh_token: Option<String>,
#[serde(default)]
pub expires_in: Option<u64>,
#[serde(default)]
pub scope: Option<String>,
#[serde(default)]
pub id_token: Option<String>,
}
impl Token {
pub fn new(access_token: impl Into<String>) -> Self {
Self {
access_token: access_token.into(),
token_type: None,
refresh_token: None,
expires_in: None,
scope: None,
id_token: None,
}
}
}
impl fmt::Debug for Token {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Token")
.field("token_type", &self.token_type)
.field("expires_in", &self.expires_in)
.field("scope", &self.scope)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Default, Serialize)]
#[non_exhaustive]
pub struct Profile {
pub id: String,
pub email: Option<String>,
pub email_verified: bool,
pub name: Option<String>,
pub avatar: Option<String>,
}
impl Profile {
pub fn new(id: impl Into<String>) -> Self {
Self {
id: id.into(),
..Self::default()
}
}
pub fn email(mut self, email: impl Into<String>, verified: bool) -> Self {
self.email = Some(email.into());
self.email_verified = verified;
self
}
pub fn name(mut self, name: Option<String>) -> Self {
self.name = name.filter(|name| !name.trim().is_empty());
self
}
pub fn avatar(mut self, avatar: Option<String>) -> Self {
self.avatar = avatar.filter(|url| !url.is_empty());
self
}
pub fn verified_email(&self) -> Option<&str> {
self.email
.as_deref()
.filter(|email| self.email_verified && !email.is_empty())
}
}
pub async fn exchange_code(http: &Http, endpoint: &str, request: TokenRequest) -> Result<Token> {
let form = [
("grant_type", "authorization_code"),
("code", request.code.as_str()),
("redirect_uri", request.redirect_uri.as_str()),
("client_id", request.client_id.as_str()),
("client_secret", request.client_secret.as_str()),
("code_verifier", request.code_verifier.as_str()),
];
let response = http
.post(endpoint)
.header("accept", "application/json")
.form(&form)
.timeout(TIMEOUT)
.send()
.await?;
let body: renox::serde_json::Value = response.json().unwrap_or_default();
if !response.ok() || body.get("access_token").is_none() {
let error = body
.get("error")
.and_then(|e| e.as_str())
.unwrap_or("no access token");
return Err(renox::anyhow::anyhow!(
"{endpoint}: the code wasn't exchanged ({}: {error})",
response.status()
)
.into());
}
Ok(renox::serde_json::from_value(body)?)
}
pub(crate) async fn get_json<T: serde::de::DeserializeOwned>(
http: &Http,
url: &str,
token: &Token,
accept: &str,
) -> Result<T> {
http.get(url)
.bearer(&token.access_token)
.header("accept", accept)
.timeout(TIMEOUT)
.send()
.await?
.error_for_status()?
.json()
}
#[cfg(test)]
mod debug_tests {
use super::*;
#[test]
fn debug_hides_secrets_codes_and_tokens() {
let given = Credentials::new("client-1", "very-secret");
assert_eq!(format!("{given:?}"), "Credentials(client-1, secret hidden)");
assert_eq!(
given.resolve(&Config::default()),
Some(("client-1".to_owned(), "very-secret".to_owned()))
);
assert_eq!(
Credentials::new("client-1", "").resolve(&Config::default()),
None
);
assert_eq!(
format!("{:?}", Credentials::from_config("GOOGLE")),
"Credentials::from_config(\"GOOGLE\")"
);
let request = TokenRequest {
code: "the-code".into(),
redirect_uri: "https://app.test/auth/google/callback".into(),
code_verifier: "the-verifier".into(),
client_id: "client-1".into(),
client_secret: "very-secret".into(),
};
let shown = format!("{request:?}");
assert!(
shown.contains("client-1") && shown.contains("/callback"),
"{shown}"
);
for hidden in ["the-code", "the-verifier", "very-secret"] {
assert!(!shown.contains(hidden), "{shown}");
}
let mut token = Token::new("access-123");
assert_eq!(token.access_token, "access-123");
assert!(token.refresh_token.is_none() && token.id_token.is_none());
token.refresh_token = Some("refresh-456".into());
token.expires_in = Some(3600);
let shown = format!("{token:?}");
assert!(shown.contains("3600"), "{shown}");
assert!(
!shown.contains("access-123") && !shown.contains("refresh-456"),
"{shown}"
);
}
}