use crate::health::BoxFuture;
use axum::{
Router,
extract::{Path, Query, State},
http::{StatusCode, header},
response::{IntoResponse, Response},
routing::get,
};
use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD as B64};
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::{collections::HashMap, sync::Arc, time::Duration};
use tower_sessions::Session;
const SESSION_KEY: &str = "social_oauth";
#[derive(Debug, Clone, PartialEq)]
pub struct SocialProfile {
pub provider: &'static str,
pub subject: String,
pub email: Option<String>,
pub email_verified: bool,
pub name: Option<String>,
}
#[derive(Debug, thiserror::Error)]
#[error("{0}")]
pub struct SocialError(pub String);
pub trait SocialUsers: Send + Sync + 'static {
fn resolve<'a>(&'a self, profile: &'a SocialProfile)
-> BoxFuture<'a, Result<i64, SocialError>>;
}
#[derive(Clone)]
pub struct GitHub {
pub client_id: String,
pub client_secret: String,
pub authorize_url: String,
pub token_url: String,
pub user_url: String,
pub emails_url: String,
}
#[derive(Clone)]
pub struct Google {
pub client_id: String,
pub client_secret: String,
pub authorize_url: String,
pub token_url: String,
pub userinfo_url: String,
}
impl std::fmt::Debug for GitHub {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("GitHub")
.field("client_id", &self.client_id)
.field("client_secret", &"<redacted>")
.finish_non_exhaustive()
}
}
impl std::fmt::Debug for Google {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Google")
.field("client_id", &self.client_id)
.field("client_secret", &"<redacted>")
.finish_non_exhaustive()
}
}
fn env_pair(prefix: &str) -> Option<(String, String)> {
let get = |k: &str| {
std::env::var(format!("{prefix}_{k}"))
.ok()
.filter(|v| !v.is_empty())
};
Some((get("CLIENT_ID")?, get("CLIENT_SECRET")?))
}
impl GitHub {
pub fn new(id: impl Into<String>, secret: impl Into<String>) -> Self {
GitHub {
client_id: id.into(),
client_secret: secret.into(),
authorize_url: "https://github.com/login/oauth/authorize".into(),
token_url: "https://github.com/login/oauth/access_token".into(),
user_url: "https://api.github.com/user".into(),
emails_url: "https://api.github.com/user/emails".into(),
}
}
pub fn from_env() -> Option<Self> {
env_pair("GITHUB").map(|(i, s)| Self::new(i, s))
}
}
impl Google {
pub fn new(id: impl Into<String>, secret: impl Into<String>) -> Self {
Google {
client_id: id.into(),
client_secret: secret.into(),
authorize_url: "https://accounts.google.com/o/oauth2/v2/auth".into(),
token_url: "https://oauth2.googleapis.com/token".into(),
userinfo_url: "https://openidconnect.googleapis.com/v1/userinfo".into(),
}
}
pub fn from_env() -> Option<Self> {
env_pair("GOOGLE").map(|(i, s)| Self::new(i, s))
}
}
#[derive(Debug, Clone)]
pub struct Social {
github: Option<GitHub>,
google: Option<Google>,
app_url: String,
after_login: String,
}
impl Default for Social {
fn default() -> Self {
Self::new()
}
}
impl Social {
pub fn new() -> Self {
Social {
github: None,
google: None,
app_url: std::env::var("APP_URL").unwrap_or_else(|_| "http://127.0.0.1:3000".into()),
after_login: "/dashboard".into(),
}
}
pub fn github(mut self, p: impl Into<Option<GitHub>>) -> Self {
self.github = p.into();
self
}
pub fn google(mut self, p: impl Into<Option<Google>>) -> Self {
self.google = p.into();
self
}
pub fn providers(&self) -> Vec<&'static str> {
let mut v = Vec::new();
if self.github.is_some() {
v.push("github");
}
if self.google.is_some() {
v.push("google");
}
v
}
pub fn app_url(mut self, url: &str) -> Self {
self.app_url = url.into();
self
}
pub fn after_login(mut self, to: &str) -> Self {
self.after_login = to.into();
self
}
pub fn routes<S: Clone + Send + Sync + 'static>(self, users: impl SocialUsers) -> Router<S> {
let http = reqwest::Client::builder()
.timeout(Duration::from_secs(10))
.connect_timeout(Duration::from_secs(10))
.redirect(reqwest::redirect::Policy::none())
.build()
.expect("reqwest client (rustls) builds");
let inner = Arc::new(Inner {
cfg: self,
users: Box::new(users),
http,
});
Router::new()
.route("/auth/{provider}/redirect", get(start))
.route("/auth/{provider}/callback", get(callback))
.with_state(inner)
}
}
struct Inner {
cfg: Social,
users: Box<dyn SocialUsers>,
http: reqwest::Client,
}
struct Prov<'a> {
name: &'static str,
id: &'a str,
secret: &'a str,
authorize: &'a str,
token: &'a str,
scope: &'static str,
}
impl Inner {
fn prov(&self, name: &str) -> Option<Prov<'_>> {
match (name, &self.cfg.github, &self.cfg.google) {
("github", Some(g), _) => Some(Prov {
name: "github",
id: &g.client_id,
secret: &g.client_secret,
authorize: &g.authorize_url,
token: &g.token_url,
scope: "read:user user:email",
}),
("google", _, Some(g)) => Some(Prov {
name: "google",
id: &g.client_id,
secret: &g.client_secret,
authorize: &g.authorize_url,
token: &g.token_url,
scope: "openid email profile",
}),
_ => None,
}
}
fn redirect_uri(&self, name: &str) -> String {
format!(
"{}/auth/{name}/callback",
self.cfg.app_url.trim_end_matches('/')
)
}
async fn fetch(&self, url: &str, token: &str) -> Result<Value, &'static str> {
let r = self
.http
.get(url)
.bearer_auth(token)
.header(header::ACCEPT, "application/json")
.header(header::USER_AGENT, "ryuk-social")
.send()
.await
.map_err(|_| "userinfo request failed")?;
if !r.status().is_success() {
return Err("userinfo rejected the token");
}
r.json().await.map_err(|_| "userinfo unreadable")
}
async fn profile(
&self,
p: &Prov<'_>,
code: &str,
verifier: &str,
) -> Result<SocialProfile, &'static str> {
let form = url::form_urlencoded::Serializer::new(String::new())
.append_pair("grant_type", "authorization_code")
.append_pair("code", code)
.append_pair("redirect_uri", &self.redirect_uri(p.name))
.append_pair("client_id", p.id)
.append_pair("client_secret", p.secret)
.append_pair("code_verifier", verifier)
.finish();
let res = self
.http
.post(p.token)
.header(header::ACCEPT, "application/json")
.header(header::CONTENT_TYPE, "application/x-www-form-urlencoded")
.body(form)
.send()
.await
.map_err(|_| "token request failed")?;
if !res.status().is_success() {
return Err("token endpoint rejected the code");
}
let body: Value = res.json().await.map_err(|_| "token response unreadable")?;
let token = body["access_token"].as_str().ok_or("no access_token")?;
if let Some(g) = self.cfg.github.as_ref().filter(|_| p.name == "github") {
let u = self.fetch(&g.user_url, token).await?;
let subject = match &u["id"] {
Value::Number(n) => n.to_string(),
Value::String(s) => s.clone(),
_ => return Err("no user id"),
};
let emails = self.fetch(&g.emails_url, token).await?;
let email = emails
.as_array()
.and_then(|a| {
a.iter()
.find(|e| e["primary"] == true && e["verified"] == true)
})
.and_then(|e| e["email"].as_str())
.map(str::to_owned);
let name = u["name"].as_str().or(u["login"].as_str());
Ok(SocialProfile {
provider: "github",
subject,
email_verified: email.is_some(),
email,
name: name.map(str::to_owned),
})
} else if let Some(g) = &self.cfg.google {
let u = self.fetch(&g.userinfo_url, token).await?;
let subject = u["sub"].as_str().ok_or("no sub")?.to_owned();
let verified = u["email_verified"] == true || u["email_verified"] == "true";
let email = u["email"].as_str().map(str::to_owned);
Ok(SocialProfile {
provider: "google",
subject,
email_verified: verified && email.is_some(),
email,
name: u["name"].as_str().map(str::to_owned),
})
} else {
Err("provider disabled")
}
}
}
fn random_b64() -> String {
let b: [u8; 32] = rand::random();
B64.encode(b)
}
fn ct_eq(a: &str, b: &str) -> bool {
a.len() == b.len() && a.bytes().zip(b.bytes()).fold(0u8, |d, (x, y)| d | (x ^ y)) == 0
}
async fn fail(session: &Session, msg: &str) -> Response {
crate::inertia::flash(session, "error", msg).await;
crate::inertia::redirect("/login")
}
async fn start(
State(s): State<Arc<Inner>>,
Path(provider): Path<String>,
session: Session,
) -> Response {
let Some(p) = s.prov(&provider) else {
return StatusCode::NOT_FOUND.into_response();
};
let (state, verifier) = (random_b64(), random_b64());
let challenge = B64.encode(Sha256::digest(verifier.as_bytes()));
let Ok(mut url) = url::Url::parse(p.authorize) else {
tracing::error!(provider = p.name, "social: invalid authorize url");
return fail(&session, "Sign-in is unavailable.").await;
};
url.query_pairs_mut()
.append_pair("response_type", "code")
.append_pair("client_id", p.id)
.append_pair("redirect_uri", &s.redirect_uri(p.name))
.append_pair("scope", p.scope)
.append_pair("state", &state)
.append_pair("code_challenge", &challenge)
.append_pair("code_challenge_method", "S256");
let saved = serde_json::json!({"provider": p.name, "state": state, "verifier": verifier});
if session.insert(SESSION_KEY, saved).await.is_err() {
tracing::error!(provider = p.name, "social: session write failed");
return fail(&session, "Sign-in is unavailable.").await;
}
crate::inertia::redirect(url.as_str())
}
async fn callback(
State(s): State<Arc<Inner>>,
Path(provider): Path<String>,
Query(q): Query<HashMap<String, String>>,
session: Session,
) -> Response {
let Some(p) = s.prov(&provider) else {
return StatusCode::NOT_FOUND.into_response();
};
let saved: Option<Value> = session.remove(SESSION_KEY).await.ok().flatten();
let state_ok = saved.as_ref().is_some_and(|v| {
v["provider"] == p.name
&& q.get("state")
.is_some_and(|got| ct_eq(got, v["state"].as_str().unwrap_or("")))
});
if !state_ok {
tracing::warn!(provider = p.name, "social: state mismatch or missing");
return fail(&session, "Sign-in failed. Please try again.").await;
}
if q.contains_key("error") {
tracing::info!(
provider = p.name,
"social: consent denied or provider error"
);
return fail(&session, "Sign-in was cancelled.").await;
}
let (Some(code), Some(verifier)) = (
q.get("code"),
saved.as_ref().and_then(|v| v["verifier"].as_str()),
) else {
return fail(&session, "Sign-in failed. Please try again.").await;
};
let profile = match s.profile(&p, code, verifier).await {
Ok(pr) => pr,
Err(why) => {
tracing::warn!(provider = p.name, "social: {why}");
return fail(&session, "Sign-in failed. Please try again.").await;
}
};
let uid = match s.users.resolve(&profile).await {
Ok(uid) => uid,
Err(e) => {
tracing::warn!(provider = p.name, "social: login refused: {e}");
return fail(&session, "We could not sign you in with that account.").await;
}
};
if crate::auth::login(&session, uid).await.is_err() {
tracing::error!(provider = p.name, "social: session login failed");
return fail(&session, "Sign-in failed. Please try again.").await;
}
crate::inertia::flash(&session, "success", "Signed in.").await;
crate::inertia::redirect(&s.cfg.after_login)
}
#[cfg(test)]
mod tests {
#[test]
fn debug_never_prints_client_secrets_and_providers_lists_names() {
let s = Social::new()
.github(GitHub::new("gh-id", "gh-SECRET-value"))
.google(Google::new("g-id", "goog-SECRET-value"));
let shown = format!(
"{s:?} {:?} {:?}",
GitHub::new("a", "gh-SECRET-value"),
Google::new("b", "goog-SECRET-value")
);
assert!(!shown.contains("SECRET-value"), "{shown}");
assert_eq!(s.providers(), vec!["github", "google"]);
assert!(Social::new().providers().is_empty());
assert_eq!(
Social::new().github(GitHub::new("i", "s")).providers(),
vec!["github"]
);
}
use super::*;
use axum::{body::Body, http::HeaderMap, http::Request};
use std::sync::Mutex;
use tower::ServiceExt;
#[derive(Default)]
struct Mock {
challenges: Mutex<HashMap<String, String>>, verified: bool,
token_fails: bool,
deny: bool,
}
type M = Arc<Mock>;
const SECRET: &str = "sek-ret-value";
const TOKEN: &str = "tok-en-value";
async fn authorize(State(m): State<M>, Query(q): Query<HashMap<String, String>>) -> Response {
let (st, redir) = (&q["state"], &q["redirect_uri"]);
assert_eq!(q["code_challenge_method"], "S256");
let loc = if m.deny {
format!("{redir}?error=access_denied&state={st}")
} else {
let mut c = m.challenges.lock().unwrap();
let code = format!("code{}", c.len());
c.insert(code.clone(), q["code_challenge"].clone());
format!("{redir}?code={code}&state={st}")
};
(StatusCode::SEE_OTHER, [(header::LOCATION, loc)]).into_response()
}
async fn token(
State(m): State<M>,
axum::Form(f): axum::Form<HashMap<String, String>>,
) -> Response {
let chal = m.challenges.lock().unwrap().remove(&f["code"]); let ok = !m.token_fails
&& f["client_secret"] == SECRET
&& chal.is_some_and(|c| c == B64.encode(Sha256::digest(f["code_verifier"].as_bytes())));
if ok {
axum::Json(serde_json::json!({"access_token": TOKEN})).into_response()
} else {
(StatusCode::BAD_REQUEST, "secret provider error body").into_response()
}
}
fn authed(h: &HeaderMap) -> bool {
h.get(header::AUTHORIZATION)
.is_some_and(|v| v == &format!("Bearer {TOKEN}"))
}
async fn mock(m: M) -> String {
let app = Router::new()
.route("/authorize", get(authorize))
.route("/token", axum::routing::post(token))
.route(
"/user",
get(|h: HeaderMap| async move {
if authed(&h) {
axum::Json(serde_json::json!({"id": 7, "login": "octo"})).into_response()
} else {
StatusCode::UNAUTHORIZED.into_response()
}
}),
)
.route(
"/emails",
get(|State(m): State<M>, h: HeaderMap| async move {
if !authed(&h) {
return StatusCode::UNAUTHORIZED.into_response();
}
axum::Json(serde_json::json!([
{"email": "other@x.test", "primary": false, "verified": true},
{"email": "me@x.test", "primary": true, "verified": m.verified}
]))
.into_response()
}),
)
.route(
"/userinfo",
get(|State(m): State<M>, h: HeaderMap| async move {
if !authed(&h) {
return StatusCode::UNAUTHORIZED.into_response();
}
axum::Json(serde_json::json!({"sub": "g1", "email": "me@x.test",
"email_verified": m.verified, "name": "Gee"}))
.into_response()
}),
)
.with_state(m);
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let base = format!("http://{}", l.local_addr().unwrap());
tokio::spawn(async move { axum::serve(l, app).await.unwrap() });
base
}
struct Users(Arc<Mutex<Vec<SocialProfile>>>);
impl SocialUsers for Users {
fn resolve<'a>(&'a self, p: &'a SocialProfile) -> BoxFuture<'a, Result<i64, SocialError>> {
Box::pin(async move {
self.0.lock().unwrap().push(p.clone());
Ok(42)
})
}
}
struct Env {
app: Router,
base: String,
seen: Arc<Mutex<Vec<SocialProfile>>>,
cookie: String,
http: reqwest::Client,
}
async fn env(m: Mock) -> Env {
let base = mock(Arc::new(m)).await;
let mut gh = GitHub::new("cid", SECRET);
gh.authorize_url = format!("{base}/authorize");
gh.token_url = format!("{base}/token");
gh.user_url = format!("{base}/user");
gh.emails_url = format!("{base}/emails");
let mut gg = Google::new("gid", SECRET);
gg.authorize_url = format!("{base}/authorize");
gg.token_url = format!("{base}/token");
gg.userinfo_url = format!("{base}/userinfo");
let seen = Arc::new(Mutex::new(vec![]));
let social = Social::new()
.app_url("http://app.test")
.github(gh)
.google(gg);
let app = Router::new()
.merge(social.routes(Users(seen.clone())))
.layer(crate::session::session_layer());
let http = reqwest::Client::builder()
.redirect(reqwest::redirect::Policy::none())
.build()
.unwrap();
Env {
app,
base,
seen,
cookie: String::new(),
http,
}
}
impl Env {
async fn get(&mut self, uri: &str) -> (StatusCode, String) {
let mut r = Request::get(uri);
if !self.cookie.is_empty() {
r = r.header(header::COOKIE, &self.cookie);
}
let res = self
.app
.clone()
.oneshot(r.body(Body::empty()).unwrap())
.await
.unwrap();
if let Some(c) = res.headers().get(header::SET_COOKIE) {
self.cookie = c.to_str().unwrap().split(';').next().unwrap().to_owned();
}
let loc = res
.headers()
.get(header::LOCATION)
.map(|v| v.to_str().unwrap().to_owned())
.unwrap_or_default();
(res.status(), loc)
}
async fn authorize(&mut self, provider: &str) -> String {
let (_, loc) = self.get(&format!("/auth/{provider}/redirect")).await;
assert!(loc.starts_with(&self.base), "{loc}");
let res = self.http.get(&loc).send().await.unwrap();
let back = res.headers()[header::LOCATION].to_str().unwrap().to_owned();
back.strip_prefix("http://app.test").unwrap().to_owned()
}
}
#[tokio::test]
async fn happy_path_github_with_pkce_and_secret() {
let mut e = env(Mock {
verified: true,
..Default::default()
})
.await;
let cb = e.authorize("github").await;
assert_eq!(
e.get(&cb).await,
(StatusCode::SEE_OTHER, "/dashboard".into())
);
let seen = e.seen.lock().unwrap();
assert_eq!(seen.len(), 1);
assert_eq!(seen[0].subject, "7");
assert_eq!(seen[0].email.as_deref(), Some("me@x.test"));
assert!(seen[0].email_verified);
}
#[tokio::test]
async fn happy_path_google() {
let mut e = env(Mock {
verified: true,
..Default::default()
})
.await;
let cb = e.authorize("google").await;
assert_eq!(e.get(&cb).await.1, "/dashboard");
let seen = e.seen.lock().unwrap();
assert_eq!(
(
seen[0].provider,
seen[0].subject.as_str(),
seen[0].email_verified
),
("google", "g1", true)
);
}
#[tokio::test]
async fn unverified_email_is_reported_unverified() {
let mut e = env(Mock::default()).await;
let cb = e.authorize("github").await;
assert_eq!(e.get(&cb).await.1, "/dashboard");
let cb = e.authorize("google").await;
e.get(&cb).await;
let seen = e.seen.lock().unwrap();
assert_eq!(seen[0].email, None); assert!(!seen[0].email_verified && !seen[1].email_verified);
}
#[tokio::test]
async fn state_mismatch_replay_denied_and_provider_error_go_to_login() {
let mut e = env(Mock {
verified: true,
..Default::default()
})
.await;
let cb = e.authorize("github").await;
assert_eq!(e.get(&cb.replace("state=", "state=x")).await.1, "/login");
assert_eq!(e.get(&cb).await.1, "/login");
let cb = e.authorize("github").await;
assert_eq!(e.get(&cb).await.1, "/dashboard");
assert_eq!(e.get(&cb).await.1, "/login");
assert_eq!(e.seen.lock().unwrap().len(), 1);
let mut fresh = env(Mock::default()).await;
assert_eq!(
fresh.get("/auth/github/callback?code=a&state=b").await.1,
"/login"
);
let mut d = env(Mock {
deny: true,
..Default::default()
})
.await;
let cb = d.authorize("github").await;
assert_eq!(d.get(&cb).await.1, "/login");
let mut p = env(Mock {
token_fails: true,
..Default::default()
})
.await;
let cb = p.authorize("google").await;
assert_eq!(
p.get(&cb).await,
(StatusCode::SEE_OTHER, "/login".to_string())
);
assert!(p.seen.lock().unwrap().is_empty());
}
#[tokio::test]
async fn unknown_provider_is_404() {
let mut e = env(Mock::default()).await;
assert_eq!(
e.get("/auth/myspace/redirect").await.0,
StatusCode::NOT_FOUND
);
assert_eq!(
e.get("/auth/myspace/callback").await.0,
StatusCode::NOT_FOUND
);
}
#[tokio::test]
async fn redirect_url_is_well_formed() {
let mut e = env(Mock::default()).await;
let (st, loc) = e.get("/auth/github/redirect").await;
assert_eq!(st, StatusCode::SEE_OTHER);
let q: HashMap<_, _> = url::Url::parse(&loc)
.unwrap()
.query_pairs()
.into_owned()
.collect();
assert_eq!(q["redirect_uri"], "http://app.test/auth/github/callback");
assert_eq!(q["client_id"], "cid");
assert_eq!(q["state"].len(), 43);
assert!(!loc.contains(SECRET));
}
#[derive(Clone, Default)]
struct Buf(Arc<Mutex<Vec<u8>>>);
impl std::io::Write for Buf {
fn write(&mut self, b: &[u8]) -> std::io::Result<usize> {
self.0.lock().unwrap().extend_from_slice(b);
Ok(b.len())
}
fn flush(&mut self) -> std::io::Result<()> {
Ok(())
}
}
impl<'a> tracing_subscriber::fmt::MakeWriter<'a> for Buf {
type Writer = Buf;
fn make_writer(&'a self) -> Buf {
self.clone()
}
}
#[tokio::test]
async fn secrets_never_logged() {
let buf = Buf::default();
let _g = tracing::subscriber::set_default(
tracing_subscriber::fmt()
.with_writer(buf.clone())
.with_max_level(tracing::Level::TRACE)
.finish(),
);
for m in [
Mock {
token_fails: true,
..Default::default()
},
Mock {
verified: true,
..Default::default()
},
] {
let mut e = env(m).await;
let cb = e.authorize("github").await;
e.get(&cb).await;
e.get(&cb).await; e.get("/auth/github/callback?code=zzcode&state=bad").await;
}
let logs = String::from_utf8(buf.0.lock().unwrap().clone()).unwrap();
assert!(logs.contains("social:"), "expected social logs: {logs}");
for secret in [
SECRET,
TOKEN,
"zzcode",
"code0",
"secret provider error body",
"state=",
] {
assert!(!logs.contains(secret), "{secret} leaked: {logs}");
}
}
}