1use std::{sync::Arc, time::Duration};
2
3use base64::{Engine as _, engine::general_purpose::URL_SAFE_NO_PAD};
4use serde::de::DeserializeOwned;
5use serde_json::{Value, json};
6use sha2::{Digest, Sha256};
7use subtle::ConstantTimeEq as _;
8use url::Url;
9
10use crate::transport::{DefaultTransport, MAX_BODY, timeout, too_large};
11use crate::{
12 CurrentUser, HostedNavigation, HttpMethod, HttpRequest, JwksDocument, OwlAuthError,
13 PendingLogin, PublicApplicationConfig, SessionTokens, Transport, ValidatedCallback,
14};
15
16#[derive(Debug, Clone)]
18pub struct ClientConfig {
19 pub base_url: String,
20 pub project_public_id: String,
21 pub application_id: String,
22 pub publishable_key: String,
23 pub allow_insecure_http: bool,
24 pub timeout: Duration,
25}
26
27impl ClientConfig {
28 #[must_use]
29 pub fn new(
30 base_url: &str,
31 project_public_id: &str,
32 application_id: &str,
33 publishable_key: &str,
34 ) -> Self {
35 Self {
36 base_url: base_url.into(),
37 project_public_id: project_public_id.into(),
38 application_id: application_id.into(),
39 publishable_key: publishable_key.into(),
40 allow_insecure_http: false,
41 timeout: Duration::from_secs(10),
42 }
43 }
44}
45
46#[derive(Clone)]
48pub struct Client {
49 config: ClientConfig,
50 base: Url,
51 transport: Arc<dyn Transport>,
52}
53
54impl Client {
55 pub fn new(config: ClientConfig) -> Result<Self, OwlAuthError> {
60 Self::with_transport(config, Arc::new(DefaultTransport::new()?))
61 }
62
63 pub fn with_transport(
68 config: ClientConfig,
69 transport: Arc<dyn Transport>,
70 ) -> Result<Self, OwlAuthError> {
71 let invalid = || {
72 local(
73 "invalid_configuration",
74 "Invalid Runtime client configuration",
75 )
76 };
77 let base = secure_url(&config.base_url, config.allow_insecure_http).ok_or_else(invalid)?;
78 if base.query().is_some()
79 || config.project_public_id.is_empty()
80 || !config
81 .project_public_id
82 .bytes()
83 .all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
84 || config.application_id.is_empty()
85 || config.publishable_key.is_empty()
86 || config.timeout.is_zero()
87 || config.timeout > Duration::from_millis(2_147_483_647)
88 {
89 return Err(invalid());
90 }
91 Ok(Self {
92 config,
93 base,
94 transport,
95 })
96 }
97
98 pub async fn get_config(&self) -> Result<PublicApplicationConfig, OwlAuthError> {
103 let mut url = self.auth("config");
104 url.query_pairs_mut()
105 .append_pair("application_id", &self.config.application_id);
106 let config: PublicApplicationConfig = self.json(url, 200, None, None).await?;
107 self.check_binding(&config.project_id, &config.application_id)?;
108 Ok(config)
109 }
110
111 pub async fn get_jwks(&self) -> Result<JwksDocument, OwlAuthError> {
116 self.json(
117 self.route(&format!(
118 "/projects/{}/.well-known/jwks.json",
119 self.config.project_public_id
120 )),
121 200,
122 None,
123 None,
124 )
125 .await
126 }
127
128 pub async fn start_login(&self, redirect_uri: &str) -> Result<PendingLogin, OwlAuthError> {
133 self.redirect(redirect_uri)?;
134 let state = nonce()?;
135 let pkce_verifier = nonce()?;
136 let result = self
137 .navigation(
138 "login/start",
139 json!({
140 "application_id": self.config.application_id,
141 "publishable_key": self.config.publishable_key,
142 "redirect_uri": redirect_uri,
143 "pkce_challenge": pkce_challenge(&pkce_verifier),
144 "state": state,
145 }),
146 None,
147 )
148 .await?;
149 Ok(PendingLogin {
150 hosted_url: result.hosted_url,
151 expires_at: result.expires_at,
152 redirect_uri: redirect_uri.into(),
153 state,
154 pkce_verifier,
155 })
156 }
157
158 pub async fn exchange_handoff(
163 &self,
164 handoff_code: &str,
165 pkce_verifier: &str,
166 ) -> Result<SessionTokens, OwlAuthError> {
167 self.json(
168 self.auth("handoff/exchange"),
169 200,
170 Some(json!({
171 "application_id": self.config.application_id,
172 "handoff_code": handoff_code, "pkce_verifier": pkce_verifier,
173 })),
174 None,
175 )
176 .await
177 }
178
179 pub async fn complete_login(
184 &self,
185 callback: &str,
186 pending: &PendingLogin,
187 ) -> Result<SessionTokens, OwlAuthError> {
188 let validated = validate_callback(callback, pending)?;
189 self.exchange_handoff(&validated.handoff_code, &pending.pkce_verifier)
190 .await
191 }
192
193 pub async fn refresh(&self, refresh_token: &str) -> Result<SessionTokens, OwlAuthError> {
198 self.json(
199 self.auth("sessions/refresh"),
200 200,
201 Some(json!({
202 "application_id": self.config.application_id, "refresh_token": refresh_token,
203 })),
204 None,
205 )
206 .await
207 }
208
209 pub async fn current_user(&self, access_token: &str) -> Result<CurrentUser, OwlAuthError> {
214 let user: CurrentUser = self
215 .json(self.auth("users/me"), 200, None, Some(access_token))
216 .await?;
217 self.check_binding(&user.project_id, &user.application_id)?;
218 Ok(user)
219 }
220
221 pub async fn logout(&self, access_token: &str) -> Result<(), OwlAuthError> {
226 self.request(self.auth("sessions/logout"), 204, None, Some(access_token))
227 .await?;
228 Ok(())
229 }
230
231 pub async fn prepare_browser_logout(
236 &self,
237 access_token: &str,
238 redirect_uri: &str,
239 ) -> Result<HostedNavigation, OwlAuthError> {
240 self.redirect(redirect_uri)?;
241 self.navigation(
242 "browser-logout/prepare",
243 json!({"redirect_uri": redirect_uri}),
244 Some(access_token),
245 )
246 .await
247 }
248
249 fn check_binding(&self, project_id: &str, application_id: &str) -> Result<(), OwlAuthError> {
250 if project_id != self.config.project_public_id
251 || application_id != self.config.application_id
252 {
253 return Err(invalid_response(200));
254 }
255 Ok(())
256 }
257
258 fn auth(&self, action: &str) -> Url {
259 self.route(&format!(
260 "/v1/projects/{}/auth/{action}",
261 self.config.project_public_id
262 ))
263 }
264
265 fn route(&self, suffix: &str) -> Url {
266 let mut target = self.base.clone();
267 target.set_path(&format!(
268 "{}{suffix}",
269 self.base.path().trim_end_matches('/')
270 ));
271 target
272 }
273
274 fn redirect(&self, value: &str) -> Result<(), OwlAuthError> {
275 let invalid = || local("invalid_configuration", "Invalid application redirect URI");
276 let allow_http = self.config.allow_insecure_http && self.base.scheme() == "http";
277 let url = secure_url(value, allow_http).ok_or_else(invalid)?;
278 if url
279 .query_pairs()
280 .any(|(key, _)| matches!(key.as_ref(), "state" | "handoff_code"))
281 {
282 return Err(invalid());
283 }
284 Ok(())
285 }
286
287 async fn navigation(
288 &self,
289 action: &str,
290 body: Value,
291 bearer: Option<&str>,
292 ) -> Result<HostedNavigation, OwlAuthError> {
293 let result: HostedNavigation = self
294 .json(self.auth(action), 201, Some(body), bearer)
295 .await?;
296 let safe = secure_url(&result.hosted_url, self.config.allow_insecure_http);
297 if !safe.is_some_and(|url| url.origin() == self.base.origin()) {
298 return Err(OwlAuthError::new(
299 "invalid_response",
300 "Invalid Runtime hosted URL",
301 Some(201),
302 ));
303 }
304 Ok(result)
305 }
306
307 async fn json<T: DeserializeOwned>(
308 &self,
309 url: Url,
310 expected: u16,
311 body: Option<Value>,
312 bearer: Option<&str>,
313 ) -> Result<T, OwlAuthError> {
314 let bytes = self.request(url, expected, body.as_ref(), bearer).await?;
315 serde_json::from_slice(&bytes).map_err(|_| invalid_response(expected))
316 }
317
318 async fn request(
319 &self,
320 url: Url,
321 expected: u16,
322 body: Option<&Value>,
323 bearer: Option<&str>,
324 ) -> Result<Vec<u8>, OwlAuthError> {
325 let request = HttpRequest {
326 method: if body.is_some() || expected == 204 {
327 HttpMethod::Post
328 } else {
329 HttpMethod::Get
330 },
331 url,
332 bearer: bearer.map(str::to_owned),
333 body: body.map(|v| v.to_string().into_bytes()),
334 timeout: self.config.timeout,
335 };
336 let response = tokio::time::timeout(self.config.timeout, self.transport.send(request))
337 .await
338 .map_err(|_| timeout())??;
339 let status = response.status;
340 if (300..400).contains(&status) {
341 return Err(OwlAuthError::new(
342 "redirect_rejected",
343 "Runtime API redirect rejected",
344 Some(status),
345 ));
346 }
347 if response.body.len() > MAX_BODY {
348 return Err(too_large(status));
349 }
350 if status == expected {
351 return Ok(response.body);
352 }
353 if (200..300).contains(&status) {
354 return Err(invalid_response(status));
355 }
356 let mut secrets: Vec<_> = bearer.into_iter().collect();
357 if let Some(body) = body {
358 secrets.extend(
359 ["refresh_token", "pkce_verifier", "handoff_code", "state"]
360 .iter()
361 .filter_map(|k| body[k].as_str()),
362 );
363 }
364 Err(OwlAuthError::http(status, &response.body, &secrets))
365 }
366}
367
368#[must_use]
370pub fn pkce_challenge(verifier: &str) -> String {
371 URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
372}
373
374pub fn validate_callback(
379 callback: &str,
380 pending: &PendingLogin,
381) -> Result<ValidatedCallback, OwlAuthError> {
382 let invalid = || local("invalid_callback", "Invalid login callback");
383 if callback.chars().any(unsafe_url_char) {
384 return Err(invalid());
385 }
386 let actual;
387 let query = if let Some(query) = callback.strip_prefix('?') {
388 query
389 } else if callback
390 .split_once('=')
391 .is_some_and(|(key, _)| !key.is_empty() && !key.contains([':', '/', '?']))
392 {
393 callback
394 } else {
395 actual = absolute_url(callback).ok_or_else(invalid)?;
396 let expected = absolute_url(&pending.redirect_uri).ok_or_else(invalid)?;
397 if actual.origin() != expected.origin() || actual.path() != expected.path() {
398 return Err(invalid());
399 }
400 actual.query().unwrap_or_default()
401 };
402 let mut state = None;
403 let mut code = None;
404 let mut errors = 0;
405 let mut has_error = false;
406 for (key, value) in url::form_urlencoded::parse(query.as_bytes()) {
407 match key.as_ref() {
408 "state" if state.is_none() => state = Some(value),
409 "handoff_code" if code.is_none() => code = Some(value),
410 "state" | "handoff_code" => return Err(invalid()),
411 "error" => {
412 errors += 1;
413 has_error = !value.is_empty();
414 }
415 _ => {}
416 }
417 }
418 let state = state.filter(|v| !v.is_empty()).ok_or_else(invalid)?;
419 if !bool::from(pending.state.as_bytes().ct_eq(state.as_bytes())) {
420 return Err(local(
421 "state_mismatch",
422 "Login callback state does not match",
423 ));
424 }
425 match code {
426 Some(value) if !value.is_empty() => Ok(ValidatedCallback {
427 handoff_code: value.into_owned(),
428 }),
429 None if errors == 1 && has_error => {
430 Err(local("callback_error", "Login callback reported an error"))
431 }
432 _ => Err(invalid()),
433 }
434}
435
436fn nonce() -> Result<String, OwlAuthError> {
437 let mut bytes = [0; 32];
438 getrandom::fill(&mut bytes)
439 .map_err(|_| local("entropy_unavailable", "Secure randomness unavailable"))?;
440 Ok(URL_SAFE_NO_PAD.encode(bytes))
441}
442
443fn unsafe_url_char(value: char) -> bool {
444 value.is_whitespace() || value.is_ascii_control() || matches!(value, '\\' | '#')
445}
446
447fn absolute_url(value: &str) -> Option<Url> {
448 let (scheme, rest) = value.split_once("://")?;
449 let authority = rest.split(['/', '?']).next()?;
450 if !(scheme.eq_ignore_ascii_case("https") || scheme.eq_ignore_ascii_case("http"))
451 || authority.is_empty()
452 || authority.contains('@')
453 || value.chars().any(unsafe_url_char)
454 {
455 return None;
456 }
457 Url::parse(value).ok().filter(|url| url.port() != Some(0))
458}
459
460fn secure_url(value: &str, allow_http: bool) -> Option<Url> {
461 let url = absolute_url(value)?;
462 if url.scheme() == "https" {
463 return Some(url);
464 }
465 let authority = value.split_once("://")?.1.split(['/', '?']).next()?;
467 let host = if let Some((_, suffix)) = authority.split_once(']') {
468 authority.strip_suffix(suffix)?
469 } else {
470 authority.split(':').next()?
471 };
472 (allow_http
473 && (host.eq_ignore_ascii_case("localhost") || matches!(host, "127.0.0.1" | "[::1]")))
474 .then_some(url)
475}
476
477fn local(code: &str, message: &str) -> OwlAuthError {
478 OwlAuthError::new(code, message, None)
479}
480fn invalid_response(status: u16) -> OwlAuthError {
481 OwlAuthError::new("invalid_response", "Invalid Runtime response", Some(status))
482}