use crate::AuthError;
use crate::crypto;
use crate::http::{query_of, with_query};
use crate::provider::Provider;
use crate::session::{Loopback, SessionOptions};
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Redirect {
Auto,
Scheme(String),
Loopback { port: u16, path: String },
Https(String),
}
impl Redirect {
pub fn loopback() -> Redirect {
Redirect::Loopback {
port: 0,
path: "/callback".into(),
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[must_use]
#[expect(
clippy::struct_field_names,
reason = "`client_id` and `client_secret` are the OAuth parameter names"
)]
pub struct Client {
pub(crate) provider: Provider,
pub(crate) client_id: String,
pub(crate) client_secret: Option<String>,
pub(crate) redirect: Redirect,
pub(crate) scopes: Vec<String>,
pub(crate) extra: Vec<(String, String)>,
pub(crate) session: SessionOptions,
pub(crate) pkce: bool,
}
impl Client {
pub fn new(provider: Provider, client_id: impl Into<String>) -> Client {
Client {
provider,
client_id: client_id.into(),
client_secret: None,
redirect: Redirect::Auto,
scopes: vec!["openid".into()],
extra: Vec::new(),
session: SessionOptions::default(),
pkce: true,
}
}
pub fn provider(&self) -> &Provider {
&self.provider
}
pub fn client_id(&self) -> &str {
&self.client_id
}
pub fn redirect(mut self, redirect: Redirect) -> Self {
self.redirect = redirect;
self
}
pub fn scopes<S: Into<String>>(mut self, scopes: impl IntoIterator<Item = S>) -> Self {
self.scopes = scopes.into_iter().map(Into::into).collect();
self
}
pub fn client_secret(mut self, secret: impl Into<String>) -> Self {
self.client_secret = Some(secret.into());
self
}
pub fn param(mut self, name: impl Into<String>, value: impl Into<String>) -> Self {
self.extra.push((name.into(), value.into()));
self
}
pub fn session(mut self, options: SessionOptions) -> Self {
self.session = options;
self
}
pub fn pkce(mut self, on: bool) -> Self {
self.pkce = on;
self
}
pub fn is_openid(&self) -> bool {
self.scopes.iter().any(|s| s == "openid")
}
pub fn start(&self) -> Result<Authorization, AuthError> {
if self.client_id.is_empty() {
return Err(AuthError::InvalidRequest("the client id is empty".into()));
}
self.provider.validate()?;
let reserved = [
"response_type",
"client_id",
"redirect_uri",
"scope",
"state",
"nonce",
"code_challenge",
"code_challenge_method",
];
let endpoint = crate::urls::endpoint(&self.provider.authorization_endpoint)?;
if self
.extra
.iter()
.any(|(key, _)| reserved.contains(&key.as_str()))
|| endpoint
.query_pairs()
.any(|(key, _)| reserved.contains(&key.as_ref()))
{
return Err(AuthError::InvalidRequest(
"authorization parameters cannot override protocol fields".into(),
));
}
let (redirect_uri, loopback) = resolve_redirect(&self.redirect)?;
let state = crypto::random_token(24)?;
let nonce = if self.is_openid() {
Some(crypto::random_token(24)?)
} else {
None
};
let verifier = if self.pkce {
Some(crypto::random_token(48)?)
} else {
None
};
let scope = self.scopes.join(" ");
let mut fields: Vec<(&str, &str)> = vec![
("response_type", "code"),
("client_id", &self.client_id),
("redirect_uri", &redirect_uri),
("scope", &scope),
("state", &state),
];
if let Some(nonce) = &nonce {
fields.push(("nonce", nonce));
}
let challenge = verifier
.as_deref()
.map(|v| crypto::base64url(&crypto::sha256(v.as_bytes())));
if let Some(challenge) = &challenge {
fields.push(("code_challenge", challenge));
fields.push(("code_challenge_method", "S256"));
}
for (k, v) in &self.extra {
fields.push((k, v));
}
let url = with_query(&self.provider.authorization_endpoint, &fields);
Ok(Authorization {
client: self.clone(),
url,
redirect_uri,
state,
nonce,
verifier,
loopback,
})
}
}
pub struct Authorization {
client: Client,
url: String,
redirect_uri: String,
state: String,
nonce: Option<String>,
verifier: Option<String>,
loopback: Option<Loopback>,
}
impl Authorization {
pub(crate) fn validate_client(&self, client: &Client) -> Result<(), AuthError> {
if &self.client != client {
return Err(AuthError::InvalidRequest(
"authorization belongs to a different client configuration".into(),
));
}
Ok(())
}
pub fn url(&self) -> &str {
&self.url
}
pub fn redirect_uri(&self) -> &str {
&self.redirect_uri
}
pub fn state(&self) -> &str {
&self.state
}
pub fn nonce(&self) -> Option<&str> {
self.nonce.as_deref()
}
pub fn verifier(&self) -> Option<&str> {
self.verifier.as_deref()
}
pub fn take_loopback(&mut self) -> Option<Loopback> {
self.loopback.take()
}
pub fn code_from(&self, callback_url: &str) -> Result<String, AuthError> {
if !crate::urls::callback_matches(&self.redirect_uri, callback_url) {
return Err(AuthError::InvalidRequest(
"the callback is not for this request's redirect".into(),
));
}
let query = query_of(callback_url);
let mut names = std::collections::HashSet::new();
if query.iter().any(|(key, _)| !names.insert(key)) {
return Err(AuthError::InvalidRequest(
"duplicate authorization response parameter".into(),
));
}
let get = |name: &str| {
query
.iter()
.find(|(k, _)| k == name)
.map(|(_, v)| v.as_str())
};
match get("state") {
Some(state) if crypto::constant_time_eq(state.as_bytes(), self.state.as_bytes()) => {}
_ => return Err(AuthError::StateMismatch),
}
if let Some(issuer) = get("iss")
&& self.client.provider.issuer.as_deref() != Some(issuer)
{
return Err(AuthError::InvalidRequest(
"authorization response issuer mismatch".into(),
));
}
if get("code").is_some() && get("error").is_some() {
return Err(AuthError::InvalidRequest(
"authorization response contains both code and error".into(),
));
}
if let Some(error) = get("error") {
return Err(AuthError::Provider {
error: error.to_string(),
description: get("error_description").map(str::to_string),
});
}
match get("code") {
Some(code) if !code.is_empty() => Ok(code.to_string()),
_ => Err(AuthError::InvalidRequest(
"the callback carries no code".into(),
)),
}
}
}
fn resolve_redirect(redirect: &Redirect) -> Result<(String, Option<Loopback>), AuthError> {
match redirect {
Redirect::Scheme(url) => {
if !url.contains("://")
|| matches!(
crate::urls::parse(url)?.scheme(),
"http" | "https" | "javascript" | "data" | "file"
)
{
return Err(AuthError::InvalidRequest(
"a scheme redirect is `<scheme>://<path>` with the app's own scheme".into(),
));
}
Ok((url.clone(), None))
}
Redirect::Https(url) => {
if crate::urls::endpoint(url)?.scheme() != "https" {
return Err(AuthError::InvalidRequest(
"an https redirect must start with https://".into(),
));
}
Ok((url.clone(), None))
}
Redirect::Loopback { port, path } => {
let listener = Loopback::bind(*port, path)?;
Ok((listener.redirect_uri().to_string(), Some(listener)))
}
Redirect::Auto => {
if cfg!(target_arch = "wasm32") {
let page = crate::session::page_url().ok_or_else(|| {
AuthError::InvalidRequest(
"the page's URL is unknown; name a Redirect::Https".into(),
)
})?;
return Ok((page, None));
}
if cfg!(any(
target_os = "ios",
target_os = "android",
target_env = "ohos"
)) {
let scheme = app_scheme().ok_or_else(|| {
AuthError::InvalidRequest(
"no app scheme is known (DAY_APP_SCHEME); name a Redirect::Scheme".into(),
)
})?;
return Ok((format!("{scheme}://auth/callback"), None));
}
resolve_redirect(&Redirect::loopback())
}
}
}
pub fn app_scheme() -> Option<String> {
std::env::var("DAY_APP_SCHEME")
.ok()
.filter(|s| !s.is_empty())
.or_else(|| option_env!("DAY_APP_SCHEME").map(str::to_owned))
}
#[cfg(test)]
mod tests {
use super::*;
use std::assert_matches;
#[test]
fn callback_spoofing_and_ambiguous_parameters_are_rejected() {
let client = Client::new(Provider::google(), "fixture")
.redirect(Redirect::Scheme("fixture://auth/callback".into()));
let request = client.start().expect("request");
for suffix in [
"/extra?code=x&state=",
".evil?code=x&state=",
"?code=x&code=y&state=",
"?code=x&error=access_denied&state=",
"?code=x&iss=https%3A%2F%2Fevil.test&state=",
] {
let callback = format!("fixture://auth/callback{suffix}{}", request.state());
assert!(request.code_from(&callback).is_err(), "{suffix}");
}
assert!(request.validate_client(&client.clone()).is_ok());
assert!(
request
.validate_client(&client.clone().param("prompt", "login"))
.is_err()
);
}
#[test]
fn custom_parameters_cannot_replace_protocol_fields() {
let client = Client::new(Provider::google(), "fixture")
.redirect(Redirect::Scheme("fixture://callback".into()));
assert!(client.clone().param("state", "fixed").start().is_err());
assert!(
client
.clone()
.param("code_challenge", "fixed")
.start()
.is_err()
);
assert!(client.param("prompt", "login").start().is_ok());
}
fn client() -> Client {
Client::new(Provider::new("https://p/auth", "https://p/token"), "app")
.redirect(Redirect::Scheme("myapp://auth/callback".into()))
.scopes(["openid", "email"])
.param("prompt", "consent")
}
#[test]
fn the_request_carries_pkce_state_nonce_and_the_extras() {
let a = client().start().expect("start");
let query = query_of(a.url());
let get = |k: &str| query.iter().find(|(n, _)| n == k).map(|(_, v)| v.clone());
assert!(a.url().starts_with("https://p/auth?"));
assert_eq!(get("response_type").as_deref(), Some("code"));
assert_eq!(get("client_id").as_deref(), Some("app"));
assert_eq!(
get("redirect_uri").as_deref(),
Some("myapp://auth/callback")
);
assert_eq!(get("scope").as_deref(), Some("openid email"));
assert_eq!(get("state").as_deref(), Some(a.state()));
assert_eq!(get("nonce").as_deref(), a.nonce());
assert_eq!(get("code_challenge_method").as_deref(), Some("S256"));
assert_eq!(get("prompt").as_deref(), Some("consent"));
let expected =
crypto::base64url(&crypto::sha256(a.verifier().expect("verifier").as_bytes()));
assert_eq!(get("code_challenge").as_deref(), Some(expected.as_str()));
let b = client().start().expect("start");
assert_ne!(a.state(), b.state());
assert_ne!(a.verifier(), b.verifier());
}
#[test]
fn plain_oauth_sends_no_nonce_and_pkce_can_be_turned_off() {
let a = client()
.scopes(["read"])
.pkce(false)
.start()
.expect("start");
assert!(a.nonce().is_none() && a.verifier().is_none());
assert!(!a.url().contains("code_challenge"));
assert!(!a.url().contains("nonce="));
}
#[test]
fn callbacks_are_checked_for_redirect_state_error_and_code() {
let a = client().start().expect("start");
let good = format!("myapp://auth/callback?state={}&code=abc", a.state());
assert_eq!(a.code_from(&good).as_deref(), Ok("abc"));
assert_eq!(
a.code_from("myapp://other?code=abc"),
Err(AuthError::InvalidRequest(
"the callback is not for this request's redirect".into()
))
);
assert_eq!(
a.code_from("myapp://auth/callback?state=wrong&code=abc"),
Err(AuthError::StateMismatch)
);
assert_eq!(
a.code_from("myapp://auth/callback?code=abc"),
Err(AuthError::StateMismatch)
);
let denied = format!(
"myapp://auth/callback?state={}&error=access_denied&error_description=no",
a.state()
);
assert_eq!(
a.code_from(&denied),
Err(AuthError::Provider {
error: "access_denied".into(),
description: Some("no".into())
})
);
let empty = format!("myapp://auth/callback?state={}", a.state());
assert_matches!(a.code_from(&empty), Err(AuthError::InvalidRequest(_)));
}
#[test]
fn redirects_are_validated_and_loopback_binds() {
assert!(
Client::new(Provider::new("https://p/a", "https://p/t"), "app")
.redirect(Redirect::Scheme("https://x".into()))
.start()
.is_err()
);
assert!(
Client::new(Provider::new("https://p/a", "https://p/t"), "app")
.redirect(Redirect::Https("http://x".into()))
.start()
.is_err()
);
assert!(
Client::new(Provider::new("http://p/a", "https://p/t"), "app")
.start()
.is_err()
);
assert!(
Client::new(Provider::new("https://p/a", "https://p/t"), "")
.start()
.is_err()
);
let mut a = Client::new(Provider::new("https://p/a", "https://p/t"), "app")
.redirect(Redirect::loopback())
.start()
.expect("start");
assert!(a.redirect_uri().starts_with("http://127.0.0.1:"));
assert!(a.take_loopback().is_some());
assert!(a.take_loopback().is_none());
}
}