use self::response::OAuthError;
use crate::rocket_framework as rocket;
use crate::rocket_framework::{FromForm, get, routes};
use crate::{
AuthenticatedUser, Error, ErrorKind, MwOAuthClient, MwOAuthConfig, PendingOAuthFlow,
SessionStore, UserProfile,
};
use rocket::fairing::Fairing;
use rocket::http::{Cookie, CookieJar, SameSite, Status};
use rocket::request::{FromRequest, Outcome, Request};
use rocket::response::Redirect;
use rocket::{Build, Rocket};
use serde::Deserialize;
use std::time::{SystemTime, UNIX_EPOCH};
use url::Url;
mod response;
type Result<T, E = Error> = std::result::Result<T, E>;
const AUTH_COOKIE_NAME: &str = "mwoauth_auth";
const FLOW_COOKIE_NAME: &str = "mwoauth_flow";
const REFRESH_MARGIN_SECS: u64 = 60;
#[derive(Deserialize)]
struct RocketConfig {
client_id: String,
client_secret: String,
wiki_url: Url,
#[serde(default)]
redirect_uri: Option<Url>,
}
impl RocketConfig {
fn into_core(self, user_agent: String) -> Result<MwOAuthConfig> {
let config = MwOAuthConfig::confidential(
self.wiki_url,
self.client_id,
self.client_secret,
self.redirect_uri
.clone()
.unwrap_or_else(default_redirect_uri),
user_agent,
)?;
Ok(if self.redirect_uri.is_some() {
config
} else {
config.with_registered_redirect()
})
}
}
fn default_redirect_uri() -> Url {
Url::parse("http://localhost/oauth/callback").expect("static callback URI is valid")
}
#[derive(Clone, Debug)]
pub struct UserGuard(AuthenticatedUser);
#[derive(Clone, Debug)]
pub struct OptionalUserGuard(pub Option<UserGuard>);
impl UserGuard {
pub fn profile(&self) -> &UserProfile {
self.0.profile()
}
pub fn oauth2_token(&self) -> &str {
self.0.token().access_token()
}
}
impl OptionalUserGuard {
pub fn into_option(self) -> Option<UserGuard> {
self.0
}
pub fn as_ref(&self) -> Option<&UserGuard> {
self.0.as_ref()
}
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for OptionalUserGuard {
type Error = Error;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
match UserGuard::from_request(request).await {
Outcome::Success(user) => Outcome::Success(Self(Some(user))),
Outcome::Error((_, Error::NotLoggedIn | Error::SessionExpired)) => {
Outcome::Success(Self(None))
}
Outcome::Error(error) => Outcome::Error(error),
Outcome::Forward(status) => Outcome::Forward(status),
}
}
}
#[rocket::async_trait]
impl<'r> FromRequest<'r> for UserGuard {
type Error = Error;
async fn from_request(request: &'r Request<'_>) -> Outcome<Self, Self::Error> {
let mut session = RocketSession::new(request.cookies());
let user = match session.authenticated_user() {
Ok(Some(user)) => user,
Ok(None) | Err(_) => {
let _ = session.clear_authenticated_user();
return Outcome::Error((Status::Unauthorized, Error::NotLoggedIn));
}
};
let now = unix_timestamp();
if now >= user.session_expires_at() {
let _ = session.clear_authenticated_user();
return Outcome::Error((Status::Unauthorized, Error::SessionExpired));
}
if !is_token_expiring(&user, now) {
return Outcome::Success(Self(user));
}
if user.token().refresh_token().is_none() {
let _ = session.clear_authenticated_user();
return Outcome::Error((Status::Unauthorized, Error::SessionExpired));
}
let Some(client) = request.rocket().state::<MwOAuthClient>() else {
let _ = session.clear_authenticated_user();
return Outcome::Error((Status::Unauthorized, Error::SessionExpired));
};
match client.refresh_authenticated_user(&user).await {
Ok(user) => match session.set_authenticated_user(user.clone()) {
Ok(()) => Outcome::Success(Self(user)),
Err(error) => Outcome::Error((Status::Unauthorized, error)),
},
Err(error) => {
let _ = session.clear_authenticated_user();
let status = match error.kind() {
ErrorKind::Network | ErrorKind::Provider => Status::BadGateway,
ErrorKind::Configuration | ErrorKind::Session => Status::InternalServerError,
ErrorKind::Callback | ErrorKind::Unauthenticated => Status::Unauthorized,
};
Outcome::Error((status, error))
}
}
}
}
fn is_token_expiring(user: &AuthenticatedUser, now: u64) -> bool {
user.token_expires_at()
.is_some_and(|expires_at| now >= expires_at.saturating_sub(REFRESH_MARGIN_SECS))
}
fn unix_timestamp() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
struct RocketSession<'a> {
cookies: &'a CookieJar<'a>,
}
impl<'a> RocketSession<'a> {
fn new(cookies: &'a CookieJar<'a>) -> Self {
Self { cookies }
}
fn private_cookie<T: serde::de::DeserializeOwned>(&self, name: &str) -> Result<Option<T>> {
self.cookies
.get_private(name)
.map(|cookie| serde_json::from_str(cookie.value()).map_err(|_| Error::Session))
.transpose()
}
fn set_private_cookie<T: serde::Serialize>(&self, name: &'static str, value: &T) -> Result<()> {
let value = serde_json::to_string(value).map_err(|_| Error::Session)?;
self.cookies.add_private(
Cookie::build((name, value))
.secure(true)
.http_only(true)
.same_site(SameSite::Lax)
.path("/")
.build(),
);
Ok(())
}
fn remove_private_cookie(&self, name: &'static str) {
self.cookies.remove_private(Cookie::build(name).path("/"));
}
}
impl SessionStore for RocketSession<'_> {
fn pending_flow(&self) -> Result<Option<PendingOAuthFlow>> {
self.private_cookie(FLOW_COOKIE_NAME)
}
fn set_pending_flow(&mut self, flow: PendingOAuthFlow) -> Result<()> {
self.set_private_cookie(FLOW_COOKIE_NAME, &flow)
}
fn take_pending_flow(&mut self) -> Result<Option<PendingOAuthFlow>> {
let flow = self.pending_flow();
self.remove_private_cookie(FLOW_COOKIE_NAME);
flow
}
fn authenticated_user(&self) -> Result<Option<AuthenticatedUser>> {
self.private_cookie(AUTH_COOKIE_NAME)
}
fn set_authenticated_user(&mut self, user: AuthenticatedUser) -> Result<()> {
self.set_private_cookie(AUTH_COOKIE_NAME, &user)
}
fn clear_authenticated_user(&mut self) -> Result<()> {
self.remove_private_cookie(AUTH_COOKIE_NAME);
Ok(())
}
fn clear_pending_flow(&mut self) -> Result<()> {
self.remove_private_cookie(FLOW_COOKIE_NAME);
Ok(())
}
}
#[get("/oauth/login")]
fn login(
client: &rocket::State<MwOAuthClient>,
cookies: &CookieJar<'_>,
) -> Result<Redirect, OAuthError> {
let mut session = RocketSession::new(cookies);
let authorization = client.begin_authorization(&mut session, &[])?;
Ok(Redirect::to(authorization.url.to_string()))
}
#[derive(FromForm)]
struct CallbackQuery<'r> {
code: Option<&'r str>,
state: Option<&'r str>,
error: Option<&'r str>,
}
#[get("/oauth/callback?<query..>")]
async fn callback(
query: CallbackQuery<'_>,
client: &rocket::State<MwOAuthClient>,
cookies: &CookieJar<'_>,
) -> Result<Redirect, OAuthError> {
complete_callback(query, client, cookies).await
}
async fn complete_callback(
query: CallbackQuery<'_>,
client: &MwOAuthClient,
cookies: &CookieJar<'_>,
) -> Result<Redirect, OAuthError> {
let mut session = RocketSession::new(cookies);
if let Some(provider_error) = query.error {
session.clear_pending_flow()?;
return Err(Error::AuthorizationDenied {
error: sanitize_provider_error(provider_error),
}
.into());
}
let (Some(code), Some(state)) = (query.code, query.state) else {
session.clear_pending_flow()?;
return Err(Error::MissingFlowState.into());
};
client
.complete_authorization(&mut session, code, state)
.await?;
Ok(Redirect::to("/"))
}
fn sanitize_provider_error(value: &str) -> String {
let value: String = value
.chars()
.filter(|character| character.is_ascii_alphanumeric() || matches!(character, '_' | '-'))
.take(64)
.collect();
if value.is_empty() {
"unknown_error".to_owned()
} else {
value
}
}
#[get("/oauth/logout")]
fn logout(cookies: &CookieJar<'_>) -> Redirect {
let mut session = RocketSession::new(cookies);
let _ = session.clear();
Redirect::to("/")
}
#[cfg(feature = "legacy-callback")]
#[get("/auth?<query..>")]
async fn legacy_callback(
query: CallbackQuery<'_>,
client: &rocket::State<MwOAuthClient>,
cookies: &CookieJar<'_>,
) -> Result<Redirect, OAuthError> {
complete_callback(query, client, cookies).await
}
pub fn config_from_figment(
figment: &rocket::figment::Figment,
user_agent: impl Into<String>,
) -> Result<MwOAuthConfig> {
#[allow(clippy::result_large_err)]
let config: RocketConfig = figment
.extract_inner("mwoauth")
.or_else(
|_| -> std::result::Result<RocketConfig, rocket::figment::Error> {
Ok(RocketConfig {
client_id: figment.extract_inner("mwoauth_client_id")?,
client_secret: figment.extract_inner("mwoauth_client_secret")?,
wiki_url: figment.extract_inner("mwoauth_wiki_url")?,
redirect_uri: if figment.contains("mwoauth_redirect_uri") {
Some(figment.extract_inner("mwoauth_redirect_uri")?)
} else {
None
},
})
},
)
.map_err(|error| Error::configuration(format!("Rocket OAuth configuration: {error}")))?;
config.into_core(user_agent.into())
}
pub struct RocketOAuth {
client: MwOAuthClient,
}
impl RocketOAuth {
pub fn new(client: MwOAuthClient) -> Self {
Self { client }
}
}
#[rocket::async_trait]
impl Fairing for RocketOAuth {
fn info(&self) -> rocket::fairing::Info {
rocket::fairing::Info {
name: "MediaWiki OAuth2",
kind: rocket::fairing::Kind::Ignite,
}
}
async fn on_ignite(&self, rocket: Rocket<Build>) -> rocket::fairing::Result {
Ok(rocket.manage(self.client.clone()).mount("/", {
#[allow(unused_mut)]
let mut routes = routes![login, callback, logout];
#[cfg(feature = "legacy-callback")]
routes.extend(routes![legacy_callback]);
routes
}))
}
}
#[cfg(test)]
mod tests {
use super::*;
use rocket::figment::Figment;
use rocket::http::{Cookie, SameSite};
use rocket::local::asynchronous::Client;
use rocket::{Build, Rocket};
use std::io;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
#[get("/whoami")]
fn whoami(user: UserGuard) -> String {
format!("{}:{}", user.profile().username(), user.oauth2_token())
}
#[get("/required")]
fn required(_user: UserGuard) -> &'static str {
"ok"
}
#[get("/soft")]
fn soft(user: Option<UserGuard>) -> &'static str {
if user.is_some() {
"authenticated"
} else {
"anonymous"
}
}
#[get("/strict-soft")]
fn strict_soft(user: OptionalUserGuard) -> &'static str {
if user.as_ref().is_some() {
"authenticated"
} else {
"anonymous"
}
}
fn configured_rocket(base_url: &str) -> Rocket<Build> {
configured_rocket_with_ttl(base_url, None)
}
fn test_figment(base_url: &str) -> Figment {
Figment::from(rocket::Config::debug_default())
.merge(("secret_key", "h2nYFY07yiknpofkgwK3EqdwRgOi9P6RmJC3uyCgPeo="))
.merge(("mwoauth.client_id", "client-id"))
.merge(("mwoauth.client_secret", "client-secret"))
.merge(("mwoauth.wiki_url", base_url))
.merge(("mwoauth.redirect_uri", "http://localhost/oauth/callback"))
}
fn configured_rocket_with_ttl(
base_url: &str,
ttl: Option<std::time::Duration>,
) -> Rocket<Build> {
let config = MwOAuthConfig::confidential(
Url::parse(base_url).unwrap(),
"client-id",
"client-secret",
Url::parse("http://localhost/oauth/callback").unwrap(),
"rocket-test/1.0",
)
.unwrap();
let mut client = MwOAuthClient::new(config).unwrap();
if let Some(ttl) = ttl {
client = client.with_flow_ttl(ttl).unwrap();
}
rocket::custom(test_figment(base_url)).attach(RocketOAuth::new(client))
}
fn flat_configured_rocket(base_url: &str) -> Rocket<Build> {
let figment = Figment::from(rocket::Config::debug_default())
.merge(("secret_key", "h2nYFY07yiknpofkgwK3EqdwRgOi9P6RmJC3uyCgPeo="))
.merge(("mwoauth_client_id", "client-id"))
.merge(("mwoauth_client_secret", "client-secret"))
.merge(("mwoauth_wiki_url", base_url));
rocket::custom(figment)
}
#[rocket::async_test]
async fn login_redirect_sets_encrypted_flow_cookie() {
let client = Client::tracked(configured_rocket("https://wiki.test/w/api.php"))
.await
.unwrap();
let response = client.get("/oauth/login").dispatch().await;
assert_eq!(response.status(), Status::SeeOther);
let location = response.headers().get_one("Location").unwrap();
assert!(location.starts_with("https://wiki.test/w/rest.php/oauth2/authorize?"));
assert!(location.contains("code_challenge_method=S256"));
let cookies = client.cookies();
let cookie = cookies.get(AUTH_COOKIE_NAME);
assert!(cookie.is_none());
let flow_cookie = cookies.get(FLOW_COOKIE_NAME).unwrap();
assert_ne!(flow_cookie.value().chars().next(), Some('{'));
assert_eq!(flow_cookie.http_only(), Some(true));
assert_eq!(flow_cookie.secure(), Some(true));
assert_eq!(flow_cookie.same_site(), Some(SameSite::Lax));
}
#[rocket::async_test]
async fn flat_configuration_uses_registered_callback() {
let rocket = flat_configured_rocket("https://wiki.test/w/api.php");
let config = config_from_figment(rocket.figment(), "rocket-test/1.0").unwrap();
assert_eq!(config.client_id, "client-id");
assert_eq!(config.client_secret.as_deref(), Some("client-secret"));
assert!(config.redirect_uri.is_none());
}
#[rocket::async_test]
async fn callback_success_authenticates_guard() {
let (base_url, server) = mock_mediawiki().await;
let rocket = configured_rocket(&base_url).mount("/", routes![whoami]);
let client = Client::tracked(rocket).await.unwrap();
let login = client.get("/oauth/login").dispatch().await;
let location = Url::parse(login.headers().get_one("Location").unwrap()).unwrap();
let state = location
.query_pairs()
.find(|(key, _)| key == "state")
.unwrap()
.1
.into_owned();
let callback = client
.get(format!("/oauth/callback?code=test-code&state={state}"))
.dispatch()
.await;
assert_eq!(callback.status(), Status::SeeOther);
assert_eq!(callback.headers().get_one("Location"), Some("/"));
assert!(client.cookies().get_private(FLOW_COOKIE_NAME).is_none());
assert!(client.cookies().get_private(AUTH_COOKIE_NAME).is_some());
let replay = client
.get(format!("/oauth/callback?code=test-code&state={state}"))
.dispatch()
.await;
assert_eq!(replay.status(), Status::BadRequest);
let response = client.get("/whoami").dispatch().await;
assert_eq!(response.status(), Status::Ok);
assert_eq!(
response.into_string().await.as_deref(),
Some("Example:access-token")
);
let logout = client.get("/oauth/logout").dispatch().await;
assert_eq!(logout.status(), Status::SeeOther);
assert!(client.cookies().get_private(AUTH_COOKIE_NAME).is_none());
assert_eq!(
client.get("/whoami").dispatch().await.status(),
Status::Unauthorized
);
server.await.unwrap().unwrap();
}
#[cfg(feature = "legacy-callback")]
#[rocket::async_test]
async fn legacy_callback_route_is_registered() {
let client = Client::tracked(configured_rocket("https://wiki.test/w/api.php"))
.await
.unwrap();
let response = client.get("/auth?error=access_denied").dispatch().await;
assert_eq!(response.status(), Status::BadRequest);
}
#[rocket::async_test]
async fn callback_failure_consumes_pending_flow() {
let client = Client::tracked(configured_rocket("https://wiki.test/w/api.php"))
.await
.unwrap();
let login = client.get("/oauth/login").dispatch().await;
let location = Url::parse(login.headers().get_one("Location").unwrap()).unwrap();
let state = location
.query_pairs()
.find(|(key, _)| key == "state")
.unwrap()
.1
.into_owned();
let response = client
.get(format!("/oauth/callback?code=test&state={state}x"))
.dispatch()
.await;
assert_eq!(response.status(), Status::BadRequest);
assert!(client.cookies().get_private(FLOW_COOKIE_NAME).is_none());
}
#[rocket::async_test]
async fn expired_and_replayed_callbacks_are_rejected() {
let client = Client::tracked(configured_rocket_with_ttl(
"https://wiki.test/w/api.php",
Some(std::time::Duration::from_secs(1)),
))
.await
.unwrap();
let login = client.get("/oauth/login").dispatch().await;
let location = Url::parse(login.headers().get_one("Location").unwrap()).unwrap();
let state = location
.query_pairs()
.find(|(key, _)| key == "state")
.unwrap()
.1
.into_owned();
tokio::time::sleep(std::time::Duration::from_secs(1)).await;
let callback_uri = format!("/oauth/callback?code=test&state={state}");
assert_eq!(
client.get(&callback_uri).dispatch().await.status(),
Status::BadRequest
);
assert_eq!(
client.get(&callback_uri).dispatch().await.status(),
Status::BadRequest
);
}
#[rocket::async_test]
async fn token_provider_failure_returns_bad_gateway() {
let (base_url, server) = mock_token_failure().await;
let client = Client::tracked(configured_rocket(&base_url)).await.unwrap();
let login = client.get("/oauth/login").dispatch().await;
let location = Url::parse(login.headers().get_one("Location").unwrap()).unwrap();
let state = location
.query_pairs()
.find(|(key, _)| key == "state")
.unwrap()
.1
.into_owned();
let response = client
.get(format!("/oauth/callback?code=test-code&state={state}"))
.dispatch()
.await;
assert_eq!(response.status(), Status::BadGateway);
server.await.unwrap().unwrap();
}
#[rocket::async_test]
async fn network_failure_returns_bad_gateway() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
drop(listener);
let client = Client::tracked(configured_rocket(&format!("http://{address}/w/api.php")))
.await
.unwrap();
let login = client.get("/oauth/login").dispatch().await;
let location = Url::parse(login.headers().get_one("Location").unwrap()).unwrap();
let state = location
.query_pairs()
.find(|(key, _)| key == "state")
.unwrap()
.1
.into_owned();
let response = client
.get(format!("/oauth/callback?code=test-code&state={state}"))
.dispatch()
.await;
assert_eq!(response.status(), Status::BadGateway);
}
#[rocket::async_test]
async fn guard_supports_required_soft_and_malformed_sessions() {
let rocket = configured_rocket("https://wiki.test/w/api.php")
.mount("/", routes![required, soft, strict_soft]);
let client = Client::tracked(rocket).await.unwrap();
assert_eq!(
client.get("/required").dispatch().await.status(),
Status::Unauthorized
);
assert_eq!(
client
.get("/soft")
.dispatch()
.await
.into_string()
.await
.unwrap(),
"anonymous"
);
assert_eq!(
client
.get("/strict-soft")
.dispatch()
.await
.into_string()
.await
.unwrap(),
"anonymous"
);
client.cookies().add_private(
Cookie::build((AUTH_COOKIE_NAME, "not-json"))
.path("/")
.build(),
);
assert_eq!(
client.get("/required").dispatch().await.status(),
Status::Unauthorized
);
assert!(client.cookies().get_private(AUTH_COOKIE_NAME).is_none());
client.cookies().add(
Cookie::build((AUTH_COOKIE_NAME, "forged-cookie"))
.path("/")
.build(),
);
assert_eq!(
client.get("/required").dispatch().await.status(),
Status::Unauthorized
);
}
async fn mock_token_failure() -> (String, tokio::task::JoinHandle<io::Result<()>>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await?;
let mut request = vec![0_u8; 8192];
let _ = stream.read(&mut request).await?;
let body = "provider unavailable";
let response = format!(
"HTTP/1.1 503 Service Unavailable\r\nContent-Type: text/plain\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
stream.write_all(response.as_bytes()).await?;
Ok(())
});
(format!("http://{address}/w/api.php"), server)
}
async fn mock_mediawiki() -> (String, tokio::task::JoinHandle<io::Result<()>>) {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let responses = [
r#"{"access_token":"access-token","refresh_token":"refresh-token","expires_in":3600,"token_type":"Bearer"}"#,
r#"{"sub":"42","username":"Example","blocked":false,"confirmed_email":true,"editcount":10,"email_verified":true,"grants":["basic"],"groups":["user"],"registered":"2020-01-01T00:00:00Z","rights":["read"]}"#,
];
for (index, body) in responses.into_iter().enumerate() {
let (mut stream, _) = listener.accept().await?;
let mut request = vec![0_u8; 8192];
let bytes_read = stream.read(&mut request).await?;
let request = String::from_utf8_lossy(&request[..bytes_read]);
if index == 0 {
assert!(request.starts_with("POST /w/rest.php/oauth2/access_token"));
assert!(request.contains("code=test-code"));
assert!(request.contains("code_verifier="));
} else {
assert!(request.starts_with("GET /w/rest.php/oauth2/resource/profile"));
assert!(
request
.to_ascii_lowercase()
.contains("authorization: bearer access-token")
);
}
let response = format!(
"HTTP/1.1 200 OK\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
body.len()
);
stream.write_all(response.as_bytes()).await?;
}
Ok(())
});
(format!("http://{address}/w/api.php"), server)
}
#[test]
fn compatibility_surface_remains_available() {
let config = MwOAuthConfig::confidential(
Url::parse("https://wiki.test/w/api.php").unwrap(),
"client-id",
"client-secret",
Url::parse("https://app.test/oauth/callback").unwrap(),
"application/1.0",
)
.unwrap();
let _ = RocketOAuth::new(MwOAuthClient::new(config).unwrap());
fn accepts_guard(_guard: UserGuard) {}
let _ = accepts_guard;
}
}