use std::{sync::Arc, time::Duration};
use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
use serde::de::DeserializeOwned;
use serde_json::{Value, json};
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq as _;
use url::Url;
use crate::transport::{DefaultTransport, MAX_BODY, timeout, too_large};
use crate::{
CurrentUser, HostedNavigation, HttpMethod, HttpRequest, JwksDocument, OwlAuthError,
PendingLogin, PublicApplicationConfig, SessionTokens, Transport, ValidatedCallback,
};
#[derive(Debug, Clone)]
pub struct ClientConfig {
pub base_url: String,
pub project_public_id: String,
pub application_id: String,
pub publishable_key: String,
pub allow_insecure_http: bool,
pub timeout: Duration,
}
impl ClientConfig {
#[must_use]
pub fn new(
base_url: &str,
project_public_id: &str,
application_id: &str,
publishable_key: &str,
) -> Self {
Self {
base_url: base_url.into(),
project_public_id: project_public_id.into(),
application_id: application_id.into(),
publishable_key: publishable_key.into(),
allow_insecure_http: false,
timeout: Duration::from_secs(10),
}
}
}
#[derive(Clone)]
pub struct Client {
config: ClientConfig,
base: Url,
transport: Arc<dyn Transport>,
}
impl Client {
pub fn new(config: ClientConfig) -> Result<Self, OwlAuthError> {
Self::with_transport(config, Arc::new(DefaultTransport::new()?))
}
pub fn with_transport(
config: ClientConfig,
transport: Arc<dyn Transport>,
) -> Result<Self, OwlAuthError> {
let invalid = || {
local(
"invalid_configuration",
"Invalid Runtime client configuration",
)
};
let base = secure_url(&config.base_url, config.allow_insecure_http).ok_or_else(invalid)?;
if base.query().is_some()
|| config.project_public_id.is_empty()
|| !config
.project_public_id
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
|| config.application_id.is_empty()
|| config.publishable_key.is_empty()
|| config.timeout.is_zero()
|| config.timeout > Duration::from_millis(2_147_483_647)
{
return Err(invalid());
}
Ok(Self {
config,
base,
transport,
})
}
pub async fn get_config(&self) -> Result<PublicApplicationConfig, OwlAuthError> {
let mut url = self.auth("config");
url.query_pairs_mut()
.append_pair("application_id", &self.config.application_id);
let config: PublicApplicationConfig = self.json(url, 200, None, None).await?;
self.check_binding(&config.project_id, &config.application_id)?;
Ok(config)
}
pub async fn get_jwks(&self) -> Result<JwksDocument, OwlAuthError> {
self.json(
self.route(&format!(
"/projects/{}/.well-known/jwks.json",
self.config.project_public_id
)),
200,
None,
None,
)
.await
}
pub async fn start_login(&self, redirect_uri: &str) -> Result<PendingLogin, OwlAuthError> {
self.redirect(redirect_uri)?;
let state = nonce()?;
let pkce_verifier = nonce()?;
let result = self
.navigation(
"login/start",
json!({
"application_id": self.config.application_id,
"publishable_key": self.config.publishable_key,
"redirect_uri": redirect_uri,
"pkce_challenge": pkce_challenge(&pkce_verifier),
"state": state,
}),
None,
)
.await?;
Ok(PendingLogin {
hosted_url: result.hosted_url,
expires_at: result.expires_at,
redirect_uri: redirect_uri.into(),
state,
pkce_verifier,
})
}
pub async fn exchange_handoff(
&self,
handoff_code: &str,
pkce_verifier: &str,
) -> Result<SessionTokens, OwlAuthError> {
self.json(
self.auth("handoff/exchange"),
200,
Some(json!({
"application_id": self.config.application_id,
"handoff_code": handoff_code, "pkce_verifier": pkce_verifier,
})),
None,
)
.await
}
pub async fn complete_login(
&self,
callback: &str,
pending: &PendingLogin,
) -> Result<SessionTokens, OwlAuthError> {
let validated = validate_callback(callback, pending)?;
self.exchange_handoff(&validated.handoff_code, &pending.pkce_verifier)
.await
}
pub async fn refresh(&self, refresh_token: &str) -> Result<SessionTokens, OwlAuthError> {
self.json(
self.auth("sessions/refresh"),
200,
Some(json!({
"application_id": self.config.application_id, "refresh_token": refresh_token,
})),
None,
)
.await
}
pub async fn current_user(&self, access_token: &str) -> Result<CurrentUser, OwlAuthError> {
let user: CurrentUser = self
.json(self.auth("users/me"), 200, None, Some(access_token))
.await?;
self.check_binding(&user.project_id, &user.application_id)?;
Ok(user)
}
pub async fn logout(&self, access_token: &str) -> Result<(), OwlAuthError> {
self.request(self.auth("sessions/logout"), 204, None, Some(access_token))
.await?;
Ok(())
}
pub async fn prepare_browser_logout(
&self,
access_token: &str,
redirect_uri: &str,
) -> Result<HostedNavigation, OwlAuthError> {
self.redirect(redirect_uri)?;
self.navigation(
"browser-logout/prepare",
json!({"redirect_uri": redirect_uri}),
Some(access_token),
)
.await
}
fn check_binding(&self, project_id: &str, application_id: &str) -> Result<(), OwlAuthError> {
if project_id != self.config.project_public_id
|| application_id != self.config.application_id
{
return Err(invalid_response(200));
}
Ok(())
}
fn auth(&self, action: &str) -> Url {
self.route(&format!(
"/v1/projects/{}/auth/{action}",
self.config.project_public_id
))
}
fn route(&self, suffix: &str) -> Url {
let mut target = self.base.clone();
target.set_path(&format!(
"{}{suffix}",
self.base.path().trim_end_matches('/')
));
target
}
fn redirect(&self, value: &str) -> Result<(), OwlAuthError> {
let invalid = || local("invalid_configuration", "Invalid application redirect URI");
let allow_http = self.config.allow_insecure_http && self.base.scheme() == "http";
let url = secure_url(value, allow_http).ok_or_else(invalid)?;
if url
.query_pairs()
.any(|(key, _)| matches!(key.as_ref(), "state" | "handoff_code"))
{
return Err(invalid());
}
Ok(())
}
async fn navigation(
&self,
action: &str,
body: Value,
bearer: Option<&str>,
) -> Result<HostedNavigation, OwlAuthError> {
let result: HostedNavigation = self
.json(self.auth(action), 201, Some(body), bearer)
.await?;
let safe = secure_url(&result.hosted_url, self.config.allow_insecure_http);
if !safe.is_some_and(|url| url.origin() == self.base.origin()) {
return Err(OwlAuthError::new(
"invalid_response",
"Invalid Runtime hosted URL",
Some(201),
));
}
Ok(result)
}
async fn json<T: DeserializeOwned>(
&self,
url: Url,
expected: u16,
body: Option<Value>,
bearer: Option<&str>,
) -> Result<T, OwlAuthError> {
let bytes = self.request(url, expected, body.as_ref(), bearer).await?;
serde_json::from_slice(&bytes).map_err(|_| invalid_response(expected))
}
async fn request(
&self,
url: Url,
expected: u16,
body: Option<&Value>,
bearer: Option<&str>,
) -> Result<Vec<u8>, OwlAuthError> {
let request = HttpRequest {
method: if body.is_some() || expected == 204 {
HttpMethod::Post
} else {
HttpMethod::Get
},
url,
bearer: bearer.map(str::to_owned),
body: body.map(|v| v.to_string().into_bytes()),
timeout: self.config.timeout,
};
let response = tokio::time::timeout(self.config.timeout, self.transport.send(request))
.await
.map_err(|_| timeout())??;
let status = response.status;
if (300..400).contains(&status) {
return Err(OwlAuthError::new(
"redirect_rejected",
"Runtime API redirect rejected",
Some(status),
));
}
if response.body.len() > MAX_BODY {
return Err(too_large(status));
}
if status == expected {
return Ok(response.body);
}
if (200..300).contains(&status) {
return Err(invalid_response(status));
}
let mut secrets: Vec<_> = bearer.into_iter().collect();
if let Some(body) = body {
secrets.extend(
["refresh_token", "pkce_verifier", "handoff_code", "state"]
.iter()
.filter_map(|k| body[k].as_str()),
);
}
Err(OwlAuthError::http(status, &response.body, &secrets))
}
}
#[must_use]
pub fn pkce_challenge(verifier: &str) -> String {
URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
}
pub fn validate_callback(
callback: &str,
pending: &PendingLogin,
) -> Result<ValidatedCallback, OwlAuthError> {
let invalid = || local("invalid_callback", "Invalid login callback");
if callback.chars().any(unsafe_url_char) {
return Err(invalid());
}
let actual;
let query = if let Some(query) = callback.strip_prefix('?') {
query
} else if callback
.split_once('=')
.is_some_and(|(key, _)| !key.is_empty() && !key.contains([':', '/', '?']))
{
callback
} else {
actual = absolute_url(callback).ok_or_else(invalid)?;
let expected = absolute_url(&pending.redirect_uri).ok_or_else(invalid)?;
if actual.origin() != expected.origin() || actual.path() != expected.path() {
return Err(invalid());
}
actual.query().unwrap_or_default()
};
let mut state = None;
let mut code = None;
let mut errors = 0;
let mut has_error = false;
for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
match key.as_ref() {
"state" if state.is_none() => state = Some(value),
"handoff_code" if code.is_none() => code = Some(value),
"state" | "handoff_code" => return Err(invalid()),
"error" => {
errors += 1;
has_error = !value.is_empty();
}
_ => {}
}
}
let state = state.filter(|v| !v.is_empty()).ok_or_else(invalid)?;
if !bool::from(pending.state.as_bytes().ct_eq(state.as_bytes())) {
return Err(local(
"state_mismatch",
"Login callback state does not match",
));
}
match code {
Some(value) if !value.is_empty() => Ok(ValidatedCallback {
handoff_code: value.into_owned(),
}),
None if errors == 1 && has_error => {
Err(local("callback_error", "Login callback reported an error"))
}
_ => Err(invalid()),
}
}
fn nonce() -> Result<String, OwlAuthError> {
let mut bytes = [0; 32];
getrandom::fill(&mut bytes)
.map_err(|_| local("entropy_unavailable", "Secure randomness unavailable"))?;
Ok(URL_SAFE_NO_PAD.encode(bytes))
}
fn unsafe_url_char(value: char) -> bool {
value.is_whitespace() || value.is_ascii_control() || matches!(value, '\\' | '#')
}
fn absolute_url(value: &str) -> Option<Url> {
let (scheme, rest) = value.split_once("://")?;
let authority = rest.split(['/', '?']).next()?;
if !(scheme.eq_ignore_ascii_case("https") || scheme.eq_ignore_ascii_case("http"))
|| authority.is_empty()
|| authority.contains('@')
|| value.chars().any(unsafe_url_char)
{
return None;
}
Url::parse(value).ok().filter(|url| url.port() != Some(0))
}
fn secure_url(value: &str, allow_http: bool) -> Option<Url> {
let url = absolute_url(value)?;
if url.scheme() == "https" {
return Some(url);
}
let authority = value.split_once("://")?.1.split(['/', '?']).next()?;
let host = if let Some((_, suffix)) = authority.split_once(']') {
authority.strip_suffix(suffix)?
} else {
authority.split(':').next()?
};
(allow_http
&& (host.eq_ignore_ascii_case("localhost") || matches!(host, "127.0.0.1" | "[::1]")))
.then_some(url)
}
fn local(code: &str, message: &str) -> OwlAuthError {
OwlAuthError::new(code, message, None)
}
fn invalid_response(status: u16) -> OwlAuthError {
OwlAuthError::new("invalid_response", "Invalid Runtime response", Some(status))
}