owlauth-client 0.4.0

Rust Project Auth client for OwlAuth
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
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,
};

/// Options for one Runtime Project and Application.
#[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),
        }
    }
}

/// Storage-free Project Auth Runtime client.
#[derive(Clone)]
pub struct Client {
    config: ClientConfig,
    base: Url,
    transport: Arc<dyn Transport>,
}

impl Client {
    /// Construct a client using the built-in HTTP transport.
    ///
    /// # Errors
    /// Returns an error for invalid configuration or HTTP transport setup failure.
    pub fn new(config: ClientConfig) -> Result<Self, OwlAuthError> {
        Self::with_transport(config, Arc::new(DefaultTransport::new()?))
    }

    /// Construct a client with an application-supplied transport.
    ///
    /// # Errors
    /// Returns an error for invalid configuration.
    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,
        })
    }

    /// Fetch the public configuration for the configured Application.
    ///
    /// # Errors
    /// Returns a Runtime, transport, or response validation error.
    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)
    }

    /// Fetch the configured Project's public signing keys.
    ///
    /// # Errors
    /// Returns a Runtime, transport, or response validation error.
    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
    }

    /// Generate fresh PKCE and state and start one hosted login.
    ///
    /// # Errors
    /// Returns an error if the redirect URI is invalid, secure entropy is unavailable, or Runtime fails.
    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,
        })
    }

    /// Exchange an already validated handoff code with its original verifier.
    ///
    /// # Errors
    /// Returns a Runtime, transport, or response validation error.
    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
    }

    /// Validate the callback against the pending login before exchanging the handoff.
    ///
    /// # Errors
    /// Returns callback validation, Runtime, transport, or response validation errors.
    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
    }

    /// Rotate the session's tokens.
    ///
    /// # Errors
    /// Returns a Runtime, transport, or response validation error.
    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
    }

    /// Fetch the user projected into this Application.
    ///
    /// # Errors
    /// Returns a Runtime, transport, or response validation error.
    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)
    }

    /// Revoke the Application session.
    ///
    /// # Errors
    /// Returns a Runtime or transport error.
    pub async fn logout(&self, access_token: &str) -> Result<(), OwlAuthError> {
        self.request(self.auth("sessions/logout"), 204, None, Some(access_token))
            .await?;
        Ok(())
    }

    /// Prepare hosted browser logout. The caller navigates to the URL returned.
    ///
    /// # Errors
    /// Returns redirect URI validation, Runtime, transport, or response validation errors.
    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))
    }
}

/// Compute the unpadded base64url SHA-256 challenge for a PKCE verifier.
#[must_use]
pub fn pkce_challenge(verifier: &str) -> String {
    URL_SAFE_NO_PAD.encode(Sha256::digest(verifier.as_bytes()))
}

/// Validate an absolute callback URL or an application-supplied query string.
///
/// # Errors
/// Returns an error for malformed, unbound, or error callbacks.
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);
    }
    // Match the literal loopback host rather than a normalized numeric alias.
    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))
}