laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
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
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
//! Social login, which lets users log in with their Google, GitHub, or Microsoft account, or with
//! any OAuth 2.0 provider that the application adds with [`Drivers::extend`].
//!
//! Many users would rather sign in with an account they already have than make a new password.
//! This module sends them to the provider and returns their verified profile, and the
//! [social login guide](https://github.com/laravel/rust-framework/blob/0.x/docs/social-login.md)
//! shows how to find or create the matching user.
//!
//! Set a provider's client ID and secret, as [`config::social`](crate::config::social) describes.
//! Then add two routes in the `web` group, which keeps the login's state in the session. The
//! first route sends the user to the provider, and the second receives the user back with their
//! profile:
//!
//! ```no_run
//! use laravel::auth::social::{self, Provider};
//! use laravel::http::Redirect;
//! use laravel::routing::Params;
//!
//! pub async fn redirect(Params(provider): Params<Provider>) -> laravel::Result<Redirect> {
//!     social::redirect(provider)
//! }
//!
//! pub async fn callback(Params(provider): Params<Provider>) -> laravel::Result<Redirect> {
//!     let profile = social::user(provider).await?;
//!     // Find or create the user by `profile.provider` and `profile.id`, then log them in.
//!     Ok(Redirect::to("/dashboard"))
//! }
//! ```
//!
//! The callback's route is `/auth/{provider}/callback` unless the provider's `*_REDIRECT_URI`
//! names another URI. In tests, [`fake`] replaces the providers.

mod drivers;
mod fake;
mod providers;

use crate::session::SessionInternals as _;
use std::borrow::Cow;
use std::collections::HashMap;
use std::fmt;
use std::sync::LazyLock;

use base64::Engine as _;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use subtle::ConstantTimeEq;
use url::Url;

pub(crate) use self::drivers::Registered;
use self::drivers::Registration;
pub use self::drivers::{Driver, Drivers, Profile, Tokens};
pub(crate) use self::fake::Fakes;
pub use self::fake::{FakeUser, SocialFake, fake};
use crate::config::social::{Credentials, Social};
use crate::context::{Context, Internals};
use crate::http::Redirect;
use crate::http::client::Client;
use crate::session::Session;
use crate::time::Timestamp;

static CLIENT: LazyLock<Client> = LazyLock::new(Client::for_provider);

/// The parameters social login sets on the authorization URL itself.
const RESERVED: [&str; 7] = [
    "client_id",
    "redirect_uri",
    "response_type",
    "scope",
    "state",
    "code_challenge",
    "code_challenge_method",
];

/// The name of a provider that users can log in with, such as `google` or `gitlab`.
///
/// Laravel registers [`GOOGLE`](Self::GOOGLE), [`GITHUB`](Self::GITHUB), and
/// [`MICROSOFT`](Self::MICROSOFT), and an application adds others with
/// [`Drivers::extend`]. As a route parameter, a provider parses from any name, and
/// [`redirect`] and [`user`] respond with a `404` for a name that no provider is registered
/// under. In a model, a provider is stored as its name.
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
pub struct Provider(Cow<'static, str>);

impl Provider {
    /// Google accounts, through OpenID Connect.
    pub const GOOGLE: Self = Self(Cow::Borrowed("google"));
    /// GitHub accounts, through OAuth.
    pub const GITHUB: Self = Self(Cow::Borrowed("github"));
    /// Microsoft work, school, and personal accounts, through OpenID Connect.
    pub const MICROSOFT: Self = Self(Cow::Borrowed("microsoft"));

    /// A provider by name, such as `gitlab`.
    pub fn new(name: impl Into<Cow<'static, str>>) -> Self {
        Self(name.into())
    }

    /// The provider's name.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl From<&'static str> for Provider {
    fn from(name: &'static str) -> Self {
        Self::new(name)
    }
}

impl From<String> for Provider {
    fn from(name: String) -> Self {
        Self::new(name)
    }
}

impl From<&Provider> for Provider {
    fn from(provider: &Provider) -> Self {
        provider.clone()
    }
}

impl PartialEq<str> for Provider {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<&str> for Provider {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == *other
    }
}

impl fmt::Display for Provider {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}

#[cfg(feature = "database")]
mod database {
    use super::Provider;
    use crate::db::{AnyRow, Decode, JsonElement, Nullable, Value};

    impl JsonElement for Provider {}

    impl Nullable for Provider {
        fn null() -> Value<'static> {
            Value::Text(None)
        }
    }

    impl From<Provider> for Value<'_> {
        fn from(provider: Provider) -> Self {
            Self::Text(Some(provider.0))
        }
    }

    impl<'a> From<&'a Provider> for Value<'a> {
        fn from(provider: &'a Provider) -> Self {
            Self::Text(Some(std::borrow::Cow::Borrowed(provider.as_str())))
        }
    }

    impl<'a> From<&&'a Provider> for Value<'a> {
        fn from(provider: &&'a Provider) -> Self {
            Self::Text(Some(std::borrow::Cow::Borrowed(provider.as_str())))
        }
    }

    impl Decode for Provider {
        fn decode(row: &AnyRow, index: usize) -> crate::Result<Self> {
            String::decode(row, index).map(Self::from)
        }
    }
}

/// The profile of a user who logged in with a provider.
#[derive(Debug, Clone)]
pub struct User {
    /// The provider the user logged in with.
    pub provider: Provider,
    /// The user's ID at the provider, which never changes. Look users up by this ID together
    /// with `provider`.
    pub id: String,
    /// The user's full name.
    pub name: Option<String>,
    /// The user's handle, such as a GitHub login.
    pub nickname: Option<String>,
    /// The user's email address.
    pub email: Option<Email>,
    /// The URL of the user's avatar.
    pub avatar: Option<String>,
    /// The access token, for calling the provider's API as the user.
    pub token: Token,
    /// The profile exactly as the provider sent it: the ID token's claims for Google and
    /// Microsoft, the `/user` response for GitHub, or what a [`Driver`] put in
    /// [`Profile::raw`].
    pub raw: serde_json::Value,
}

impl User {
    /// The user's email address, or `None` unless the provider verified that the user owns it.
    /// Match existing accounts by this address, never by an unverified one.
    pub fn verified_email(&self) -> Option<&str> {
        self.email
            .as_ref()
            .filter(|email| email.verified)
            .map(|email| email.address.as_str())
    }
}

/// An email address, and whether the provider verified that the user owns it.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Email {
    /// The address.
    pub address: String,
    /// Whether the provider verified the address.
    pub verified: bool,
}

/// The tokens that the provider issued. Debug output never includes them, but serialized output
/// does, so [encrypt](crate::crypt::encrypt) a token before you store it.
#[derive(Clone, Serialize, Deserialize)]
pub struct Token {
    /// The access token.
    pub access: String,
    /// The refresh token, when the provider issued one.
    pub refresh: Option<String>,
    /// When the access token expires, if the provider said.
    pub expires_at: Option<Timestamp>,
    /// The scopes the provider granted.
    pub scopes: Vec<String>,
}

#[cfg(feature = "database")]
impl crate::crypt::Encryptable for Token {
    fn __encrypt(&self, encrypter: &crate::crypt::Encrypter) -> crate::Result<String> {
        crate::crypt::__encrypt_json(self, encrypter)
    }

    fn __decrypt(payload: &str, encrypter: &crate::crypt::Encrypter) -> crate::Result<(Self, bool)> {
        crate::crypt::__decrypt_json(payload, encrypter)
    }

    fn __same(&self, other: &Self) -> bool {
        crate::crypt::__same_json(self, other)
    }
}

impl fmt::Debug for Token {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("Token")
            .field("access", &"[redacted]")
            .field("refresh", &self.refresh.as_ref().map(|_| "[redacted]"))
            .field("expires_at", &self.expires_at)
            .field("scopes", &self.scopes)
            .finish()
    }
}

/// Why a social login failed. When returned with `?`, each variant responds with its own status.
#[derive(Debug, thiserror::Error, crate::errors::Status)]
pub enum Error {
    /// The provider's client ID or secret isn't set. The response is a `404` that says only "Not
    /// Found", so visitors don't learn how the application is configured. A warning in the log
    /// names the variables to set.
    #[error("Not Found")]
    #[status(404)]
    NotConfigured(Provider),
    /// No provider is registered under the name, such as a mistyped `{provider}` in the URL. The
    /// response is a `404`.
    #[error("Not Found")]
    #[status(404)]
    UnknownProvider(Provider),
    /// The user cancelled the login at the provider. The response is a `403`.
    #[error("The login was cancelled.")]
    #[status(403)]
    Denied,
    /// The callback doesn't belong to a login that this session started. Its state doesn't
    /// match, the login already finished, or the provider sent no code. The response is a `403`.
    #[error("The login has expired. Please try again.")]
    #[status(403)]
    InvalidState,
    /// The provider reported an error or sent a response that can't be trusted. The response is
    /// a `502`.
    #[error("{0}")]
    #[status(502)]
    Provider(String),
}

/// Sends the user to the provider to log in, with the provider's default scopes. For an Inertia
/// visit, such as one from a `<Link>`, it responds with a `409` and `X-Inertia-Location`, so that
/// the browser goes to the provider with a full page load.
///
/// # Errors
///
/// Fails with [`Error::UnknownProvider`] when no provider is registered under the name,
/// [`Error::NotConfigured`] when the provider's credentials aren't set, and with a server error
/// when the request has no session. Only routes in the `web` group start a session.
///
/// # Panics
///
/// Panics outside an application context.
#[track_caller]
pub fn redirect(provider: impl Into<Provider>) -> crate::Result<Redirect> {
    self::provider(provider).redirect()
}

/// Starts a redirect to the provider with more scopes or authorization parameters.
///
/// ```no_run
/// use laravel::auth::social::{self, Provider};
///
/// # fn example() -> laravel::Result<()> {
/// social::provider(Provider::GITHUB)
///     .scopes(["repo"])
///     .with([("allow_signup", "false")])
///     .redirect()?;
/// # Ok(()) }
/// ```
pub fn provider(provider: impl Into<Provider>) -> PendingRedirect {
    PendingRedirect {
        provider: provider.into(),
        scopes: Vec::new(),
        parameters: Vec::new(),
    }
}

/// A pending redirect to a provider, with its scopes and parameters. [`provider`] returns one.
#[derive(Debug, Clone)]
#[must_use = "a pending redirect does nothing until `redirect()` builds it"]
pub struct PendingRedirect {
    provider: Provider,
    scopes: Vec<String>,
    parameters: Vec<(String, String)>,
}

impl PendingRedirect {
    /// Asks for these scopes in addition to the provider's defaults.
    pub fn scopes<S: Into<String>>(mut self, scopes: impl IntoIterator<Item = S>) -> Self {
        self.scopes.extend(scopes.into_iter().map(Into::into));
        self
    }

    /// Adds parameters to the authorization URL, such as `prompt` or `login_hint`.
    ///
    /// # Panics
    ///
    /// Panics when social login sets a parameter itself: `client_id`, `redirect_uri`,
    /// `response_type`, `scope`, `state`, `code_challenge`, or `code_challenge_method`.
    #[track_caller]
    pub fn with<K: Into<String>, V: Into<String>>(mut self, parameters: impl IntoIterator<Item = (K, V)>) -> Self {
        for (name, value) in parameters {
            let name = name.into();
            assert!(
                !RESERVED.contains(&name.as_str()),
                "social login sets the `{name}` parameter itself"
            );

            self.parameters.push((name, value.into()));
        }

        self
    }

    /// Sends the user to the provider to log in.
    ///
    /// # Errors
    ///
    /// Fails when [`redirect`] would fail.
    ///
    /// # Panics
    ///
    /// Panics outside an application context.
    #[track_caller]
    pub fn redirect(self) -> crate::Result<Redirect> {
        let context = Context::expect("laravel::auth::social::redirect()");
        let driver = registration(&context, &self.provider)?;
        if let Some(fake) = Fakes::of(&context).active() {
            let url = format!("https://social.fake/{}/authorize", self.provider);
            fake.record_redirect(self.provider);
            return Ok(leave_for(&context, url));
        }

        let social = &context.config().social;
        let credentials = credentials(social, &self.provider, &driver.label)?;
        let session = Session::of(&context).ok_or_else(|| {
            crate::error::fail("social login needs a session: use it in routes of the `web` group, which start one")
        })?;
        let login = PendingLogin {
            state: crate::str::random(40),
            verifier: crate::str::random(64),
            callback_url: callback_url(&self.provider, credentials),
        };
        let url = self.authorize_url(driver, credentials, &login)?;

        session.put(&session_key(&self.provider), &login);
        Ok(leave_for(&context, url))
    }

    /// The provider's authorization URL for the login, with the driver's scopes and then these.
    fn authorize_url(
        &self,
        driver: &Registration,
        credentials: &Credentials,
        login: &PendingLogin,
    ) -> Result<String, Error> {
        let mut scopes: Vec<&str> = driver.scopes().to_vec();
        for scope in &self.scopes {
            if !scopes.contains(&scope.as_str()) {
                scopes.push(scope);
            }
        }
        let challenge = URL_SAFE_NO_PAD.encode(Sha256::digest(login.verifier.as_bytes()));

        let mut url = Url::parse(&driver.authorize_url())
            .map_err(|error| Error::Provider(format!("{}'s authorization URL is invalid: {error}", driver.label)))?;
        url.query_pairs_mut()
            .append_pair("client_id", &credentials.client_id)
            .append_pair("redirect_uri", &login.callback_url)
            .append_pair("response_type", "code")
            .append_pair("scope", &scopes.join(" "))
            .append_pair("state", &login.state)
            .append_pair("code_challenge", &challenge)
            .append_pair("code_challenge_method", "S256")
            .extend_pairs(&self.parameters);

        Ok(url.into())
    }
}

/// A redirect to the provider. An Inertia visit fetches responses in the background and can't
/// follow a redirect to another site, so it gets a `409` with `X-Inertia-Location` instead.
/// Inertia's client answers that response with a full page load.
fn leave_for(context: &Context, url: String) -> Redirect {
    if context.request().is_some_and(|request| request.is_inertia_visit()) {
        return Redirect::to(url.clone())
            .status(409)
            .with_header("x-inertia-location", url);
    }

    Redirect::to(url)
}

/// Returns the profile of the user that the provider sent back, on the callback route. Each
/// login's callback works once.
///
/// # Errors
///
/// Fails with [`Error::Denied`] when the user cancelled, [`Error::InvalidState`] when the
/// callback doesn't match a login that this session started, [`Error::UnknownProvider`] when no
/// provider is registered under the name, [`Error::NotConfigured`] when the provider's
/// credentials aren't set, and [`Error::Provider`] when the provider reports an error or its
/// response fails verification.
///
/// # Panics
///
/// Panics outside an application context, or when the request has no session. Only routes in
/// the `web` group start a session.
pub async fn user(provider: impl Into<Provider>) -> Result<User, Error> {
    let provider = provider.into();
    let context = Context::expect("laravel::auth::social::user()");
    let driver = registration(&context, &provider)?;
    if let Some(fake) = Fakes::of(&context).active() {
        return fake.user(&provider);
    }

    let config = context.config();
    let credentials = credentials(&config.social, &provider, &driver.label)?;
    let (login, code) = callback(&context, &provider, &driver.label)?;

    let response = exchange(driver, credentials, &login, &code).await?;
    let tokens = Tokens {
        label: &driver.label,
        client_id: &credentials.client_id,
        response: &response,
    };
    let profile = driver.user(&tokens).await?;
    if profile.id.is_empty() {
        return Err(Error::Provider(format!("{}'s profile has no ID", driver.label)));
    }

    Ok(User {
        provider,
        id: profile.id,
        name: profile.name,
        nickname: profile.nickname,
        email: profile.email,
        avatar: profile.avatar,
        token: response.token(),
        raw: profile.raw,
    })
}

/// The driver registered under the provider's name.
fn registration<'a>(context: &'a Context, provider: &Provider) -> Result<&'a Registration, Error> {
    context
        .part::<Registered>()
        .get(provider)
        .ok_or_else(|| Error::UnknownProvider(provider.clone()))
}

/// Checks the callback's query against the session's pending login, which it pulls so each state
/// works once, and returns the login with the callback's code.
fn callback(context: &Context, provider: &Provider, label: &str) -> Result<(PendingLogin, String), Error> {
    let Some(session) = Session::of(context) else {
        panic!("social login needs a session: use it in routes of the `web` group, which start one");
    };
    let login: Option<PendingLogin> = session.pull(&session_key(provider));
    let query: HashMap<String, String> = context.request().map_or_else(HashMap::new, |request| {
        url::form_urlencoded::parse(request.query().as_bytes())
            .into_owned()
            .collect()
    });

    if let Some(error) = query.get("error") {
        if error == "access_denied" {
            return Err(Error::Denied);
        }
        let description = query
            .get("error_description")
            .map(|description| format!(": {description}"))
            .unwrap_or_default();
        return Err(Error::Provider(format!(
            "{label} returned `{error}` to the callback{description}"
        )));
    }

    let login = login
        .filter(|login| {
            query
                .get("state")
                .is_some_and(|state| bool::from(state.as_bytes().ct_eq(login.state.as_bytes())))
        })
        .ok_or(Error::InvalidState)?;
    let code = query.get("code").cloned().ok_or(Error::InvalidState)?;

    Ok((login, code))
}

/// Exchanges the callback's code for the provider's tokens.
async fn exchange(
    driver: &Registration,
    credentials: &Credentials,
    login: &PendingLogin,
    code: &str,
) -> Result<TokenResponse, Error> {
    let label = &driver.label;
    let response = CLIENT
        .post(driver.token_url())
        .accept_json()
        .form([
            ("grant_type", "authorization_code"),
            ("code", code),
            ("redirect_uri", &login.callback_url),
            ("client_id", &credentials.client_id),
            ("client_secret", &credentials.client_secret),
            ("code_verifier", &login.verifier),
        ])
        .send()
        .await
        .map_err(|error| Error::Provider(format!("couldn't reach {label}'s token endpoint: {error}")))?;

    let body: serde_json::Value = response.json().unwrap_or_default();
    if let Some(error) = body.get("error").and_then(serde_json::Value::as_str) {
        let description = body
            .get("error_description")
            .and_then(serde_json::Value::as_str)
            .map(|description| format!(": {description}"))
            .unwrap_or_default();
        return Err(Error::Provider(format!(
            "{label} refused the token exchange with HTTP {} and `{error}`{description}",
            response.status().as_u16(),
        )));
    }
    if !response.successful() {
        return Err(Error::Provider(format!(
            "{label} refused the token exchange with HTTP {}: {}",
            response.status().as_u16(),
            response.text()
        )));
    }

    serde_json::from_value(body)
        .map_err(|error| Error::Provider(format!("{label}'s token response is invalid: {error}")))
}

/// The token endpoint's response.
#[derive(Deserialize)]
struct TokenResponse {
    access_token: String,
    refresh_token: Option<String>,
    expires_in: Option<i64>,
    scope: Option<String>,
    id_token: Option<String>,
}

impl TokenResponse {
    fn token(&self) -> Token {
        let expires_at = self.expires_in.and_then(|seconds| {
            crate::now()
                .timestamp()
                .checked_add(jiff::SignedDuration::from_secs(seconds))
                .ok()
        });

        Token {
            access: self.access_token.clone(),
            refresh: self.refresh_token.clone(),
            expires_at,
            scopes: self
                .scope
                .as_deref()
                .unwrap_or_default()
                .split([' ', ','])
                .filter(|scope| !scope.is_empty())
                .map(str::to_owned)
                .collect(),
        }
    }
}

/// A login waiting for its callback, kept in the session.
#[derive(Serialize, Deserialize)]
struct PendingLogin {
    state: String,
    verifier: String,
    callback_url: String,
}

/// The provider's OAuth client, or [`Error::NotConfigured`] with a warning that names the
/// variables to set.
fn credentials<'a>(social: &'a Social, provider: &Provider, label: &str) -> Result<&'a Credentials, Error> {
    social.client(provider.as_str()).ok_or_else(|| {
        let prefix = Social::env_prefix(provider.as_str());
        tracing::warn!("set {prefix}_CLIENT_ID and {prefix}_CLIENT_SECRET to log in with {label}");

        Error::NotConfigured(provider.clone())
    })
}

fn session_key(provider: &Provider) -> String {
    format!("social.{provider}")
}

#[track_caller]
fn callback_url(provider: &Provider, credentials: &Credentials) -> String {
    match &credentials.redirect {
        Some(redirect) => crate::url::to(redirect),
        None => crate::url::to(&format!("/auth/{provider}/callback")),
    }
}